python实现推箱子代码
时间: 2024-05-02 18:15:20 浏览: 180
推箱子是一种经典的益智游戏,可以使用Python来实现。以下是一个简单的推箱子代码示例:
```python
# 定义地图
map = [
"#####",
"#O #",
"# #",
"# #",
"#####"
]
# 定义玩家初始位置
player_x = 1
player_y = 1
# 游戏主循环
while True:
# 打印地图
for row in map:
print(row)
# 判断是否胜利
if map == "O":
print("恭喜你,胜利了!")
break
# 获取玩家输入
move = input("请输入移动方向:(w上 s下 a左 d右)")
# 移动玩家
if move == "w" and map[player_y - 1][player_x] != "#":
map[player_y][player_x] = " "
player_y -= 1
elif move == "s" and map[player_y + 1][player_x] != "#":
map[player_y][player_x] = " "
player_y += 1
elif move == "a" and map[player_y][player_x - 1] != "#":
map[player_y][player_x] = " "
player_x -= 1
elif move == "d" and map[player_y][player_x + 1] != "#":
map[player_y][player_x] = " "
player_x += 1
# 判断是否推动箱子
if map[player_y][player_x] == "O":
if move == "w" and map[player_y - 1][player_x] != "#":
map[player_y - 1][player_x] = "O"
elif move == "s" and map[player_y + 1][player_x] != "#":
map[player_y + 1][player_x] = "O"
elif move == "a" and map[player_y][player_x - 1] != "#":
map[player_y][player_x - 1] = "O"
elif move == "d" and map[player_y][player_x + 1] != "#":
map[player_y][player_x + 1] = "O"
# 更新玩家位置
map[player_y][player_x] = "P"
```
这段代码实现了一个简单的推箱子游戏,玩家可以通过输入"w"、"s"、"a"、"d"来控制角色的移动,目标是将箱子推到指定位置。如果成功将箱子推到指定位置,游戏结束并提示胜利。
阅读全文