#趣味代码# 要用Python实现迷宫生成器,可以使用深度优先搜索(DFS)算法。以下是一个简单的迷宫生成器代码示例: ```python import random def create_maze(width, height): # 初始化迷宫 maze = [['#'] * (width * 2 + 1) for _ in range(height * 2 + 1)] for y in range(height * 2 + 1): for x in range(width * 2 + 1): if x % 2 == 1 and y % 2 == 1: maze[y][x] = ' ' # 随机选择起点 start_x, start_y = random.randint(1, width * 2 - 2), random.randint(1, height * 2 - 2) maze[start_y][start_x] = 'S' # 深度优先搜索 stack = [(start_x, start_y)] while stack: x, y = stack[-1] directions = [(x - 2, y), (x + 2, y), (x, y - 2), (x, y + 2)] random.shuffle(directions) found = False for dx, dy in directions: if 0 < dx < width * 2 and 0 < dy < height * 2 and maze[dy][dx] == '#': if (dx == x - 2 and maze[y][x - 1] == '#') or (dx == x + 2 and maze[y][x + 1] == '#') or (dy == y - 2 and maze[y - 1][x] == '#') or (dy == y + 2 and maze[y + 1][x] == '#'): maze[dy][dx] = ' ' stack.append((dx, dy)) found = True break if not found: stack.pop() return maze def print_maze(maze): for row in maze: print(''.join(row)) width = 10 height = 10 maze = create_maze(width, height) print_maze(maze) ``` 这个代码会生成一个宽度为10、高度为10的迷宫。你可以根据需要调整宽度和高度。生成的迷宫中,'#'表示墙壁,' '表示通道,'S'表示起点。