python 走迷宫
时间: 2024-04-20 20:21:50 浏览: 117
以下是一个用Python实现迷宫游戏的示例代码[^1]:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("迷宫游戏")
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 定义迷宫地图
maze_map = [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 0, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
# 定义迷宫单元格大小
cell_width = screen_width // len(maze_map)
cell_height = screen_height // len(maze_map)
# 定义玩家初始位置
player_x = 1
player_y = 1
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 绘制迷宫
screen.fill(BLACK)
for row in range(len(maze_map)):
for col in range(len(maze_map)):
if maze_map[row][col] == 1:
pygame.draw.rect(screen, BLUE, (col * cell_width, row * cell_height, cell_width, cell_height))
else:
pygame.draw.rect(screen, WHITE, (col * cell_width, row * cell_height, cell_width, cell_height))
# 绘制玩家
pygame.draw.rect(screen, RED, (player_x * cell_width, player_y * cell_height, cell_width, cell_height))
# 更新屏幕
pygame.display.flip()
# 退出游戏
pygame.quit()
```
这段代码使用pygame库实现了一个简单的迷宫游戏。玩家通过键盘控制移动,目标是从起点到达终点。迷宫地图由二维数组表示,其中1表示墙壁,0表示通道。玩家通过改变player_x和player_y的值来移动位置。
阅读全文