所以首先我要感謝大家之前幫助過我。在深入挖掘了我之前理解的問題后,有很多人幫助我有了更好的理解。所以我提前為問了這么多問題道歉,但老實說,這是我的學習方式,我覺得從長遠來看,這會讓我成為一個更好的編碼員。
說我理解我在底部代碼中遇到的問題。基本上是因為我在key=item撿起物品時將其洗掉。然后,如果用戶不小心使用了相同的“獲取”專案”或任何圍繞“獲取”的東西,它只會回傳一個錯誤說key error: Item
所以我想知道是否有人對如何解決這個問題有任何想法?
# print a main menu and the commands
print("Halo Text Adventure Game")
print("Collect 6 items to win the game, or be eaten by Gravemind.")
print("Move commands: go South, go North, go East, go West")
print("Add to Inventory: get 'item name'")
def movement_between_locations(location, action, rooms):
location = rooms[location][action]
return location
def get_item(location, action, rooms, equipment):
equipment.append(rooms[location]['item'])
del rooms[location]['item']
return rooms, equipment, location , action
def main():
rooms = {
'Halo': {'South': 'The Silent Cartographer', 'North': 'Assault on the Control Room',
'East': 'Pillar of Autumn', 'West': 'The Library'},
'The Silent Cartographer': {'North': 'Halo', 'East': '343 Guilty Spark', 'item': 'Camo'},
'343 Guilty Spark': {'West': 'The Silent Cartographer', 'item': 'Energy Sword'},
'The Maw': {'South': 'Pillar of Autumn', 'item': 'Gravemind'},
'The Library': {'East': 'Halo', 'item': 'Frag Grenade'},
'Assault on the Control Room': {'South': 'Halo', 'East': 'Two Betrayals', 'item': 'Rocket Launcher'},
'Two Betrayals': {'West': 'Assault on the Control Room', 'item': 'Plasma Grenade'},
'Pillar of Autumn': {'West': 'Halo', 'North': 'The Maw', 'item': 'Over Shield'},
}
location = 'Halo'
equipment = []
show_instructions()
while True:
# Checking user_action and connecting to new room, or if they typed get item, item is received
if location == "The Maw":
# User wins
if len(equipment) == 6:
print("You won")
break
else:
print("You lost")
break
# Display players room, equipment,
print("You are in the " location)
print(equipment)
print("-" * 20)
# This will tell user if there is an item in the room
if location != 'The Maw' and 'item' in rooms[location].keys():
print('You see the {}'.format(rooms[location]['item']))
action = input("Enter your move:").title().split()
if len(action) >= 2 and action[1] in rooms[location].keys():
location = movement_between_locations(location, action[1], rooms)
continue
elif len(action[0]) == 3 and action[0] == "Get" and ' '.join(action[1:]) in rooms[location]['item']:
print("You picked up the {}!".format(rooms[location]['item']))
print('-' * 20)
get_item(location, action, rooms, equipment)
continue
else:
print("invalid input")
continue
main() ```
uj5u.com熱心網友回復:
您可以在獲取之前檢查:
def get_item(location, action, rooms, equipment):
try:
item = rooms[location]['item']
except:
return # do something here
equipment.append(item)
del rooms[location]['item']
return rooms, equipment, location , action
uj5u.com熱心網友回復:
從字典中洗掉專案時,您可以使用該dict.pop方法,該方法包含一個默認引數,用于在鍵不存在時回傳的內容:
def get_item(location, action, rooms, equipment):
# Gets removed from the dictionary here
# and if the key doesn't exist, it returns the second arg (None)
item = rooms[location].pop('item', None)
if item is not None:
equipment.append(item)
return rooms, equipment, location , action
但是,您實際上并不需要大部分引數。您只需要roomsand location,您可以回傳item并將其附加到equipment稍后:
# Get rid of unnecessary arguments
def get_item(location, rooms):
# Gets removed from the dictionary here
# and if the key doesn't exist, it returns the second arg (None)
return rooms[location].pop('item', None)
# Wherever you call `get_item` is how this code gets used
item = get_item(rooms, location)
if item is not None:
equipment.append(item)
uj5u.com熱心網友回復:
你說過在你的游戲中,一個房間最多只有一件物品,或者沒有。然后在您的資料模型中反映這一點是有意義的:
def main():
rooms = {
'Halo': {'South': 'The Silent Cartographer', 'North': 'Assault on the Control Room',
'East': 'Pillar of Autumn', 'West': 'The Library', 'item': None},
'The Silent Cartographer': {'North': 'Halo', 'East': '343 Guilty Spark', 'item': 'Camo'},
...
請注意房間的'item'字典鍵'Halo'的值是None(not 'None'),表示那里沒有專案。
現在您可以使用:
def get_item(location, action, rooms, equipment):
if item is not None:
equipment.append(rooms[location]['item'])
rooms[location]['item'] = None
return rooms, equipment, location, action
通過將值設定為None,但不洗掉密鑰,您仍然可以稍后檢查密鑰以檢查None,或者如果玩家可以丟棄一個新專案,則分配一個新專案。同樣,您可以只說“沒有 'item' 鍵”意味著沒有專案。在這種情況下,您不會更改房間定義,您可以:
def get_item(location, action, rooms, equipment):
if 'item' not in rooms[location]:
equipment.append(rooms[location]['item'])
del(rooms[location]['item'])
return rooms, equipment, location, action
只要確保您始終檢查可能不存在的密鑰的存在,無論您嘗試在代碼中讀取它們的任何位置。
當然,如果玩家試圖拿起不存在的物品等,您可以添加更多代碼來撰寫訊息。但我認為這個想法很清楚。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377077.html
