使用Python实现的简单迷宫游戏
发布时间:2023-12-04 18:15:23
下面是一个使用Python实现的简单迷宫游戏的例子。这个游戏会生成一个迷宫,并允许用户在迷宫中移动,直到找到迷宫的终点。
import random
# 用于生成迷宫的类
class Maze:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.maze = [['#' for _ in range(cols)] for _ in range(rows)]
# 生成迷宫
def generate(self):
stack = [(0, 0)]
while stack:
cell = stack[-1]
row, col = cell
self.maze[row][col] = ' '
neighbors = self.get_neighbors(row, col)
if neighbors:
next_row, next_col = random.choice(neighbors)
self.remove_wall(cell, (next_row, next_col))
stack.append((next_row, next_col))
else:
stack.pop()
# 获取邻居单元格
def get_neighbors(self, row, col):
neighbors = []
if row > 1 and self.maze[row-2][col] == '#':
neighbors.append((row-2, col))
if col > 1 and self.maze[row][col-2] == '#':
neighbors.append((row, col-2))
if row < self.rows-2 and self.maze[row+2][col] == '#':
neighbors.append((row+2, col))
if col < self.cols-2 and self.maze[row][col+2] == '#':
neighbors.append((row, col+2))
return neighbors
# 移除两个单元格之间的墙
def remove_wall(self, current, next):
curr_row, curr_col = current
next_row, next_col = next
wall_row = (curr_row + next_row) // 2
wall_col = (curr_col + next_col) // 2
self.maze[wall_row][wall_col] = ' '
# 打印迷宫
def print_maze(self):
for row in self.maze:
print(''.join(row))
# 游戏主逻辑
def main():
rows = int(input("请输入迷宫的行数:"))
cols = int(input("请输入迷宫的列数:"))
# 生成迷宫
maze = Maze(rows, cols)
maze.generate()
maze.print_maze()
# 设置起点和终点
start = (0, 0)
end = (rows-1, cols-1)
while True:
direction = input("请输入移动的方向(w:上, a:左, s:下, d:右):")
row, col = start
if direction == 'w':
row -= 1
elif direction == 'a':
col -= 1
elif direction == 's':
row += 1
elif direction == 'd':
col += 1
if 0 <= row < rows and 0 <= col < cols and maze.maze[row][col] == ' ':
start = (row, col)
maze.maze[row][col] = 'o'
maze.print_maze()
if start == end:
print("恭喜你找到了迷宫的终点!")
break
else:
print("无法移动到该位置,请重新输入移动方向。")
# 运行游戏
if __name__ == "__main__":
main()
使用该代码,用户可以输入迷宫的行数和列数,然后程序会生成一个对应大小的迷宫。迷宫由#代表墙壁,空格代表通道。用户使用w、a、s、d键来移动,直到找到迷宫的终点。程序会不断打印迷宫的当前状态,直到游戏结束。
例如,如果用户输入了一个3x3的迷宫,程序可能生成以下迷宫:
####### # # # ### # # # # # # ### # # # #######
然后,用户可以输入w键向上移动,然后输入d键向右移动,直到达到迷宫的终点:
####### # # # ### # # # # # # ### # # o # #######
最后,程序会打印出“恭喜你找到了迷宫的终点!”的消息。
