在国外网站上找到一个练习Python的小游戏感觉不错,自己实现了一下。
通过该练习你能学到:
- 元组
- 字典
- 简单定义函数和封装
- 条件控制语句
游戏说明
以下是3个房间和1个花园:
Hall 客厅 有一把钥匙,Kitchen 厨房 有一只怪物,Dinning Room 餐厅 有一瓶药水,Garden 花园
完成游戏条件:拿到钥匙和药水到达花园并躲避怪物。
游戏操作指令:
go [direction]
get [item]
[direction] 包含:east, west, south, north
[item] 包含:key, potion
游戏源码
#! python3
"""
author: laoxu
"""# 游戏说明
def showInstructions():print('''RPG Game========完成游戏条件:拿到钥匙和药水到达花园并躲避怪物。命令:go [direction]get [item]''')# 打印当前房间和背包信息
def showCurrentRoom(room, bag):print('You are in the %s' % room)print('Inventory: ', bag)rooms = {'Hall': {'south': 'Kitchen','east': 'Dinning Room','item': 'key'},'Kitchen': {'north': 'Hall','item': 'monster'},'Dinning Room': {'west': 'Hall','south': 'Garden','item': 'potion'},'Garden': {'north': 'Dinning Room'}
}# 初始化房间
currentRoom = 'Hall'# 初始化物品栏
inventory = []# 打印游戏帮助
showInstructions()print('You are in the %s' % currentRoom)
print('Inventory: ', inventory)
print('You see a key')while True:# 玩家进入厨房,游戏结束if 'item' in rooms[currentRoom] and 'monster' in rooms[currentRoom]['item']:print('你被怪物抓住了...游戏结束!')break# 玩家拿到钥匙和药水进入花园,游戏结束if currentRoom == 'Garden' and 'key' in inventory and 'potion' in inventory:print('你逃脱了房子!你赢了!')break# 接收操作步骤step = input()# 客厅->厨房if currentRoom == 'Hall' and step == 'go south':currentRoom = 'Kitchen'continue# 客厅->餐厅elif currentRoom == 'Hall' and step == 'go east':currentRoom = 'Dinning Room'# 厨房->客厅elif currentRoom == 'Kitchen' and step == 'go north':currentRoom = 'Hall'# 餐厅->客厅elif currentRoom == 'Dinning Room' and step == 'go west':currentRoom = 'Hall'# 餐厅->花园elif currentRoom == 'Dinning Room' and step == 'go south':currentRoom = 'Garden'# 花园->餐厅elif currentRoom == 'Garden' and step == 'go north':currentRoom = 'Dinning Room'# 拿到钥匙elif currentRoom == 'Hall' and 'key' not in inventory and step == 'get key':inventory.append('key')print('key got!')# 拿到药水elif currentRoom == 'Dinning Room' and 'potion' not in inventory and step == 'get potion':inventory.append('potion')print('potion got!')# 打印房间和物品栏showCurrentRoom(currentRoom, inventory)if currentRoom == 'Hall' and 'key' not in inventory:print('You see a key')if currentRoom == 'Dinning Room' and 'potion' not in inventory:print('You see a potion')continue
运行效果