Okay, let's create a simple, retro-themed haunted maze arcade game using Python and Pygame. We'll generate all assets using Pygame's drawing functions and simple data structures.
import pygame
import random
import sys
# --- Constants ---
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
CELL_SIZE = 32 # Size of each cell (wall, floor) in pixels
# Colors (Retro Palette)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
PURPLE = (128, 0, 128)
CYAN = (0, 255, 255)
GREY = (128, 128, 128)
# Game State
STATE_START = 0
STATE_PLAYING = 1
STATE_GAME_OVER = 2
STATE_WON = 3
# --- Maze Layout ---
# Using strings to define the maze layout.
# # : Wall
# . : Path (Floor)
# P : Player Start
# G : Ghost Start
# C : Collectible (Coin)
# E : Exit
MAZE_PLAN = [
"####################",
"#P.G.C.C.C.G.C.C.C.E#",
"#.#.#.###.###.###.#.#",
"#C#.#.#.#.#.#.#.#.#C#",
"#.#.###.#.#.#.#.###.#",
"#C.C.C.#.#.#.#.C.C.C#",
"###.###.#.#.#.###.###",
"#G.C.C.C.#.#.C.C.C.G#",
"#.###.###.###.###.#.#",
"#C.#.#.#.#.#.#.#.#.C#",
"#.#.#.###.###.###.#.#",
"#G.C.C.C.G.C.C.C.G.C#",
"####################",
]
# Calculate maze dimensions based on the plan
MAZE_HEIGHT = len(MAZE_PLAN)
MAZE_WIDTH = len(MAZE_PLAN[0])
# Ensure screen size is large enough for the maze
if SCREEN_WIDTH < MAZE_WIDTH * CELL_SIZE or SCREEN_HEIGHT < MAZE_HEIGHT * CELL_SIZE:
print("Warning: Screen size is smaller than the maze.")
# Adjust screen size or cell size if necessary, but let's assume it fits for now
# --- Game Classes/Objects ---
class Entity:
def __init__(self, row, col, color):
self.row = row
self.col = col
self.color = color
def draw(self, surface):
x = self.col * CELL_SIZE
y = self.row * CELL_SIZE
pygame.draw.rect(surface, self.color, (x, y, CELL_SIZE, CELL_SIZE))
# Add a little border to make them pop like old arcade sprites
pygame.draw.rect(surface, BLACK, (x, y, CELL_SIZE, CELL_SIZE), 2)
def get_grid_pos(self):
return (self.row, self.col)
class Player(Entity):
def __init__(self, row, col):
super().__init__(row, col, YELLOW)
self.lives = 3 # Starting lives
self.score = 0 # Starting score
self.start_pos = (row, col) # Store start position for respawn
def respawn(self):
self.row, self.col = self.start_pos
class Ghost(Entity):
def __init__(self, row, col):
super().__init__(row, col, PURPLE) # Ghosts are purple!
self.start_pos = (row, col) # Store start position for respawn
self.move_timer = 0
self.move_delay = 20 # Ghosts move every 20 frames (adjust for speed)
self.last_move = (0, 0) # Store last successful move
def respawn(self):
self.row, self.col = self.start_pos
self.move_timer = 0 # Reset timer
def move(self, maze_grid):
self.move_timer += 1
if self.move_timer < self.move_delay:
return # Not time to move yet
self.move_timer = 0 # Reset timer
# Simple Ghost AI: Try a random direction. If blocked, try another.
# Or try to keep going in the last direction if possible.
possible_moves = [(0, 1), (0, -1), (1, 0), (-1, 0)] # Right, Left, Down, Up
# Try moving in the last successful direction first
dr, dc = self.last_move
if dr != 0 or dc != 0:
new_row, new_col = self.row + dr, self.col + dc
if 0 <= new_row < MAZE_HEIGHT and 0 <= new_col < MAZE_WIDTH and maze_grid[new_row][new_col] != '#':
self.row, self.col = new_row, new_col
return # Moved successfully
# If last direction didn't work or wasn't set, try random directions
random.shuffle(possible_moves)
for dr, dc in possible_moves:
new_row, new_col = self.row + dr, self.col + dc
# Check bounds and wall collision
if 0 <= new_row < MAZE_HEIGHT and 0 <= new_col < MAZE_WIDTH and maze_grid[new_row][new_col] != '#':
self.row, self.col = new_row, new_col
self.last_move = (dr, dc) # Store successful move
return # Moved successfully
class Collectible:
def __init__(self, row, col):
self.row = row
self.col = col
self.color = YELLOW # Coins are yellow!
self.collected = False
def draw(self, surface):
if not self.collected:
x = self.col * CELL_SIZE + CELL_SIZE // 2 # Center of the cell
y = self.row * CELL_SIZE + CELL_SIZE // 2
radius = CELL_SIZE // 4
pygame.draw.circle(surface, self.color, (x, y), radius)
# Add a little border
pygame.draw.circle(surface, BLACK, (x, y), radius, 2)
def get_grid_pos(self):
return (self.row, self.col)
# --- Maze Initialization ---
def build_maze(plan):
maze_grid = []
player_start = None
ghost_starts = []
collectibles = []
exit_pos = None
for r, row_str in enumerate(plan):
grid_row = []
for c, cell_char in enumerate(row_str):
grid_row.append(cell_char)
if cell_char == 'P':
player_start = (r, c)
elif cell_char == 'G':
ghost_starts.append((r, c))
elif cell_char == 'C':
collectibles.append(Collectible(r, c))
elif cell_char == 'E':
exit_pos = (r, c)
maze_grid.append(grid_row)
return maze_grid, player_start, ghost_starts, collectibles, exit_pos
# --- Drawing Functions ---
def draw_maze(surface, maze_grid):
for r in range(MAZE_HEIGHT):
for c in range(MAZE_WIDTH):
cell_char = maze_grid[r][c]
x = c * CELL_SIZE
y = r * CELL_SIZE
if cell_char == '#':
# Draw a wall block - simple grey rectangle
pygame.draw.rect(surface, GREY, (x, y, CELL_SIZE, CELL_SIZE))
# Add some detail - inner black rectangle
pygame.draw.rect(surface, BLACK, (x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4))
elif cell_char in ('.', 'P', 'G', 'C', 'E'):
# Draw a floor tile - simple black rectangle
pygame.draw.rect(surface, BLACK, (x, y, CELL_SIZE, CELL_SIZE))
def draw_score_lives(surface, score, lives, font):
score_text = font.render(f"SCORE: {score:06}", True, WHITE)
lives_text = font.render(f"LIVES: {lives}", True, WHITE)
surface.blit(score_text, (10, 10))
surface.blit(lives_text, (SCREEN_WIDTH - lives_text.get_width() - 10, 10))
def draw_message(surface, message, font, color=WHITE):
text_surface = font.render(message, True, color)
text_rect = text_surface.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
surface.blit(text_surface, text_rect)
# --- Game Logic Functions ---
def can_move(maze_grid, row, col, dr, dc):
new_row = row + dr
new_col = col + dc
# Check bounds
if new_row < 0 or new_row >= MAZE_HEIGHT or new_col < 0 or new_col >= MAZE_WIDTH:
return False
# Check wall collision
if maze_grid[new_row][new_col] == '#':
return False
return True
def check_collisions(player, ghosts, collectibles, maze_grid):
# Check player-ghost collision
player_pos = player.get_grid_pos()
for ghost in ghosts:
if not isinstance(ghost, Ghost): continue # Just in case
if player_pos == ghost.get_grid_pos():
player.lives -= 1
if player.lives <= 0:
return STATE_GAME_OVER
else:
player.respawn()
for g in ghosts:
if isinstance(g, Ghost):
g.respawn() # Respawn all ghosts too
# Note: Game state remains PLAYING, but player and ghosts reset
return STATE_PLAYING # Indicate collision handled
# Check player-collectible collision
collected_count = 0
for collectible in collectibles:
if not collectible.collected and player_pos == collectible.get_grid_pos():
collectible.collected = True
player.score += 10 # Score for collecting a coin
collected_count += 1
# Check player-exit
exit_pos = None
# Find exit position (only need to do this once ideally)
for r in range(MAZE_HEIGHT):
for c in range(MAZE_WIDTH):
if maze_grid[r][c] == 'E':
exit_pos = (r, c)
break
if exit_pos: break
if exit_pos and player_pos == exit_pos:
# Check if all collectibles are collected before allowing exit?
# Let's make it simple for now: exit is always possible if you reach it.
# For a Pac-Man style, you'd collect all dots first.
# If you wanted that, add: if all(c.collected for c in collectibles):
return STATE_WON
# No game-ending collisions, stay in PLAYING state (even if life lost)
return STATE_PLAYING
# --- Main Game Loop ---
def run_game():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Haunted Maze Arcade")
clock = pygame.time.Clock()
# Font setup - use a default or monospace font
try:
# Try a fixed-width font often available
font = pygame.font.SysFont('monospace', 30, bold=True)
small_font = pygame.font.SysFont('monospace', 20)
except pygame.font.error:
# Fallback if 'monospace' isn't found
font = pygame.font.Font(None, 40)
small_font = pygame.font.Font(None, 30)
# Game state variables
game_state = STATE_START
player = None
ghosts = []
collectibles = []
maze_grid = []
exit_pos = None
# --- Game Reset Function ---
def reset_game():
nonlocal maze_grid, player, ghosts, collectibles, exit_pos, game_state
maze_grid, player_start, ghost_starts, collectibles_data, exit_pos = build_maze(MAZE_PLAN)
player = Player(player_start[0], player_start[1])
ghosts = [Ghost(gs[0], gs[1]) for gs in ghost_starts]
collectibles = collectibles_data # Use the list generated by build_maze
game_state = STATE_PLAYING
# --- Game Loop ---
running = True
while running:
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if game_state == STATE_START or game_state == STATE_GAME_OVER or game_state == STATE_WON:
if event.key == pygame.K_RETURN: # Press Enter to start/restart
reset_game()
elif game_state == STATE_PLAYING:
dr, dc = 0, 0
if event.key == pygame.K_UP:
dr = -1
elif event.key == pygame.K_DOWN:
dr = 1
elif event.key == pygame.K_LEFT:
dc = -1
elif event.key == pygame.K_RIGHT:
dc = 1
if dr != 0 or dc != 0:
if can_move(maze_grid, player.row, player.col, dr, dc):
player.row += dr
player.col += dc
# --- Game State Updates ---
if game_state == STATE_PLAYING:
# Move ghosts
for ghost in ghosts:
ghost.move(maze_grid)
# Check for collisions after player and ghosts move
current_game_state = check_collisions(player, ghosts, collectibles, maze_grid)
# If collision detection returned a different state (game over, won), update it
if current_game_state != STATE_PLAYING:
game_state = current_game_state
# --- Drawing ---
screen.fill(BLACK) # Background
if game_state == STATE_START:
draw_message(screen, "HAUNTED MAZE ARCADE", font)
draw_message(screen, "Press ENTER to Start", small_font, GREY)
elif game_state == STATE_PLAYING:
draw_maze(screen, maze_grid)
# Draw collectibles
for collectible in collectibles:
collectible.draw(screen)
# Draw player and ghosts
player.draw(screen)
for ghost in ghosts:
ghost.draw(screen)
# Draw score and lives
draw_score_lives(screen, player.score, player.lives, small_font)
elif game_state == STATE_GAME_OVER:
draw_message(screen, "GAME OVER", font, RED)
draw_message(screen, f"Final Score: {player.score}", small_font, WHITE)
draw_message(screen, "Press ENTER to Play Again", small_font, GREY)
elif game_state == STATE_WON:
draw_message(screen, "YOU ESCAPED!", font, GREEN)
draw_message(screen, f"Final Score: {player.score}", small_font, WHITE)
draw_message(screen, "Press ENTER to Play Again", small_font, GREY)
# --- Update Display ---
pygame.display.flip() # Or pygame.display.update()
# --- Frame Rate Control ---
clock.tick(60) # Limit to 60 frames per second
pygame.quit()
sys.exit()
# --- Run the Game ---
if __name__ == "__main__":
run_game()
How the Code Works:
- Import Pygame: Imports the necessary library.
- Constants: Defines screen dimensions, cell size, and the retro color palette. Defines integer constants for game states (
STATE_START, STATE_PLAYING, etc.).
- Maze Layout (
MAZE_PLAN): A list of strings visually representing the maze. This is the core "asset" for the level design, generated directly in the code.
- Entity Classes (
Entity, Player, Ghost, Collectible):
Entity: A base class for things on the grid, storing row, column, and color. It has a simple draw method to draw a colored square.
Player: Inherits from Entity, adds lives, score, and a respawn method.
Ghost: Inherits from Entity, adds move_timer for controlling speed and a basic movement logic (move). It also has respawn. The move logic is intentionally simple and grid-based, mimicking early arcade AI. It tries a random valid move or continues its last successful move attempt.
Collectible: Stores position and a collected status. Has a draw method that only draws if not collected.
build_maze Function: Parses the MAZE_PLAN string representation into a 2D list (maze_grid) which is easier to work with for grid-based movement and collision. It also finds the initial positions of the player, ghosts, collectibles, and the exit based on the characters in the plan.
- Drawing Functions:
draw_maze: Iterates through the maze_grid and draws rectangles for walls (with a simple inner black border for a blocky look) and empty floor tiles.
draw_score_lives: Renders and draws the score and lives text at the top of the screen.
draw_message: A helper to draw centered text messages (used for start, game over, win screens).
- Game Logic Functions:
can_move: Checks if a potential move (player or ghost) to a new (row, col) is valid (within bounds and not a wall).
check_collisions: Called after entities move. Checks for player-ghost collision (decrements life, respawns), player-collectible collision (increments score, marks collectible), and player-exit collision (checks for win condition). It returns the new game state if a state change occurs.
This code provides a functional, albeit simple, retro haunted maze experience with movement, basic enemy AI, scoring, lives, collectibles, and game over/win states, all built without external asset files.