2013-09-28 134 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