我的程序是一個冒險遊戲藥水和箱子。我將這些設置在列表中,因此當用戶喝了一劑藥水或打開一個箱子時,我可以使用pop()
將它從列表中刪除。當用戶在同一個房間裏時,這可以正常工作,但是如果他們回到房間,他們可以再次使用該藥水或胸部。列表和流行()不工作,因爲我期望
僞代碼,系統應工作是這樣的:
if potions:
if there are still potions in the list:
drink potion
potions.pop()
else:
print "There are no potions left."
else:
print "There are no potions to drink."
我認爲正在發生的事情是,當我從列表彈出藥水,if potions
不計算到爲真,它會自動進入到其他區塊,但我不確定它爲什麼這樣做,我也不確定爲什麼當我回到房間時,列表會自動重置。
這很可能是因爲我沒有完全理解列表或pop方法是如何工作的,所以如果有人能夠澄清那會很好。 謝謝!
編輯真正的代碼從OP的鏈接
if room.potions:
if len(room.potions) > 0: # if there are potions left
if hasattr(room.potions[0], 'explode'): # if the potion is a bomb
room.potions[0].explode(You) # explode using zeroeth item from the list
room.potions[0].pop # remove zeroeth item from the list`
else:
room.potions[0].heal(You) # heal using zeroeth potion from the list
room.potions.pop(0) # remove zeroeth item from the list
else:
print "There are no more potions to drink"
else:
print "There are no potions to drink"
編輯:解決
我的問題是,當我把在詞典中的參數,我把整個房間作爲一個他們,認爲我能夠使用它的一切都很好。但是,每次我這樣做,它都會將空間設置爲init,從而有效地破壞我正在嘗試做的事情。我爲魔藥和胸部添加了單獨的參數,現在它完美地工作。 謝謝@Bernie提供的有用建議可以讓我看到錯誤。 也謝謝你@你的建議和提示。 ,
if potions: # same as len(potions) > 0
# drink potion
potions.pop()
else:
print "There are no potions to drink."
所以,檢查是否有任何藥水留如果是左圖:
你可以發佈代碼給你一個錯誤嗎? –
我會放一個魔藥部分的鏈接。爆炸部分不是我所擔心的。 [鏈接](https://www.dropbox.com/s/pecf9cyv2n45owt/testfile.py?dl=0) –
你也應該擔心爆炸部分,因爲它說藥劑[0] .pop()而不是藥劑。流行(0)。 –