Python 迷宫游戏:用代码构建你的冒险之旅
以下是一个使用 Python 编写简单的迷宫游戏示例:
import random
# 创建迷宫类
class Maze:
def __init__(self, size):
self.size = size
self.maze = [['#' for _ in range(size)] for _ in range(size)]
def generate(self):
stack = []
visited = set()
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
x, y = random.randint(0, self.size-1), random.randint(0, self.size-1)
stack.append((x, y))
visited.add((x, y))
while stack:
x, y = stack[-1]
neighbors = []
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < self.size and 0 <= ny < self.size and (nx, ny) not in visited:
count = 0
for dx, dy in directions:
nnx, nny = nx + dx, ny + dy
if 0 <= nnx < self.size and 0 <= nny < self.size and (nnx, nny) in visited:
count += 1
if count == 1:
neighbors.append((nx, ny))
if neighbors:
nx, ny = random.choice(neighbors)
self.maze[nx][ny] = ' '
stack.append((nx, ny))
visited.add((nx, ny))
else:
stack.pop()
self.maze[0][0] = 'S'
self.maze[self.size-1][self.size-1] = 'E'
def display(self):
for row in self.maze:
print(' '.join(row))
def play(self):
x, y = 0, 0
self.maze[x][y] = 'X'
self.display()
while (x, y) != (self.size-1, self.size-1):
move = input('Enter your move (W/A/S/D): ')
if move == 'W' and x > 0 and self.maze[x-1][y] != '#':
self.maze[x][y] = ' '
x -= 1
elif move == 'A' and y > 0 and self.maze[x][y-1] != '#':
self.maze[x][y] = ' '
y -= 1
elif move == 'S' and x < self.size-1 and self.maze[x+1][y] != '#':
self.maze[x][y] = ' '
x += 1
elif move == 'D' and y < self.size-1 and self.maze[x][y+1] != '#':
self.maze[x][y] = ' '
y += 1
self.maze[x][y] = 'X'
self.display()
print('Congratulations! You have reached the exit.')
# 创建迷宫对象并生成迷宫
maze = Maze(10)
maze.generate()
# 开始游戏
maze.play()
这个迷宫游戏使用 '#' 表示墙壁,' ' 表示通路,'S' 表示起点,'E' 表示终点,'X' 表示玩家的当前位置。玩家通过键盘输入'W/A/S/D'来移动,直到到达终点位置。游戏结束时会显示恭喜信息。
原文地址: https://www.cveoy.top/t/topic/p6IO 著作权归作者所有。请勿转载和采集!