赞
踩
在国外网站上找到一个练习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
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。