python pygame 迷宫找出口
时间: 2025-06-15 19:16:11 浏览: 7
### Python 和 Pygame 实现迷宫找出口的示例代码
以下是一个基于 Python 和 Pygame 的迷宫游戏实现,支持玩家手动控制和系统自动寻路(A*算法)。代码中包含迷宫生成、玩家路径记录以及 A* 算法的实现。
#### 1. 迷宫生成
迷宫生成使用深度优先搜索(DFS)算法[^4]。每个单元格表示一个房间,房间之间通过墙分隔。
#### 2. A* 寻路算法
A* 算法用于计算从起点到终点的最短路径[^3]。它结合了启发式函数(估计距离)和实际代价,确保路径最优。
#### 3. 游戏主循环
游戏主循环处理用户输入(方向键)、绘制迷宫和路径,并更新屏幕显示[^2]。
以下是完整代码:
```python
import pygame
import random
import heapq
# 初始化 Pygame
pygame.init()
# 屏幕尺寸
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
TILE_SIZE = 40
ROWS, COLS = SCREEN_HEIGHT // TILE_SIZE, SCREEN_WIDTH // TILE_SIZE
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 创建窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("迷宫游戏")
# 迷宫生成类
class Cell:
def __init__(self, x, y):
self.x = x
self.y = y
self.walls = {'top': True, 'right': True, 'bottom': True, 'left': True}
self.visited = False
def draw(self):
x, y = self.x * TILE_SIZE, self.y * TILE_SIZE
if self.walls['top']:
pygame.draw.line(screen, WHITE, (x, y), (x + TILE_SIZE, y))
if self.walls['right']:
pygame.draw.line(screen, WHITE, (x + TILE_SIZE, y), (x + TILE_SIZE, y + TILE_SIZE))
if self.walls['bottom']:
pygame.draw.line(screen, WHITE, (x, y + TILE_SIZE), (x + TILE_SIZE, y + TILE_SIZE))
if self.walls['left']:
pygame.draw.line(screen, WHITE, (x, y), (x, y + TILE_SIZE))
def remove_walls(current, next_cell):
dx = current.x - next_cell.x
if dx == 1:
current.walls['left'] = False
next_cell.walls['right'] = False
elif dx == -1:
current.walls['right'] = False
next_cell.walls['left'] = False
dy = current.y - next_cell.y
if dy == 1:
current.walls['top'] = False
next_cell.walls['bottom'] = False
elif dy == -1:
current.walls['bottom'] = False
next_cell.walls['top'] = False
def generate_maze():
grid = [[Cell(col, row) for row in range(ROWS)] for col in range(COLS)]
stack = []
current = grid[0][0]
current.visited = True
stack.append(current)
while stack:
current = stack[-1]
neighbors = []
directions = [(0, -1), (1, 0), (0, 1), (-1, 0)]
for dx, dy in directions:
nx, ny = current.x + dx, current.y + dy
if 0 <= nx < COLS and 0 <= ny < ROWS:
neighbor = grid[nx][ny]
if not neighbor.visited:
neighbors.append(neighbor)
if neighbors:
next_cell = random.choice(neighbors)
next_cell.visited = True
remove_walls(current, next_cell)
stack.append(next_cell)
else:
stack.pop()
return grid
# A* 寻路算法
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
def a_star(start, goal, grid):
open_set = []
heapq.heappush(open_set, (0, start))
came_from = {}
g_score = { (x, y): float('inf') for x in range(COLS) for y in range(ROWS) }
g_score[start] = 0
f_score = { (x, y): float('inf') for x in range(COLS) for y in range(ROWS) }
f_score[start] = heuristic(start, goal)
while open_set:
current = heapq.heappop(open_set)[1]
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
directions = [(0, -1), (1, 0), (0, 1), (-1, 0)]
for dx, dy in directions:
nx, ny = current[0] + dx, current[1] + dy
neighbor = (nx, ny)
if 0 <= nx < COLS and 0 <= ny < ROWS and not grid[nx][ny].walls.get((dx, dy), False):
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
if neighbor not in [node[1] for node in open_set]:
heapq.heappush(open_set, (f_score[neighbor], neighbor))
return []
# 主程序
def main():
grid = generate_maze()
player_pos = (0, 0)
end_pos = (COLS - 1, ROWS - 1)
path = []
running = True
while running:
screen.fill(BLACK)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
if not grid[player_pos[0]][player_pos[1]].walls['top']:
player_pos = (player_pos[0], player_pos[1] - 1)
if keys[pygame.K_DOWN]:
if not grid[player_pos[0]][player_pos[1]].walls['bottom']:
player_pos = (player_pos[0], player_pos[1] + 1)
if keys[pygame.K_LEFT]:
if not grid[player_pos[0]][player_pos[1]].walls['left']:
player_pos = (player_pos[0] - 1, player_pos[1])
if keys[pygame.K_RIGHT]:
if not grid[player_pos[0]][player_pos[1]].walls['right']:
player_pos = (player_pos[0] + 1, player_pos[1])
if keys[pygame.K_SPACE]:
path = a_star(player_pos, end_pos, grid)
# 绘制迷宫
for x in range(COLS):
for y in range(ROWS):
grid[x][y].draw()
# 绘制路径
for pos in path:
pygame.draw.rect(screen, BLUE, (pos[0] * TILE_SIZE, pos[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE))
# 绘制玩家和终点
pygame.draw.rect(screen, RED, (player_pos[0] * TILE_SIZE, player_pos[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE))
pygame.draw.rect(screen, GREEN, (end_pos[0] * TILE_SIZE, end_pos[1] * TILE_SIZE, TILE_SIZE, TILE_SIZE))
pygame.display.flip()
pygame.quit()
if __name__ == '__main__':
main()
```
阅读全文
相关推荐


















