使用Python实现迷宫游戏
发布时间:2023-12-04 13:29:40
下面是一个用Python实现迷宫游戏的示例。在这个示例中,我们将使用Tkinter库来创建游戏界面,并使用深度优先搜索算法生成迷宫。
import tkinter as tk
import random
# 迷宫类
class MazeGame:
def __init__(self, rows, cols):
self.rows = rows
self.cols = cols
self.maze = [[True] * (cols * 2 + 1) for _ in range(rows * 2 + 1)]
self.generate_maze()
# 在迷宫中随机挖墙
def generate_maze(self):
stack = [(0, 0)]
visited = set()
while stack:
x, y = stack[-1]
visited.add((x, y))
neighbors = []
if x > 1 and (x - 2, y) not in visited:
neighbors.append((x - 2, y))
if y > 1 and (x, y - 2) not in visited:
neighbors.append((x, y - 2))
if x < self.rows * 2 - 1 and (x + 2, y) not in visited:
neighbors.append((x + 2, y))
if y < self.cols * 2 - 1 and (x, y + 2) not in visited:
neighbors.append((x, y + 2))
if neighbors:
nx, ny = random.choice(neighbors)
self.maze[nx][ny] = False
self.maze[(nx + x) // 2][(ny + y) // 2] = False
stack.append((nx, ny))
else:
stack.pop()
# 检查指定位置是否是通路
def is_path(self, x, y):
return not self.maze[x][y]
# 游戏界面
def create_game(self):
window = tk.Tk()
canvas = tk.Canvas(window, width=self.cols * 20, height=self.rows * 20)
canvas.pack()
for i in range(1, self.rows * 2, 2):
for j in range(1, self.cols * 2, 2):
if self.is_path(i, j):
canvas.create_rectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20, fill='white')
else:
canvas.create_rectangle(j * 20, i * 20, (j + 1) * 20, (i + 1) * 20, fill='black')
def on_key_press(event):
x, y = 1, 1
if event.keysym == 'Up':
x, y = -1, 0
elif event.keysym == 'Down':
x, y = 1, 0
elif event.keysym == 'Left':
x, y = 0, -1
elif event.keysym == 'Right':
x, y = 0, 1
nx, ny = canvas.coords(player)[0] // 20 + x, canvas.coords(player)[1] // 20 + y
if nx > 0 and nx < self.rows * 2 - 1 and ny > 0 and ny < self.cols * 2 - 1 and self.is_path(nx, ny):
canvas.move(player, 20 * x, 20 * y)
if nx == self.rows * 2 - 2 and ny == self.cols * 2 - 2:
canvas.create_text(self.cols * 20 - 10, self.rows * 20 - 10, text='Congratulations!', fill='red')
player = canvas.create_rectangle(20, 20, 40, 40, fill='blue')
canvas.bind_all('<KeyPress>', on_key_press)
canvas.focus_set()
window.mainloop()
# 创建一个10行10列的迷宫游戏
maze = MazeGame(10, 10)
maze.create_game()
上述代码使用了深度优先搜索算法来生成迷宫。迷宫游戏界面使用Tkinter库创建,每个方块的大小为20像素。玩家使用键盘的箭头键来控制蓝色方块在迷宫中移动,目标是到达迷宫的出口。
在MazeGame类中,generate_maze方法使用stack和visited来生成迷宫。利用random.choice随机选择邻居节点,并更新墙壁。
create_game方法通过Tkinter库创建了游戏界面,并根据MazeGame中的is_path方法来绘制迷宫。同时,该方法定义了on_key_press函数,用于捕捉键盘输入并移动玩家方块。最后,通过调用mainloop来运行游戏界面。
可以根据需要调整MazeGame的初始化参数和create_game方法中创建的迷宫大小。
