import pygame
import random
# Initialize pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 300, 180
GRID_SIZE = 30 # Each cell in the grid is 30x30 pixels
ROWS, COLS = HEIGHT // GRID_SIZE, WIDTH // GRID_SIZE
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
pacman_pos = [1,1]
# Maze grid (1 = Wall, 0 = Empty path, 2 = Pellet, 3 = Ghost, 4 = Pac-Man)
maze = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 4, 0, 0, 0, 0, 0, 0, 1, 1],
[1, 0, 1, 1, 1, 1, 0, 0, 0, 1],
[1, 0, 1, 0, 0, 1, 0, 1, 0, 1],
[1, 2, 0, 0, 0, 0, 0, 1, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
def draw_maze(screen):
for row_idx, row in enumerate(maze):
for col_idx, cell in enumerate(row):
x, y = col_idx * GRID_SIZE, row_idx * GRID_SIZE
if cell == 1:
pygame.draw.rect(screen, BLUE, (x, y, GRID_SIZE, GRID_SIZE))
elif cell == 2:
pygame.draw.circle(screen, WHITE, (x + GRID_SIZE // 2, y + GRID_SIZE // 2), 5)
elif cell == 3:
pygame.draw.circle(screen, RED, (x + GRID_SIZE // 2, y + GRID_SIZE // 2), 12)
elif cell == 4:
pygame.draw.circle(screen, YELLOW, (x + GRID_SIZE // 2, y + GRID_SIZE // 2), 12)
def move_pacman(direction, screen):
global pacman_pos, score
row, col = pacman_pos
new_row, new_col = row, col
if direction == "UP":
new_row -= 1
elif direction == "DOWN":
new_row += 1
elif direction == "LEFT":
new_col -= 1
elif direction == "RIGHT":
new_col += 1
if maze[new_row][new_col] != 1:
maze[row][col] = 0 # Clear old position
maze[new_row][new_col] = 4 # Move Pac-Man
pacman_pos = [new_row, new_col]
def main():
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pac-Man (Beginner Version)")
clock = pygame.time.Clock()
while True:
screen.fill(BLACK)
draw_maze(screen)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
move_pacman("UP", screen)
elif event.key == pygame.K_DOWN:
move_pacman("DOWN", screen)
elif event.key == pygame.K_LEFT:
move_pacman("LEFT", screen)
elif event.key == pygame.K_RIGHT:
move_pacman("RIGHT", screen)
clock.tick(5) # Control game speed
if __name__ == "__main__":
main()