将随机选择答案转到if语句

时间:2013-09-28 09:34:29

标签: python python-3.x

我在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)]

但是知道当我运行程序时我会得到错误:

语法错误并突出显示消息

我只是添加了错误的代码或者它是什么东西

1 个答案:

答案 0 :(得分: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)])