Test bachelor

mail@pastecode.io avatar
unknown
python
7 months ago
1.8 kB
1
Indexable
Never
import random

def generate_maze(width, height):
    # Create a grid with all walls
    maze = [["wall" for _ in range(width)] for _ in range(height)]

    def is_valid(x, y):
        return 0 <= x < width and 0 <= y < height

    def get_neighbors(x, y):
        neighbors = [(x+2, y), (x-2, y), (x, y+2), (x, y-2)]
        random.shuffle(neighbors)
        return [(nx, ny) for nx, ny in neighbors if is_valid(nx, ny)]

    def connect_cells(x1, y1, x2, y2):
        maze[y1][x1] = "path"
        maze[y2][x2] = "path"
        maze[(y1+y2)//2][(x1+x2)//2] = "path"

    stack = [(random.randrange(0, width, 2), random.randrange(0, height, 2))]
    while stack:
        x, y = stack[-1]
        neighbors = get_neighbors(x, y)
        unvisited_neighbors = [(nx, ny) for nx, ny in neighbors if maze[ny][nx] == "wall"]
        if unvisited_neighbors:
            nx, ny = random.choice(unvisited_neighbors)
            connect_cells(x, y, nx, ny)
            stack.append((nx, ny))
        else:
            stack.pop()

    return maze

def print_maze(maze):
    for row in maze:
        print(" ".join(["#" if cell == "wall" else "R" for cell in row]))


if __name__ == "__main__":
    difficulty = input("Choose a difficulty level (easy, medium, hard): ").lower()

    if difficulty == "easy":
        width = random.randint(3, 5)
        height = random.randint(3, 5)
    elif difficulty == "medium":
        width = random.randint(6, 8)
        height = random.randint(6, 8)
    elif difficulty == "hard":
        width = random.randint(9, 11)
        height = random.randint(9, 11)
    else:
        print("Invalid difficulty level. Please choose 'easy', 'medium', or 'hard'.")
        exit(1)

    maze = generate_maze(width, height)
    print_maze(maze)