大家好,我正在為一個班級構建一個基于文本的游戲,我在房間之間移動并嘗試收集所有物品而無需與惡棍一起進入房間,在這種情況下是唱片執行官,我只是在直接訪問該物品時遇到問題我可以將其添加到我的庫存清單中。
這是我的字典:
rooms = {
'Lobby':{'East': 'Bar'},
'Roof':{'South': 'Bar', 'East': 'Stage', 'Item': 'Steel guitar'},
'Bar':{'West': 'Lobby', 'North': 'Roof', 'East': 'Bathroom', 'South': 'Basement', 'Item': 'Keyboard'},
'Basement':{'North': 'Bar', 'East': 'Studio', 'Item': 'Drums'},
'Stage':{'West': 'Roof', 'Item': 'Microphone'},
'Soundcheck':{'South': 'Bathroom', 'Item': 'Bass Guitar'},
'Bathroom':{'North': 'Soundcheck', 'West': 'Bar', 'Item': 'Electric Guitar'},
'Studio': {'West': 'Basement', 'Item': 'Record Executive'}
}
繼承人我的運動代碼:
while gameOver != True:
playerStats(currentRoom, inventory, rooms)
# currentRoom
playerMove = input('Enter your move:\n')
try:
currentRoom = rooms[currentRoom][playerMove]
except Exception:
print('Invalid move')
continue
我從大廳向東移動,我當前的房間像它應該的那樣更改為酒吧,但我不知道如何進入其中的“專案”屬性,因此我可以將“鍵盤”添加到我的庫存串列中......任何幫助都會非常感激!!謝謝你
uj5u.com熱心網友回復:
索引你想要的字典
currentRoom['Item']
你將它添加到串列中后做的舉動,所以在最后(以下簡稱“嘗試”,“除”,后一部分),你會增加:
inventory.append(currentRoom['Item'])
通過將它放在移動代碼之后,您可以從新房間而不是現有房間中取出物品。
有些房間可能沒有物品,所以你可以這樣做:
try:
inventory.append(currentRoom['Item'])
except KeyError:
pass
這可以防止您在沒有物品的情況下進入房間時出錯。
此外,您可能想在拿走物品時將其從房間中取出。所以你可以做到。
try:
inventory.append(currentRoom['Item'])
del currentRoom['Item']
except KeyError:
pass
該del去除的詞典中的關鍵
順便說一句,在你的運動代碼中,你也應該改變
except Exception:
到
except KeyError:
因此,如果存在不同的例外(例如,您按 ctrl-C),則它不會捕獲它。
uj5u.com熱心網友回復:
就像這個命令
currentRoom = rooms[currentRoom][playerMove]
您可以嘗試將房間中的專案附加到變數(庫存),最好是串列(如果滿足您的要求,則為一組)
inventory = []
for i in rooms:
for j in i:
if j == 'Item':
inventory.append(rooms[i][j])
現在它看起來像這樣:
inventory = []
gameOver = False
rooms = {
'Lobby':{'East': 'Bar'},
'Roof':{'South': 'Bar', 'East': 'Stage', 'Item': 'Steel guitar'},
'Bar':{'West': 'Lobby', 'North': 'Roof', 'East': 'Bathroom', 'South': 'Basement', 'Item': 'Keyboard'},
'Basement':{'North': 'Bar', 'East': 'Studio', 'Item': 'Drums'},
'Stage':{'West': 'Roof', 'Item': 'Microphone'},
'Soundcheck':{'South': 'Bathroom', 'Item': 'Bass Guitar'},
'Bathroom':{'North': 'Soundcheck', 'West': 'Bar', 'Item': 'Electric Guitar'},
'Studio': {'West': 'Basement', 'Item': 'Record Executive'}
}
while not gameOver:
playerStats(currentRoom, inventory, rooms)
# currentRoom
playerMove = input('\n Enter your move: ')
if playerMove == 'pick' or playerMove == 'acquire' or playerMove == 'get':
# add to inventory if exists
for i in rooms:
for j in i:
if j == 'Item':
inventory.append(rooms[i][j])
else:
print('nothing to pick')
else:
try:
currentRoom = rooms[currentRoom][playerMove]
except Exception:
print('Invalid move')
continue
編輯:
此外,您現在應該從房間中洗掉該專案,因為它現在已獲得--
(正如@Addlestrop 在他們的回答中指出的那樣)
for i in rooms:
for j in i:
if j == 'Item':
inventory.append(rooms[i][j])
del rooms[i][j]
# copy item to inventory and delete from the room
else:
print('nothing to pick')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/369001.html
上一篇:Python求冪運算子
下一篇:如何在python中比較兩個日期
