Create Pacman Game using Python
This Python-based Pacman game project provides an engaging console interface using pygame for players to navigate through a maze, consume dots, and avoid ghosts.
The game simulates the classic Pacman experience. Players control Pacman’s movements using keyboard inputs, strategizing to maximize points while evading ghost enemies.
About Python Pacman Project
This project aims to create a simplified Pacman game using Python and the Pygame library. The game involves navigating Pacman through
a maze, eating pellets, avoiding ghosts and scoring points.
Prerequisites for Python Pacman Project
To implement this successfully, a basic understanding of Python programming and familiarity with PyGame are required. The PyGame library needs to be installed using pip before running the game.
Project File Structure
This project includes the following steps:
- Import necessary libraries and modules
- Initialize the game and set constants
- Define the game board
- Load assets
- Define game functions
- Create the game loop
Import necessary libraries and modules
import pygame
import sys
import random
- pygame: This is used to create the game interface and handle game. logic.sys: For system-specific parameters and functions.
- random: For randomizing ghost movements.
Initialize the game and set constants
pygame.init()
SCREEN_WIDTH = 560
SCREEN_HEIGHT = 620
CELL_SIZE = 20
FPS = 10
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Pac-Man")
font = pygame.font.SysFont('Arial', 18)
- pygame.init(): This line initializes the library.
- Variable Definitions: Defines variables for game window size, cell size,
- frame rate and colors (black,white and blue)
- screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)): This line creates the main game window. It sets window size based on variables defined earlier.
- pygame.display.set_caption(“Pac-Man”): This line sets the title of the game window to pac-man.
- font = pygame.font.SysFont(‘Arial’,18): This line is used to display text elements in game.
Define the game board
The game board is a 2D list representing the maze layout
board = [
"############################",
"#............##............#",
"#.####.#####.##.#####.####.#",
"#o####.#####.##.#####.####o#",
"#.####.#####.##.#####.####.#",
"#..........................#",
"#.####.##.########.##.####.#",
"#.####.##.########.##.####.#",
"#......##....##....##......#",
"######.##### ## #####.######",
"######.##### ## #####.######",
"######.## ##.######",
"######.## ###--### ##.######",
"######.## # # ##.######",
" ## # # ## ",
"######.## # # ##.######",
"######.## ######## ##.######",
"######.## ##.######",
"######.## ######## ##.######",
"######.## ######## ##.######",
"#............##............#",
"#.####.#####.##.#####.####.#",
"#.####.#####.##.#####.####.#",
"#o..##................##..o#",
"###.##.##.########.##.##.###",
"###.##.##.########.##.##.###",
"#......##....##....##......#",
"#.##########.##.##########.#",
"#.##########.##.##########.#",
"#..........................#",
"############################"
]
This code is the design of the maze used in the game.
Load Assets
Load images for pacman and ghosts
pacman_img = pygame.image.load('assets/pacman.png')
ghost_imgs = [
pygame.image.load('assets/yellow.png'),
pygame.image.load('assets/red.png'),
pygame.image.load('assets/blue.png'),
pygame.image.load('assets/green.png')
]
pacman_img = pygame.transform.scale(pacman_img, (CELL_SIZE, CELL_SIZE))
for i in range(len(ghost_imgs)):
ghost_imgs[i] = pygame.transform.scale(ghost_imgs[i], (CELL_SIZE, CELL_SIZE))
This code snippet loads images of Pacman and ghosts from our project’s assets folder and then resizes them to ensure that they all have the same dimensions and match the size of the cell of our maze.
Defining Game Functions
- Draw the game board
def draw_board():
for y, row in enumerate(board):
for x, cell in enumerate(row):
if cell == '#':
pygame.draw.rect(screen, BLUE, (x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE))
elif cell == '.':
pygame.draw.circle(screen, WHITE, (x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2), 3)
elif cell == 'o':
pygame.draw.circle(screen, WHITE, (x * CELL_SIZE + CELL_SIZE // 2, y * CELL_SIZE + CELL_SIZE // 2), 7)
This function reads the characters in the board list and translates them into visual elements on the screen. Walls are drawn as black rectangles, empty spaces are marked with small white circles, and unique elements are shown with larger white circles.
2. Draw pac-man and ghosts.
def draw_pacman():
screen.blit(pacman_img, (pacman_x * CELL_SIZE, pacman_y * CELL_SIZE))
def draw_ghosts():
for i, ghost in enumerate(ghosts):
screen.blit(ghost_imgs[i], (ghost['x'] * CELL_SIZE, ghost['y'] * CELL_SIZE))
These functions take the pac-man and ghost images and positions(stored in separate variables) and use them to draw these elements onto the pygame window at the correct locations within the maze.
3. Moving pac-man
def move_pacman():
global pacman_x, pacman_y, score
if pacman_direction == 'LEFT' and board[pacman_y][pacman_x - 1] != '#':
pacman_x -= 1
elif pacman_direction == 'RIGHT' and board[pacman_y][pacman_x + 1] != '#':
pacman_x += 1
elif pacman_direction == 'UP' and board[pacman_y - 1][pacman_x] != '#':
pacman_y -= 1
elif pacman_direction == 'DOWN' and board[pacman_y + 1][pacman_x] != '#':
pacman_y += 1
if board[pacman_y][pacman_x] == '.':
board[pacman_y] = board[pacman_y][:pacman_x] + ' ' + board[pacman_y][pacman_x + 1:]
score += 10
elif board[pacman_y][pacman_x] == 'o':
board[pacman_y] = board[pacman_y][:pacman_x] + ' ' + board[pacman_y][pacman_x + 1:]
score += 50
This function handles Pac-Man’s movement based on the current direction and checks for collisions with walls. It also updates the game board and scores based on whether Pac-Man eats a dot or collects a special element.
4. Moving ghosts
def move_ghosts():
for ghost in ghosts:
direction = random.choice(['LEFT', 'RIGHT', 'UP', 'DOWN'])
if direction == 'LEFT' and board[ghost['y']][ghost['x'] - 1] != '#':
ghost['x'] -= 1
elif direction == 'RIGHT' and board[ghost['y']][ghost['x'] + 1] != '#':
ghost['x'] += 1
elif direction == 'UP' and board[ghost['y'] - 1][ghost['x']] != '#':
ghost['y'] -= 1
elif direction == 'DOWN' and board[ghost['y'] + 1][ghost['x']] != '#':
ghost['y'] += 1
This function iterates through each ghost, randomly chooses a direction for it to move, and then checks if that move is valid based on the board layout. If it’s a valid move, the ghost’s position is updated in the ghost list
5. Checking Collisions
def check_collisions():
for ghost in ghosts:
if ghost['x'] == pacman_x and ghost['y'] == pacman_y:
return True
return False
This function checks each ghost in the list to see if its position overlaps with pac-man’s position. If there is a match, it signals a collision. If there are no matches after checking all ghosts, it indicates no collision has occurred.
6. Check if all pellets are eaten
def check_all_pellets_eaten():
for row in board:
if '.' in row or 'o' in row:
return False
return True
This function examines each row of the game board. If it finds any uneaten pellets in any row, it returns false. Otherwise, it returns true.
Create a game loop
The game loop handles events, updates the game state and renders the game.
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pacman_direction = 'LEFT'
elif event.key == pygame.K_RIGHT:
pacman_direction = 'RIGHT'
elif event.key == pygame.K_UP:
pacman_direction = 'UP'
elif event.key == pygame.K_DOWN:
pacman_direction = 'DOWN'
move_pacman()
move_ghosts()
if check_collisions():
print("Game Over!")
running = False
if check_all_pellets_eaten():
print("You Win!")
running = False
screen.fill(BLACK)
draw_board()
draw_pacman()
draw_ghosts()
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (10, SCREEN_HEIGHT - 30))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()
This code loop continuously checks for user input( controls Pac-Man’s direction), updates the game state( moves Pac-Man and ghosts, checks for collisions and win/lose conditions), redraws the game scene on the screen with updated positions and scores, and maintains a consistent frame rate for smooth gameplay.
Python Pacman Game Output
Conclusion
With this project, we have successfully created a Pac-Man game using the pygame library in Python. The project involves setting up the game environment, creating Pac-Man and ghosts, taking user inputs for moving Pac-Man, and implementing game logic for collision detection and score tracking. The game runs in a graphical window, and the player controls Pac-Man to navigate through a maze, collect pellets, and avoid ghosts.