pygame做随机沙盘高难度迷宫游戏+计时器
时间: 2025-06-25 18:00:33 浏览: 5
以下是一个使用 `pygame` 实现的随机沙盘高难度迷宫游戏,并带有计时器功能的完整代码示例:
```python
import pygame
import random
import time
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("随机沙盘高难度迷宫游戏")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 迷宫参数
CELL_SIZE = 20
ROWS = HEIGHT // CELL_SIZE
COLS = WIDTH // CELL_SIZE
# 计时器
start_time = None
# 创建迷宫
class Maze:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.grid = [[Cell(x, y) for y in range(cols)] for x in range(rows)]
self.generate_maze(0, 0)
def generate_maze(self, x, y):
stack = [(x, y)]
visited = set()
visited.add((x, y))
while stack:
current = stack[-1]
neighbors = self.get_unvisited_neighbors(current[0], current[1], visited)
if neighbors:
next_cell = random.choice(neighbors)
self.remove_wall(current[0], current[1], next_cell[0], next_cell[1])
visited.add(next_cell)
stack.append(next_cell)
else:
stack.pop()
def get_unvisited_neighbors(self, x, y, visited):
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
neighbors = []
for dx, dy in directions:
nx, ny = x + dx * 2, y + dy * 2
if 0 <= nx < self.rows and 0 <= ny < self.cols and (nx, ny) not in visited:
neighbors.append((nx, ny))
return neighbors
def remove_wall(self, x1, y1, x2, y2):
mid_x = (x1 + x2) // 2
mid_y = (y1 + y2) // 2
self.grid[mid_x][mid_y].walls = False
def draw(self, screen):
for row in self.grid:
for cell in row:
cell.draw(screen)
class Cell:
def __init__(self, x, y):
self.x = x
self.y = y
self.walls = True
def draw(self, screen):
if self.walls:
rect = pygame.Rect(self.y * CELL_SIZE, self.x * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, BLACK, rect)
else:
rect = pygame.Rect(self.y * CELL_SIZE, self.x * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, WHITE, rect)
# 主程序
def main():
global start_time
maze = Maze(ROWS, COLS)
player_pos = [1, 1]
end_pos = [ROWS - 2, COLS - 2]
running = True
start_time = time.time()
while running:
screen.fill(BLACK)
maze.draw(screen)
# 绘制玩家
player_rect = pygame.Rect(player_pos[1] * CELL_SIZE, player_pos[0] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, RED, player_rect)
# 绘制终点
end_rect = pygame.Rect(end_pos[1] * CELL_SIZE, end_pos[0] * CELL_SIZE, CELL_SIZE, CELL_SIZE)
pygame.draw.rect(screen, GREEN, end_rect)
# 显示计时器
elapsed_time = int(time.time() - start_time)
font = pygame.font.Font(None, 36)
text = font.render(f"Time: {elapsed_time} seconds", True, WHITE)
screen.blit(text, (10, 10))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and maze.grid[player_pos[0] - 1][player_pos[1]].walls is False:
player_pos[0] -= 1
if keys[pygame.K_DOWN] and maze.grid[player_pos[0] + 1][player_pos[1]].walls is False:
player_pos[0] += 1
if keys[pygame.K_LEFT] and maze.grid[player_pos[0]][player_pos[1] - 1].walls is False:
player_pos[1] -= 1
if keys[pygame.K_RIGHT] and maze.grid[player_pos[0]][player_pos[1] + 1].walls is False:
player_pos[1] += 1
# 检查是否到达终点
if player_pos == end_pos:
print(f"恭喜!你完成了迷宫,用时 {elapsed_time} 秒")
running = False
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
```
### 上述代码解释:
1. **迷宫生成**:我们使用了递归回溯算法(深度优先搜索)来生成迷宫。每个单元格可以看作一个节点,通过随机选择未访问过的邻居并移除墙壁来构建路径。
2. **计时器**:使用 Python 的 `time` 模块记录玩家从开始到完成迷宫所花费的时间。
3. **玩家移动**:玩家可以通过键盘的方向键(上、下、左、右)进行移动,但只能在没有墙壁的地方移动。
4. **终点检测**:当玩家到达指定的终点位置时,游戏结束并显示完成时间。
---
###
阅读全文
相关推荐
















