write me a pacman game with maze in python using pygame. do not use images, all figures…
- User
write me a pacman game with maze in python using pygame. do not use images, all figures should be drawn in code itself
- Assistant
write me a pacman game with maze in python using pygame. do not use images, all figures should be drawn in code itself
Creating a Pac-Man game using Python’s pygame library is a fun project that involves setting up the game window, drawing the maze, handling user input for movement, and implementing game logic for collecting dots and avoiding ghosts. Below is a step-by-step guide along with the complete code to help you create a simple version of Pac-Man without using any external images.
Python Installed: Make sure you have Python 3.x installed on your machine.
pygame Installed: Install the pygame library if you haven't already. You can install it using pip:
pip install pygame
import pygame
import sys
# Initialize pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
CELL_SIZE = 20
# Colors
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
NAVY = (0, 0, 128)
YELLOW = (255, 255, 0)
WHITE = (255, 255, 255)
PINK = (255, 105, 180)
ORANGE = (255, 165, 0)
# Set up the display
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Pac-Man in Python")
# Clock to control the frame rate
clock = pygame.time.Clock()
FPS = 30
# Define the maze
# Legend:
# 'W' - Wall
# '.' - Dot
# ' ' - Empty space
maze = [
"WWWWWWWWWWWWWWWWWWWW",
"W........WW........W",
"W.WWW.WWW.WWW.WWW.WW",
"W.WWW.WWW.WWW.WWW.WW",
"W..................W",
"W.WWW.WW.WW.WW.WWW.W",
"W....WW....WW....W.W",
"WWWWWWWWWWWWWWWWWWWW"
]
# Calculate maze dimensions
maze_rows = len(maze)
maze_cols = len(maze[0])
maze_width = maze_cols * CELL_SIZE
maze_height = maze_rows * CELL_SIZE
# Starting position for Pac-Man
pacman_x = CELL_SIZE + CELL_SIZE // 2
pacman_y = CELL_SIZE + CELL_SIZE // 2
pacman_speed = 4
direction = 'RIGHT'
# To keep track of dots
dots = []
for row in range(maze_rows):
for col in range(maze_cols):
if maze[row][col] == '.':
dots.append((col * CELL_SIZE + CELL_SIZE // 2, row * CELL_SIZE + CELL_SIZE // 2))
# Score
score = 0
font = pygame.font.SysFont(None, 36)
def draw_maze():
for row in range(maze_rows):
for col in range(maze_cols):
cell = maze[row][col]
x = col * CELL_SIZE
y = row * CELL_SIZE
if cell == 'W':
pygame.draw.rect(screen, BLUE, (x, y, CELL_SIZE, CELL_SIZE))
# You can add more elements like power pellets here
def draw_dots():
for dot in dots:
pygame.draw.circle(screen, WHITE, dot, 3)
def draw_pacman(x, y, direction):
# Draw Pac-Man as a circle with a "mouth"
mouth_angle = 30 # degrees
if direction == 'RIGHT':
start_angle = mouth_angle
end_angle = -mouth_angle
elif direction == 'LEFT':
start_angle = 180 + mouth_angle
end_angle = -mouth_angle
elif direction == 'UP':
start_angle = 90 + mouth_angle
end_angle = -mouth_angle
elif direction == 'DOWN':
start_angle = 270 + mouth_angle
end_angle = -mouth_angle
else:
start_angle = 0
end_angle = 0
pygame.draw.circle(screen, YELLOW, (x, y), CELL_SIZE // 2 - 2)
pygame.draw.polygon(screen, BLACK, [
(x, y),
(
x + (CELL_SIZE // 2 - 2) * pygame.math.cos(pygame.math.radians(start_angle)),
y + (CELL_SIZE // 2 - 2) * pygame.math.sin(pygame.math.radians(start_angle))
),
(
x + (CELL_SIZE // 2 - 2) * pygame.math.cos(pygame.math.radians(end_angle)),
y + (CELL_SIZE // 2 - 2) * pygame.math.sin(pygame.math.radians(end_angle))
)
])
def is_wall(x, y):
col = x // CELL_SIZE
row = y // CELL_SIZE
if row < 0 or row >= maze_rows or col < 0 or col >= maze_cols:
return True
return maze[row][col] == 'W'
def handle_keys(current_direction):
keys = pygame.key.get_pressed()
new_direction = current_direction
if keys[pygame.K_LEFT]:
new_direction = 'LEFT'
elif keys[pygame.K_RIGHT]:
new_direction = 'RIGHT'
elif keys[pygame.K_UP]:
new_direction = 'UP'
elif keys[pygame.K_DOWN]:
new_direction = 'DOWN'
return new_direction
# Main game loop
running = True
while running:
clock.tick(FPS)
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle direction input
new_direction = handle_keys(direction)
# Calculate potential new position
temp_x, temp_y = pacman_x, pacman_y
if new_direction == 'LEFT':
temp_x -= pacman_speed
elif new_direction == 'RIGHT':
temp_x += pacman_speed
elif new_direction == 'UP':
temp_y -= pacman_speed
elif new_direction == 'DOWN':
temp_y += pacman_speed
# Check collision with walls
# Check the four corners of Pac-Man's next move
collisions = False
corners = [
(temp_x - CELL_SIZE // 2 + 2, temp_y - CELL_SIZE // 2 + 2),
(temp_x + CELL_SIZE // 2 - 2, temp_y - CELL_SIZE // 2 + 2),
(temp_x - CELL_SIZE // 2 + 2, temp_y + CELL_SIZE // 2 - 2),
(temp_x + CELL_SIZE // 2 - 2, temp_y + CELL_SIZE // 2 - 2)
]
for point in corners:
if is_wall(point[0], point[1]):
collisions = True
break
if not collisions:
direction = new_direction
if direction == 'LEFT':
pacman_x -= pacman_speed
elif direction == 'RIGHT':
pacman_x += pacman_speed
elif direction == 'UP':
pacman_y -= pacman_speed
elif direction == 'DOWN':
pacman_y += pacman_speed
# Wrap around the screen
if pacman_x < 0:
pacman_x = SCREEN_WIDTH - CELL_SIZE // 2
elif pacman_x > SCREEN_WIDTH:
pacman_x = CELL_SIZE // 2
if pacman_y < 0:
pacman_y = SCREEN_HEIGHT - CELL_SIZE // 2
elif pacman_y > SCREEN_HEIGHT:
pacman_y = CELL_SIZE // 2
# Check for dot collection
pacman_rect = pygame.Rect(pacman_x - CELL_SIZE // 2, pacman_y - CELL_SIZE // 2, CELL_SIZE, CELL_SIZE)
dots = [dot for dot in dots if not pacman_rect.collidepoint(dot)]
score = len(dots)
# Draw everything
draw_maze()
draw_dots()
draw_pacman(pacman_x, pacman_y, direction)
# Display score
score_text = font.render(f"Dots Remaining: {score}", True, WHITE)
screen.blit(score_text, (10, SCREEN_HEIGHT - 40))
pygame.display.flip()
pygame.quit()
sys.exit()
Initialization:
pygame and set up the game window with defined dimensions.Maze Definition:
'W': Wall'.': Dot (collectible)' ': Empty spacePac-Man Representation:
Movement and Collision Detection:
handle_keys function checks for arrow key presses and updates the direction accordingly.Dot Collection:
Drawing Elements:
draw_maze(): Draws the maze walls based on the maze definition.draw_dots(): Draws all remaining dots on the screen.draw_pacman(): Draws Pac-Man at the current position with the appropriate orientation.Game Loop:
Save the Code: Save the above code in a Python file, e.g., pacman.py.
Run the Game: Open a terminal or command prompt, navigate to the directory containing pacman.py, and execute:
python pacman.py
Controls: Use the arrow keys to move Pac-Man around the maze and collect all the dots.
This is a basic implementation. Here are some ideas to enhance the game further:
This simple Pac-Man implementation provides a foundation that you can build upon. By understanding the structure and how different components interact, you can customize and expand the game’s features to create a more complete and engaging experience.
Happy coding!
Not yet included in a published release.