推箱子代码python
时间: 2023-10-13 20:23:02 浏览: 36
以下是一个简单的推箱子游戏的 Python 代码示例:
```python
# 定义地图
map = [
"#####",
"#O..#",
"#...#",
"#..P#",
"#####"
]
# 定义人和箱子的位置
player_pos = [3, 2]
box_pos = [2, 2]
# 渲染地图
def render_map():
for row in map:
print(row)
# 移动人和箱子
def move(pos, direction):
if direction == "up":
return [pos[0] - 1, pos[1]]
elif direction == "down":
return [pos[0] + 1, pos[1]]
elif direction == "left":
return [pos[0], pos[1] - 1]
elif direction == "right":
return [pos[0], pos[1] + 1]
else:
return pos
# 判断是否可以移动箱子
def can_move_box(box_pos, direction):
new_box_pos = move(box_pos, direction)
if map[new_box_pos[0]][new_box_pos[1]] == ".":
return True
else:
return False
# 推箱子的主循环
while True:
# 渲染地图
render_map()
# 判断是否完成游戏
if map[box_pos[0]][box_pos[1]] == ".":
print("You win!")
break
# 获取用户输入
direction = input("Which way? (up, down, left, right)").lower()
# 移动人
new_player_pos = move(player_pos, direction)
if map[new_player_pos[0]][new_player_pos[1]] == "#":
print("You can't move there!")
continue
# 移动箱子
if new_player_pos == box_pos:
if can_move_box(box_pos, direction):
new_box_pos = move(box_pos, direction)
box_pos = new_box_pos
else:
print("You can't move there!")
continue
# 更新人的位置
player_pos = new_player_pos
```
这只是一个简单的示例,你可以根据你的需要进行修改和扩展。