写一段游戏代码,主题为神秘森林,用Python写
时间: 2024-02-13 17:04:20 浏览: 28
好的,以下是一段使用 Python 编写的神秘森林游戏代码:
```python
import random
# 定义游戏地图
game_map = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
# 随机生成3个树木坐标
for i in range(3):
x = random.randint(0, 4)
y = random.randint(0, 4)
game_map[x][y] = 1
# 随机生成1个宝藏坐标
x = random.randint(0, 4)
y = random.randint(0, 4)
game_map[x][y] = 2
# 定义玩家初始位置
player_x = 0
player_y = 0
# 游戏循环
while True:
# 打印地图
for row in game_map:
print(row)
# 获取玩家移动方向
direction = input("请选择移动方向(上:w,下:s,左:a,右:d):")
# 根据玩家移动方向更新玩家位置
if direction == 'w':
player_x -= 1
elif direction == 's':
player_x += 1
elif direction == 'a':
player_y -= 1
elif direction == 'd':
player_y += 1
# 判断玩家是否越界
if player_x < 0 or player_x > 4 or player_y < 0 or player_y > 4:
print("你走出了神秘森林,游戏结束!")
break
# 判断玩家是否遇到树木
if game_map[player_x][player_y] == 1:
print("你撞到了树木,无法前进!")
# 判断玩家是否找到宝藏
if game_map[player_x][player_y] == 2:
print("你找到了宝藏,游戏胜利!")
break
```
以上代码实现了一个简单的神秘森林游戏,玩家需要通过键盘输入移动方向,避开树木,寻找宝藏。游戏循环持续进行直到玩家走出森林或找到宝藏。