完整的推箱子python代码
时间: 2023-07-23 17:35:24 浏览: 341
以下是一个比较完整的推箱子游戏的 Python 代码示例,包括地图编辑器和游戏关卡的加载:
```python
import os
# 定义地图
maps = [
[
"#####",
"# #",
"# #",
"#O #",
"#####"
],
[
"#######",
"# #",
"#O # #",
"# ## #",
"# #",
"###X###",
],
# 在这里添加更多的关卡
]
# 定义地图编辑器
def edit_map(map):
x, y = 0, 0
while True:
os.system("cls" if os.name == "nt" else "clear") # 清屏
# 打印地图
for row in map:
print(row)
# 打印帮助信息
print("w: Up, s: Down, a: Left, d: Right")
print("x: Wall, o: Box, p: Player, .: Goal, q: Quit")
# 接收用户输入
command = input("Command: ")
if command == "q":
break
if command == "w":
y = max(y - 1, 0)
elif command == "s":
y = min(y + 1, len(map) - 1)
elif command == "a":
x = max(x - 1, 0)
elif command == "d":
x = min(x + 1, len(map[0]) - 1)
elif command == "x":
map[y] = map[y][:x] + "#" + map[y][x+1:]
elif command == "o":
map[y] = map[y][:x] + "O" + map[y][x+1:]
elif command == "p":
map[y] = map[y][:x] + "P" + map[y][x+1:]
elif command == ".":
map[y] = map[y][:x] + "." + map[y][x+1:]
# 定义游戏关卡
class Level:
def __init__(self, map):
self.map = map
self.player = None
self.boxes = []
self.goals = []
for y in range(len(map)):
for x in range(len(map[y])):
if map[y][x] == "P":
self.player = (x, y)
elif map[y][x] == "O":
self.boxes.append((x, y))
elif map[y][x] == ".":
self.goals.append((x, y))
# 移动函数
def move(self, dx, dy):
x, y = self.player
nx, ny = x + dx, y + dy
if self.map[ny][nx] == "#":
return False
if (nx, ny) in self.boxes:
bx, by = nx + dx, ny + dy
if self.map[by][bx] == "#" or (bx, by) in self.boxes:
return False
self.boxes.remove((nx, ny))
self.boxes.append((bx, by))
self.player = (nx, ny)
return True
# 检查是否完成游戏
def is_win(self):
return all(box in self.goals for box in self.boxes)
# 定义主循环
def main():
# 打印欢迎信息
print("Welcome to Sokoban!")
print("e: Edit Map, q: Quit")
while True:
# 打印关卡列表
print("Levels:")
for i, map in enumerate(maps):
print(f"{i+1}. {len(map[0])}x{len(map)}")
# 接收用户输入
command = input("Command: ")
if command == "q":
break
elif command == "e":
# 进入地图编辑模式
map = maps[0] # 编辑第一个关卡
edit_map(map)
maps[0] = map # 保存修改后的地图
else:
try:
level_num = int(command) - 1
if level_num < 0 or level_num >= len(maps):
raise ValueError
# 加载游戏关卡
level = Level(maps[level_num])
while True:
os.system("cls" if os.name == "nt" else "clear") # 清屏
# 打印地图
for y in range(len(level.map)):
for x in range(len(level.map[y])):
if (x, y) in level.boxes:
print("O", end="")
elif (x, y) == level.player:
print("P", end="")
elif (x, y) in level.goals:
print(".", end="")
else:
print(level.map[y][x], end="")
print()
# 检查是否完成游戏
if level.is_win():
print("You win!")
break
# 接收用户输入并移动人物
move_input = input("Move: ")
dx, dy = 0, 0
if move_input == "w":
dy = -1
elif move_input == "s":
dy = 1
elif move_input == "a":
dx = -1
elif move_input == "d":
dx = 1
else:
continue
level.move(dx, dy)
except ValueError:
continue
if __name__ == "__main__":
main()
```
这个示例包含了地图编辑器和游戏关卡的加载,以及一个简单的主循环,支持多个游戏关卡。您可以根据需要进行调整和扩展,例如添加更多的关卡或者改进游戏界面。
阅读全文