Maze Runner
Every level is a brand-new random maze that grows as you progress. Stuck? Press H to see the shortest path.
- Difficulty
- Intermediate
- Source size
- 206 lines, 1 file
- Requires
- Python 3.10+, pygame-ce or pygame
- Assets
- None (drawn in code)
Controls
- Arrow keys WASD Move (hold to repeat)
- H Show or hide the hint path
- N New maze
- Space Next level
On this page
What you'll learn#
- Generating a perfect maze with a depth-first recursive backtracker
- Storing walls as bit flags
- Finding the shortest path with breadth-first search
- Key repeat for held keys
Run it on your computer#
- Install Python 3.10 or newer and Pygame:
python -m pip install pygame-ce(orpygame). See the installation guides. - Download maze.py into any folder.
- Open a terminal in that folder and run
python maze.py.
No images or sounds are needed: everything is drawn in code. The game also runs unchanged in Pygame Online, because its loop uses asyncio to hand control to the browser each frame.
How it works#
Walls as bit flags#
Each cell stores which of its four walls still stand, as bits: N = 1, S = 2, E = 4, W = 8. walls & E tests for an east wall and walls &= ~E removes it. Removing a wall between two cells means clearing one bit in each.
Generating the maze#
The generator keeps a stack of cells. From the cell on top it picks a random unvisited neighbour, knocks down the wall between them and pushes the neighbour. When a cell has no unvisited neighbours it pops back. This "recursive backtracker" visits every cell exactly once and produces a perfect maze: exactly one path between any two cells. The included tests check that property.
Finding the shortest path#
Breadth-first search explores cells in order of distance from the start using a deque. Recording where each cell was reached from lets the code walk backwards from the exit to build the path. Because every cell is visited at most once, the hint is instant even for the largest mazes.
Complete source code#
"""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())The code is released under the MIT license: use it, change it and build on it. See licenses.
Ideas to extend it#
- Add keys and locked doors that must be opened in order.
- Add a timer per level and a best-time table.
- Hide the maze except for a circle around the player (fog of war).
- Add a chasing enemy that follows the BFS path towards the player.
- Try a different generator, such as Prim's algorithm, and compare the mazes.