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

但知道当我运行程序时,我会收到如下错误:

语法错误并突出显示消息

我只是添加了错误的代码还是其他的东西

4

1 回答 1

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)])
于 2013-09-28T09:36:27.000 回答