from kandinsky import * from random import randint # Define constants for the maze SCREEN_WIDTH = 320 SCREEN_HEIGHT = 220 MAZE_WIDTH = 20 MAZE_HEIGHT = 14 WALL_COLOR = color(0, 0, 0) SPACE_COLOR = color(255, 255, 255) START_COLOR = color(0, 255, 0) END_COLOR = color(255, 0, 0) PATH_COLOR = color(0, 0, 255) CELL_SIZE = SCREEN_WIDTH // MAZE_WIDTH # Generate the maze maze = [[WALL_COLOR for _ in range(MAZE_WIDTH)] for _ in range(MAZE_HEIGHT)] start = (randint(0, MAZE_HEIGHT-1), randint(0, MAZE_WIDTH-1)) end = (randint(0, MAZE_HEIGHT-1), randint(0, MAZE_WIDTH-1)) while start == end: end = (randint(0, MAZE_HEIGHT-1), randint(0, MAZE_WIDTH-1)) maze[start[0]][start[1]] = START_COLOR maze[end[0]][end[1]] = END_COLOR for row in range(1, MAZE_HEIGHT-1): for col in range(1, MAZE_WIDTH-1): if maze[row][col] != START_COLOR and maze[row][col] != END_COLOR: if randint(0, 100) < 30: maze[row][col] = WALL_COLOR else: maze[row][col] = SPACE_COLOR # Define the pathfinding function def find_path(maze, start, end): queue = [start] visited = set() path = {} found = False while queue and not found: current = queue.pop(0) if current == end: found = True else: row, col = current neighbors = [(row-1, col), (row+1, col), (row, col-1), (row, col+1)] for neighbor in neighbors: n_row, n_col = neighbor if 0 <= n_row < MAZE_HEIGHT and 0 <= n_col < MAZE_WIDTH and maze[n_row][n_col] != WALL_COLOR and neighbor not in visited: queue.append(neighbor) visited.add(neighbor) path[neighbor] = current if found: current = end path_list = [current] while current != start: current = path[current] path_list.append(current) path_list.reverse() return path_list else: return None # Find the path and draw the maze and path path = find_path(maze, start, end) if path is not None: for row in range(MAZE_HEIGHT): for col in range(MAZE_WIDTH): if (row, col) == start: fill_rect(col*CELL_SIZE, row*CELL_SIZE, CELL_SIZE, CELL_SIZE, START_COLOR) elif (row, col) == end: fill_rect(col*CELL_SIZE, row*CELL_SIZE, CELL_SIZE, CELL_SIZE, END_COLOR) elif (row, col) in path: fill_rect(col*CELL_SIZE, row*CELL_SIZE, CELL_SIZE, CELL_SIZE, PATH_COLOR) else: fill_rect(col*CELL_SIZE, row*CELL_SIZE, CELL_SIZE, CELL_SIZE, maze[row][col]) else: print()