To create a smarter maze generation algorithm, we can utilize the Recursive Backtracker algorithm, which is a depth-first search approach that produces a perfect maze with a single, clear path from any point to any other point.
Let's update the maze generation part of the previous example using this algorithm:
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Constants
WINDOW_WIDTH, WINDOW_HEIGHT = 800, 600
GRID_SIZE = 40
MAZE_WIDTH = WINDOW_WIDTH // GRID_SIZE
MAZE_HEIGHT = WINDOW_HEIGHT // GRID_SIZE
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Initialize the screen
screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Maze Game")
# Player position
player_pos = [0, 0]
# Maze directions and their (dx, dy) movement
DIRECTIONS = {'N': (0, -1), 'S': (0, 1), 'E': (1, 0), 'W': (-1, 0)}
# Create an empty maze with walls
maze = [[1 for _ in range(MAZE_WIDTH)] for _ in range(MAZE_HEIGHT)]
def is_valid(x, y):
return 0 <= x < MAZE_WIDTH and 0 <= y < MAZE_HEIGHT
def generate_maze(x=0, y=0):
# Make the current cell a path
maze[y][x] = 0
# Randomize directions
dirs = list(DIRECTIONS.keys())
random.shuffle(dirs)
# Explore the neighbors
for direction in dirs:
dx, dy = DIRECTIONS[direction]
nx, ny = x + dx * 2, y + dy * 2
if is_valid(nx, ny) and maze[ny][nx] == 1:
# Knock down the wall between the current cell and the neighbor
maze[y + dy][x + dx] = 0
generate_maze(nx, ny)
# Generate the maze
generate_maze()
def draw_grid():
for y in range(MAZE_HEIGHT):
for x in range(MAZE_WIDTH):
rect = pygame.Rect(x * GRID_SIZE, y * GRID_SIZE, GRID_SIZE, GRID_SIZE)
if maze[y][x] == 1:
pygame.draw.rect(screen, BLACK, rect)
else:
pygame.draw.rect(screen, WHITE, rect)
if [x, y] == player_pos:
pygame.draw.rect(screen, BLUE, rect)
if [x, y] == [MAZE_WIDTH - 1, MAZE_HEIGHT - 1]:
pygame.draw.rect(screen, GREEN, rect)
def move_player(dx, dy):
new_x, new_y = player_pos[0] + dx, player_pos[1] + dy
if 0 <= new_x < MAZE_WIDTH and 0 <= new_y < MAZE_HEIGHT and maze[new_y][new_x] == 0:
player_pos[0] = new_x
player_pos[1] = new_y
def main():
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
move_player(-1, 0)
elif event.key == pygame.K_RIGHT:
move_player(1, 0)
elif event.key == pygame.K_UP:
move_player(0, -1)
elif event.key == pygame.K_DOWN:
move_player(0, 1)
screen.fill(WHITE)
draw_grid()
# Check if player reached the end
if player_pos == [MAZE_WIDTH - 1, MAZE_HEIGHT - 1]:
pygame.display.set_caption("Maze Game - You Win!")
pygame.display.flip()
clock.tick(30)
if __name__ == "__main__":
main()
Explanation:
- Recursive Backtracker Algorithm: The maze generation uses a depth-first search approach. We start from a random cell, mark it as part of the maze, then shuffle the possible directions (N, S, E, W). We recursively continue to create paths until all cells are visited.
- Odd-Indexed Cells: The algorithm digs two cells at a time to ensure 2x2 steps between pathways, maintaining wall boundaries. To simplify, wall cells start at 1s, and paths are 0s.
This recursive backtracking will generate a perfect maze, which is more realistic because it removes any isolated walls and ensures a single path between any two points in the maze.