用Python编写推箱子游戏
时间: 2024-02-16 18:58:00 浏览: 137
推箱子游戏是一种经典的益智游戏,可以用Python编写。下面是一个简单的示例代码,演示了如何使用Python和tkinter模块来实现推箱子游戏:
```python
import tkinter as tk
# 游戏地图
map_data = [
"#####",
"#O .#",
"# @#",
"#####"
]
# 玩家的初始位置
player_x = 2
player_y = 2
def move(dx, dy):
global player_x, player_y
new_x = player_x + dx
new_y = player_y + dy
if map_data[new_y][new_x] != "#":
player_x = new_x
player_y = new_y
if map_data[new_y][new_x] == ".":
map_data[new_y] = map_data[new_y][:new_x] + " " + map_data[new_y][new_x+1:]
def key_press(event):
if event.keysym == "Up":
move(0, -1)
elif event.keysym == "Down":
move(0, 1)
elif event.keysym == "Left":
move(-1, 0)
elif event.keysym == "Right":
move(1, 0)
draw_map()
def draw_map():
canvas.delete("all")
for y in range(len(map_data)):
for x in range(len(map_data[y])):
if map_data[y][x] == "#":
canvas.create_rectangle(x*50, y*50, x*50+50, y*50+50, fill="gray")
elif map_data[y][x] == " ":
canvas.create_rectangle(x*50, y*50, x*50+50, y*50+50, fill="white")
elif map_data[y][x] == "O":
canvas.create_oval(x*50+10, y*50+10, x*50+40, y*50+40, fill="red")
elif map_data[y][x] == "@":
canvas.create_rectangle(x*50, y*50, x*50+50, y*50+50, fill="blue")
canvas.create_rectangle(player_x*50, player_y*50, player_x*50+50, player_y*50+50, fill="green")
# 创建窗口和画布
window = tk.Tk()
canvas = tk.Canvas(window, width=250, height=200)
canvas.pack()
# 绑定键盘事件
window.bind("<KeyPress>", key_press)
window.focus_set()
# 绘制初始地图
draw_map()
# 运行游戏
window.mainloop()
```
这段代码使用了tkinter模块创建了一个窗口和画布,通过键盘事件来控制玩家的移动。游戏地图使用一个二维列表来表示,其中"#"表示墙壁,"O"表示目标位置,"."表示已经推到目标位置的箱子,"@"表示玩家的位置。玩家可以通过上下左右箭头键来移动,目标是将所有的箱子推到目标位置上。
阅读全文