python地牢游戏代码
时间: 2023-06-23 22:09:12 浏览: 294
这是一个简单的 Python 地牢游戏代码,可以供你参考:
```python
import random
# 游戏地图大小
MAP_SIZE = 10
# 玩家初始位置
player_pos = [0, 0]
# 地牢中的金币和陷阱
dungeon = [
['*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', '*', ' ', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', '*', ' ', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '*', ' '],
[' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '*']
]
def draw_map():
"""
绘制地图,用 X 表示玩家位置,* 表示金币或陷阱
"""
for i in range(MAP_SIZE):
for j in range(MAP_SIZE):
if player_pos == [i, j]:
print('X', end=' ')
else:
print(dungeon[i][j], end=' ')
print()
def move_player(direction):
"""
移动玩家
"""
if direction == 'up' and player_pos[0] > 0:
player_pos[0] -= 1
elif direction == 'down' and player_pos[0] < MAP_SIZE - 1:
player_pos[0] += 1
elif direction == 'left' and player_pos[1] > 0:
player_pos[1] -= 1
elif direction == 'right' and player_pos[1] < MAP_SIZE - 1:
player_pos[1] += 1
else:
print('Invalid move!')
def play_game():
"""
游戏主循环
"""
while True:
draw_map()
command = input('Enter a command: ')
if command in ['up', 'down', 'left', 'right']:
move_player(command)
if dungeon[player_pos[0]][player_pos[1]] == '*':
if random.random() < 0.5:
print('You got a coin!')
else:
print('You fell into a trap!')
dungeon[player_pos[0]][player_pos[1]] = ' '
elif command == 'quit':
break
else:
print('Invalid command!')
if __name__ == '__main__':
play_game()
```
运行代码后,你可以使用 `up`、`down`、`left`、`right` 四个指令来移动玩家,尝试抵达地图的右下角。在玩家移动时,如果当前位置有金币或陷阱,将有 50% 的概率获得金币并将该位置标记为空,有 50% 的概率掉入陷阱并将该位置标记为空。如果你输入 `quit` 指令,游戏将结束。
阅读全文