pygame生成随机迷宫
时间: 2025-03-05 13:47:03 浏览: 29
### 使用 Pygame 实现随机迷宫生成
为了创建一个基于 Pygame 的随机迷宫生成器,可以采用多种算法来构建迷宫结构。常见的有深度优先搜索 (DFS),Prim's 算法以及 Kruskal’s 算法等。这里介绍一种简单的 DFS 迷宫生成方法。
#### 安装依赖库
首先确保安装了必要的 Python 库:
```bash
pip install pygame
```
#### 初始化 Pygame 和设置参数
定义一些基本常量和初始化 Pygame 模块:
```python
import random
import pygame
from collections import deque
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# 屏幕大小设定
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
CELL_SIZE = 40
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.init()
clock = pygame.time.Clock()
class Cell:
def __init__(self, row, col):
self.row = row
self.col = col
self.walls = {'top': True, 'right': True, 'bottom': True, 'left': True}
self.visited = False
def draw(self):
x, y = col * CELL_SIZE, row * CELL_SIZE
if not self.walls['top']:
pygame.draw.line(screen, WHITE, (x, y), (x + CELL_SIZE, y))
if not self.walls['right']:
pygame.draw.line(screen, WHITE, (x + CELL_SIZE, y),(x + CELL_SIZE, y + CELL_SIZE))
if not self.walls['bottom']:
pygame.draw.line(screen, WHITE, (x, y + CELL_SIZE),(x + CELL_SIZE, y + CELL_SIZE))
if not self.walls['left']:
pygame.draw.line(screen, WHITE, (x, y), (x, y + CELL_SIZE))
def remove_walls(current_cell, next_cell):
dx = current_cell.col - next_cell.col
dy = current_cell.row - next_cell.row
if dx == 1:
current_cell.walls['left'] = False
next_cell.walls['right'] = False
elif dx == -1:
current_cell.walls['right'] = False
next_cell.walls['left'] = False
if dy == 1:
current_cell.walls['top'] = False
next_cell.walls['bottom'] = False
elif dy == -1:
current_cell.walls['bottom'] = False
next_cell.walls['top'] = False
```
#### 构建迷宫网格与执行深度优先遍历
接下来编写函数 `generate_maze` 来建立迷宫矩阵,并调用递归版本的深度优先搜索完成迷宫雕刻工作。
```python
def generate_maze(rows=15, cols=20):
grid = [[Cell(row, col) for col in range(cols)] for row in range(rows)]
stack = deque()
start_cell = grid[0][0]
def dfs(cell=start_cell):
cell.visited = True
neighbors = []
# 获取未访问过的邻居节点列表
if cell.row > 0 and not grid[cell.row-1][cell.col].visited:
neighbors.append(grid[cell.row-1][cell.col])
if cell.row < rows-1 and not grid[cell.row+1][cell.col].visited:
neighbors.append(grid[cell.row+1][cell.col])
if cell.col > 0 and not grid[cell.row][cell.col-1].visited:
neighbors.append(grid[cell.row][cell.col-1])
if cell.col < cols-1 and not grid[cell.row][cell.col+1].visited:
neighbors.append(grid[cell.row][cell.col+1])
if len(neighbors)>0:
neighbor = random.choice(neighbors)
remove_walls(cell, neighbor)
stack.append(cell)
dfs(neighbor)
elif len(stack)!=0:
backtrack_to = stack.pop()
dfs(backtrack_to)
dfs(start_cell)
return grid
```
#### 主程序逻辑
最后,在主循环里更新画面帧率并渲染迷宫图像至窗口内展示给用户查看。
```python
if __name__ == '__main__':
running = True
maze_grid = generate_maze(int(SCREEN_HEIGHT/CELL_SIZE)-1,int(SCREEN_WIDTH/CELL_SIZE)-1)
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for row in maze_grid:
for cell in row:
cell.draw()
clock.tick(30)
pygame.display.flip()
pygame.quit()
```
上述代码实现了使用 Pygame 绘制动态变化中的迷宫构造过程[^1]。此示例仅展示了基础功能,实际项目可能还需要加入更多特性比如起点终点标记、障碍物配置等功能模块。
阅读全文
相关推荐


















