"""Maze Runner - a Pygame.net game project. Every level is a new, randomly generated maze (depth-first "recursive backtracker" algorithm). Reach the yellow exit; mazes grow each level. Press H to see the shortest path, found with breadth-first search. Run it: pip install pygame-ce (or: pip install pygame) python maze.py Controls: Arrow keys or WASD to move, H toggles the hint path, N new maze. License: MIT - https://pygame.net/licenses/ """ import asyncio import random from collections import deque import pygame WIDTH, HEIGHT = 640, 480 FPS = 60 HUD = 40 BG = (16, 26, 48) WALL = (157, 194, 255) PLAYER = (91, 147, 230) EXIT = (244, 197, 49) HINT = (110, 200, 120) WHITE = (230, 236, 247) # Wall bits for each cell N, S, E, W = 1, 2, 4, 8 MOVES = {N: (0, -1), S: (0, 1), E: (1, 0), W: (-1, 0)} OPPOSITE = {N: S, S: N, E: W, W: E} def generate_maze(cols, rows, rng): """Return a grid where grid[y][x] holds the walls still standing (bit flags).""" grid = [[N | S | E | W for _ in range(cols)] for _ in range(rows)] stack = [(0, 0)] visited = {(0, 0)} while stack: x, y = stack[-1] options = [] for wall, (dx, dy) in MOVES.items(): nx, ny = x + dx, y + dy if 0 <= nx < cols and 0 <= ny < rows and (nx, ny) not in visited: options.append((wall, nx, ny)) if not options: stack.pop() continue wall, nx, ny = rng.choice(options) grid[y][x] &= ~wall grid[ny][nx] &= ~OPPOSITE[wall] visited.add((nx, ny)) stack.append((nx, ny)) return grid def shortest_path(grid, start, goal): """Breadth-first search over open passages. Returns a list of cells.""" came_from = {start: None} queue = deque([start]) while queue: cell = queue.popleft() if cell == goal: break x, y = cell for wall, (dx, dy) in MOVES.items(): nxt = (x + dx, y + dy) if not grid[y][x] & wall and nxt not in came_from: came_from[nxt] = cell queue.append(nxt) path, cell = [], goal while cell is not None: path.append(cell) cell = came_from.get(cell) return path[::-1] class Game: def __init__(self, seed=None): self.rng = random.Random(seed) self.font = pygame.font.Font(None, 30) self.big = pygame.font.Font(None, 56) self.level = 1 self.new_maze() def new_maze(self): self.cols = min(8 + self.level * 2, 30) self.rows = min(6 + self.level * 2, 21) self.cell = min(WIDTH // self.cols, (HEIGHT - HUD) // self.rows) self.ox = (WIDTH - self.cols * self.cell) // 2 self.oy = HUD + (HEIGHT - HUD - self.rows * self.cell) // 2 self.grid = generate_maze(self.cols, self.rows, self.rng) self.player = (0, 0) self.exit = (self.cols - 1, self.rows - 1) self.show_hint = False self.steps = 0 self.time = 0.0 self.done = False self.repeat = 0.0 def try_move(self, wall): x, y = self.player if self.grid[y][x] & wall: return False dx, dy = MOVES[wall] self.player = (x + dx, y + dy) self.steps += 1 if self.player == self.exit: self.done = True return True def handle_event(self, event): if event.type != pygame.KEYDOWN: return keymap = {pygame.K_UP: N, pygame.K_w: N, pygame.K_DOWN: S, pygame.K_s: S, pygame.K_RIGHT: E, pygame.K_d: E, pygame.K_LEFT: W, pygame.K_a: W} if self.done and event.key in (pygame.K_SPACE, pygame.K_RETURN): self.level += 1 self.new_maze() elif event.key == pygame.K_h: self.show_hint = not self.show_hint elif event.key == pygame.K_n: self.new_maze() elif event.key in keymap and not self.done: self.try_move(keymap[event.key]) self.repeat = 0.22 # delay before holding a key starts repeating def update(self, dt, keys=None): if self.done: return self.time += dt if keys is None: keys = pygame.key.get_pressed() held = [(pygame.K_UP, N), (pygame.K_DOWN, S), (pygame.K_RIGHT, E), (pygame.K_LEFT, W)] pressed = [w for k, w in held if keys[k]] if pressed: self.repeat -= dt if self.repeat <= 0: self.try_move(pressed[0]) self.repeat = 0.08 else: self.repeat = 0.0 def cell_rect(self, x, y): return pygame.Rect(self.ox + x * self.cell, self.oy + y * self.cell, self.cell, self.cell) def draw(self, surface): surface.fill(BG) c = self.cell ex = self.cell_rect(*self.exit).inflate(-c // 4, -c // 4) pygame.draw.rect(surface, EXIT, ex, border_radius=3) if self.show_hint: path = shortest_path(self.grid, self.player, self.exit) pts = [self.cell_rect(x, y).center for x, y in path] if len(pts) > 1: pygame.draw.lines(surface, HINT, False, pts, 3) for y in range(self.rows): for x in range(self.cols): r = self.cell_rect(x, y) walls = self.grid[y][x] if walls & N: pygame.draw.line(surface, WALL, r.topleft, r.topright, 2) if walls & W: pygame.draw.line(surface, WALL, r.topleft, r.bottomleft, 2) if y == self.rows - 1 and walls & S: pygame.draw.line(surface, WALL, r.bottomleft, r.bottomright, 2) if x == self.cols - 1 and walls & E: pygame.draw.line(surface, WALL, r.topright, r.bottomright, 2) pygame.draw.circle(surface, PLAYER, self.cell_rect(*self.player).center, max(4, c // 3)) surface.blit(self.font.render(f"Level {self.level}", True, WHITE), (14, 10)) info = self.font.render(f"Steps {self.steps} Time {self.time:4.1f}s H: hint", True, WHITE) surface.blit(info, (WIDTH - info.get_width() - 14, 10)) if self.done: shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA) shade.fill((0, 0, 0, 150)) surface.blit(shade, (0, 0)) t = self.big.render("You found the exit!", True, EXIT) surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 16))) h = self.font.render("Press Space for a bigger maze", True, WHITE) surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30))) async def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Maze Runner - Pygame.net") clock = pygame.time.Clock() game = Game() running = True while running: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False else: game.handle_event(event) game.update(dt) game.draw(screen) pygame.display.flip() await asyncio.sleep(0) pygame.quit() if __name__ == "__main__": asyncio.run(main())