import random import os import msvcrt # Constants EMPTY = " " PACMAN = "P" GHOST = "G" WALL = "#" COIN = "C" # Game settings WIDTH = 10 HEIGHT = 10 PACMAN_START_X = 1 PACMAN_START_Y = 1 GHOST_START_X = 8 GHOST_START_Y = 8 COIN_COUNT = 10 # Initialize the game board board = [[EMPTY for _ in range(WIDTH)] for _ in range(HEIGHT)] # Place Pac-Man, Ghost, and coins on the board board[PACMAN_START_Y][PACMAN_START_X] = PACMAN board[GHOST_START_Y][GHOST_START_X] = GHOST for _ in range(COIN_COUNT): x, y = random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1) while board[y][x] != EMPTY: x, y = random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1) board[y][x] = COIN # Function to print the game board def print_board(): os.system('cls' if os.name == 'nt' else 'clear') for row in board: print("".join(row)) # Function to move Pac-Man def move_pacman(dx, dy): x, y = get_pacman_position() new_x, new_y = x + dx, y + dy if ( 0 <= new_x < WIDTH and 0 <= new_y < HEIGHT and board[new_y][new_x] != WALL ): board[y][x] = EMPTY board[new_y][new_x] = PACMAN # Function to get Pac-Man's current position def get_pacman_position(): for y in range(HEIGHT): for x in range(WIDTH): if board[y][x] == PACMAN: return x, y # Main game loop while True: print_board() # Get user input for Pac-Man movement key = msvcrt.getch() if key == b'w': move_pacman(0, -1) elif key == b's': move_pacman(0, 1) elif key == b'a': move_pacman(-1, 0) elif key == b'd': move_pacman(1, 0) # Add win/lose conditions if get_pacman_position() == (GHOST_START_X, GHOST_START_Y): print("Game over! You were caught by the ghost!") break elif all(board[y][x] != COIN for y in range(HEIGHT) for x in range(WIDTH)): print("Congratulations! You collected all the coins!") break