diff --git a/23 Move a player part 1/exercise-01.py b/23 Move a player part 1/exercise-01.py new file mode 100644 index 0000000..bdcce9a --- /dev/null +++ b/23 Move a player part 1/exercise-01.py @@ -0,0 +1,95 @@ +# create a board game grid 8x8 +# number rows and columns +# add player location in bottom left (*) +# print out the grid +# add a move function that takes in the grid and returns the new grid + +class Board: + def __init__(self, rows, columns): + self.rows = rows + self.columns = columns + self.grid = [["O" for i in range(columns)] for j in range(rows)] + self.player_location = (7, 0) # bottom left + + def format_grid(self): + header = " " + " ".join(f"{j:>2}" for j in range(self.columns)) + "\n" + result = header + for i in range(self.rows): + row_cells = [] + for j in range(self.columns): + if (i, j) == self.player_location: + row_cells.append(" *") + else: + row_cells.append(f" {self.grid[i][j]}") + result += f"{i:>2} " + " ".join(row_cells) + "\n" + return result + + def move(self, x, y): + """ moves x right and y up """ + # bottom left = 7, 0 + # bottom right = 7, 7 + # top left = 0, 0 + # top right = 0, 7 + + row, col = self.player_location + + self.grid[row][col] = "O" # clear previous location + + new_col = col + x + new_row = row - y # subtract, since row 0 is the top + + if new_col < 0 or new_col > self.columns - 1: + raise ValueError("Invalid X coordinate") + elif new_row < 0 or new_row > self.rows - 1: + raise ValueError("Invalid Y coordinate") + + self.grid[new_row][new_col] = "*" + self.player_location = (new_row, new_col) + + return self.player_location + +board = Board(8, 8) + +def get_move(board): + raw = input("Enter direction and magnitude (u, d, l, r) (q to quit): ").strip().lower() + if not raw: + return get_move(board) # or handle empty input as you see fit + + letter, mag_str = raw[0], raw[1:].strip() + if letter == "q": + return None + + try: + magnitude = int(mag_str) + except ValueError: + print("Invalid magnitude.") + return get_move(board) + + moves = { + "u": (0, magnitude), + "d": (0, -magnitude), + "l": (-magnitude, 0), + "r": (magnitude, 0), + } + + if letter not in moves: + print("Invalid direction.") + return get_move(board) + + return board.move(*moves[letter]) + +def main(): + while True: + try: + move = get_move(board) + + if move is None: + quit() + + print(board.format_grid()) + except ValueError as e: + print(e) + print("Please dont go out of bounds") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/23 Move a player part 1/task.png b/23 Move a player part 1/task.png new file mode 100644 index 0000000..e59efe0 Binary files /dev/null and b/23 Move a player part 1/task.png differ