2013-09-28 89 views
1

我在python 3.3.2中創建基於文本的遊戲,我想顯示一個消息,取決於發生什麼後發生或未命中或命中(隨機選擇),你會得到取決於發生什麼的不同消息。這是到目前爲止的代碼隨機選擇答案,如果陳述

print ("A huge spider as large as your fist crawls up your arm. Do you attack it? Y/N") 
attack_spider = input() 
#North/hand in hole/keep it in/attack 
if attack_spider == "Y": 
    attack = ['Miss', 'Miss', 'Miss', 'Miss', 'Hit'] 
    from random import choice 
    print (choice(attack)) 

我認爲它看起來像這樣:

if attack == 'Miss': 
    print ("You made the spider angry") 

但這並沒有看到工作。是否有可能做到這一點?

我添加的代碼在下面像這樣的答案:

   if attack_spider == "Y": 
        attack = ['Miss', 'Miss', 'Miss', 'Miss', 'Hit'] 
        from random import choice 
        print (choice(attack)) 
        messages = { 
        "Miss": "You made the spider angry!", 
        "Hit": "You killed the spider!" 
        } 
        print messages[choice(attack)] 

但要知道,當我運行程序出現錯誤,像這樣:

語法錯誤,並強調信息

做我只是添加了錯誤的代碼或者它有些東西可以選擇

回答

3

你可以這樣做:

result = random.choice(attack) 

if result == "Miss": 
    print("You made the spider angry!") 
elif result == "Hit": 
    print("You killed the spider!") 

注意(正如Matthias提到的),在此存儲result是很重要的。如果你做的事:如預期

if choice(attack) == "Miss": # Random runs once 
    ... 
if choice(attack) == "Hit": # Random runs a second time, possibly with different results 
    ... 

事情是行不通的,因爲你可以有第二個"Hit"第一隨機和"Miss"


但更好的是,使用字典:

messages = { 
    "Miss": "You made the spider angry!", 
    "Hit": "You killed the spider!" 
} 

print(messages[choice(attack)]) 
+0

刪除我的答案。你是第一個,甚至提供了一個更好的方式來做到這一點。 – Matthias

+0

@Matthias乾杯,我添加了一個由你的答案啓發的說明,解釋爲什麼存儲結果很重要。 –

+0

@ThomasOrozco我添加了你的代碼,你可以知道在問題中看到你知道如何修復錯誤 – dashernasher