|
| 1 | +import random |
| 2 | + |
| 3 | +def generate_maze(size, player, goal): |
| 4 | + """Generates a maze grid.""" |
| 5 | + maze = [['_' for _ in range(size)] for _ in range(size)] |
| 6 | + maze[player[0]][player[1]] = 'P' # Player position |
| 7 | + maze[goal[0]][goal[1]] = 'G' # Goal position |
| 8 | + count = {x:0 for x in range(size)} |
| 9 | + for _ in range(size * 2): # Add obstacles |
| 10 | + x,y = random.randint(0,size-1),random.randint(0,size-1) |
| 11 | + if [x,y]!=player and [x,y]!=goal and count[x]<size-1: |
| 12 | + maze[x][y] = '#' |
| 13 | + return maze |
| 14 | + |
| 15 | +def display_maze(maze): |
| 16 | + """Prints the maze.""" |
| 17 | + for row in maze: |
| 18 | + print(' '.join(row)) |
| 19 | + print() |
| 20 | + |
| 21 | +def move_player(maze, player, direction): |
| 22 | + """Moves the player in the specified direction.""" |
| 23 | + x, y = player |
| 24 | + maze[x][y] = '_' # Clear current position |
| 25 | + if direction == 'w' and x > 0: x -= 1 # Move up |
| 26 | + elif direction == 's' and x < len(maze) - 1: x += 1 # Move down |
| 27 | + elif direction == 'a' and y > 0: y -= 1 # Move left |
| 28 | + elif direction == 'd' and y < len(maze[0]) - 1: y += 1 # Move right |
| 29 | + |
| 30 | + if maze[x][y] != '#': # Check for obstacles |
| 31 | + player[0], player[1] = x, y |
| 32 | + maze[player[0]][player[1]] = 'P' # Update position |
| 33 | + return player |
| 34 | + |
| 35 | +def check_win(player, goal): |
| 36 | + """Checks if the player reached the goal.""" |
| 37 | + return player == goal |
| 38 | + |
| 39 | +def play_game(): |
| 40 | + """Main game logic.""" |
| 41 | + size = 6 # Maze size |
| 42 | + player = [0, 0] # Starting position |
| 43 | + goal = [size - 1, size - 1] # Goal position |
| 44 | + print(goal) |
| 45 | + maze = generate_maze(size, player, goal) |
| 46 | + |
| 47 | + print("Welcome to the Maze Game!") |
| 48 | + print("Navigate using 'w', 'a', 's', 'd' (up, left, down, right). Reach the goal (G) to win!") |
| 49 | + display_maze(maze) |
| 50 | + |
| 51 | + while True: |
| 52 | + move = input("Enter your move (w/a/s/d): ").lower() |
| 53 | + if move not in ['w', 'a', 's', 'd']: |
| 54 | + print("Invalid move! Use 'w', 'a', 's', or 'd'.") |
| 55 | + continue |
| 56 | + |
| 57 | + player = move_player(maze, player, move) |
| 58 | + display_maze(maze) |
| 59 | + |
| 60 | + if check_win(player, goal): |
| 61 | + print("Congratulations! You've reached the goal!") |
| 62 | + break |
| 63 | + |
| 64 | +# Start the game |
| 65 | +play_game() |
0 commit comments