Python Maze Program Broken

Does anyone know why this code does not work? I’m trying to make a randomly generated maze program.

Maze Generator - Replit

import random

def generate_maze(width, height):
    # Initialize the maze with walls
    maze = [[1] * width + [0] for _ in range(height)] + [[1] * (width + 1)]
    # Set the starting point
    start_x, start_y = random.randint(0, width - 1), random.randint(0, height - 1)
    maze[start_y][start_x] = 0
    # Create a list of walls
    walls = [(start_x, start_y, x, y) for x, y in ((start_x + 1, start_y), (start_x, start_y + 1), (start_x - 1, start_y), (start_x, start_y - 1)) if 0 <= x < width and 0 <= y < height]
    while walls:
        # Choose a random wall
        wall_index = random.randint(0, len(walls) - 1)
        x1, y1, x2, y2 = walls[wall_index]
        del walls[wall_index]
        # Check if the wall separates two different regions
        if maze[y1][x1] != maze[y2][x2]:
            # Break down the wall
            maze[y1][x1] = maze[y2][x2] = 0
            # Add the neighboring walls
            walls += [(x2, y2, x2 + 1, y2), (x2, y2, x2, y2 + 1), (x2, y2, x2 - 1, y2), (x2, y2, x2, y2 - 1)]
    return maze

# Example usage
maze = generate_maze(10, 10)
for row in maze:
    print(''.join(['#' if cell else ' ' for cell in row]))

1 Like

Do some simple debugging by using the builtin debugger or printing all of the variables. We can see that the maze is a list of lists 11x11, and that right before the error, some of the variables are outside that range.

Take a look at the # Add the neighbouring walls section. You don’t check if it is within the boundaries even though you do for the initial walls at # Create a list of walls. Apply the same exact filter and that should probably fix it.

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.