python推箱子游戏代码
时间: 2023-09-05 12:09:54 浏览: 86
很高兴为您解答问题。以下是一个简单的 Python 推箱子游戏代码示例:
```python
# 定义地图
map = [['#', '#', '#', '#', '#', '#', '#', '#', '#', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', '.', '.', '#', '.', ' ', ' ', ' ', '#'],
['#', ' ', '.', '@', '#', '.', ' ', ' ', ' ', '#'],
['#', ' ', '.', '.', '.', '.', ' ', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'],
['#', '#', '#', '#', '#', '#', '#', '#', '#', '#']]
# 定义角色坐标
role_x = 4
role_y = 3
# 游戏主循环
while True:
# 显示地图
for i in range(len(map)):
for j in range(len(map[i])):
print(map[i][j], end='')
print()
# 判断是否胜利
win = True
for i in range(len(map)):
for j in range(len(map[i])):
if map[i][j] == '.':
win = False
break
if not win:
break
if win:
print('Congratulations! You win!')
break
# 获取操作
direction = input('Please input direction(w, a, s, d):')
if direction == 'w':
next_y = role_y - 1
next_x = role_x
elif direction == 'a':
next_y = role_y
next_x = role_x - 1
elif direction == 's':
next_y = role_y + 1
next_x = role_x
elif direction == 'd':
next_y = role_y
next_x = role_x + 1
else:
print('Invalid input!')
continue
# 判断是否越界
if next_x < 0 or next_x >= len(map[0]) or next_y < 0 or next_y >= len(map):
print('You hit the wall!')
continue
# 判断下一个位置的物品类型
item = map[next_y][next_x]
if item == ' ':
map[next_y][next_x] = '@'
map[role_y][role_x] = ' '
role_x = next_x
role_y = next_y
elif item == '.':
# 判断箱子是否能移动
next_box_x = next_x + (next_x - role_x)
next_box_y = next_y + (next_y - role_y)
if next_box_x < 0 or next_box_x >= len(map[0]) or next_box_y < 0 or next_box_y >= len(map):
print('You cannot push the box to there!')
continue
if map[next_box_y][next_box_x] == ' ':
map[next_y][next_x] = '@'
map[role_y][role_x] = ' '
map[next_box_y][next_box_x] = '.'
role_x = next_x
role_y = next_y
else:
print('You cannot push the box to there!')
else:
print('Invalid operation!')
```
希望能帮到您,有任何问题欢迎随时提出。
阅读全文