在python上随机选择之后的两个问题

时间:2013-09-28 11:30:05

标签: python python-3.x

我在python 3.3.2上制作一个基于文本的游戏,并希望在随机选择之后必须有两个问题这是我的代码:

if attack_spider == "Y":
    attack = ['Miss', 'Miss', 'Miss', 'Miss', 'Hit']
    from random import choice
    print(choice(attack))
    messages = {
        "Miss": "You made the spider angry! The spider bites you do you attack it again? Y/N",
        "Hit": "You killed the spider! It's fangs glow red do you pick them up? Y/N!"
    }

    print(messages[choice(attack)])

我希望能够根据你遇到或错过的天气有不同的问题,如果我只是说:

spider = input()
if spider == "Y":
    print("as you pick the fangs up the begin to drip red blood") 
即使你错过了这与蜘蛛生气无关,也应该这样。 它有一种方法可以得到不同的答案,取决于你是否命中。

我在下面的答案中添加了代码。

               if attack_spider == "Y":
                   attack = choice(attack)
                   attack = ['Miss', 'Miss', 'Miss', 'Miss', 'Hit']
                   from random import choice
                   print (choice(attack))
                   messages = {
                       "Miss": "You made the spider angry! The spider bites you do you attack it again? Y/N",
                       "Hit": "You killed the spider! It's fangs glow red do you pick them up? Y/N!"
                   }

                   print(messages[choice(attack)])
                   spider = input()
                   if spider == "Y":
                       if attack == "Hit":
                           print("As you pick the fangs up the begin to drip red blood")

                       if attack == "Miss":
                           print("As you go to hit it it runs away very quickly")

                   if spider == "N":
                       if attack == "Hit":
                           print("As you walk forward and turn right something flies past you")

                       if attack == "Miss":
                           print("The spider begins to bite harder and you beging to See stars")

我知道得到这个错误:

    Traceback (most recent call last):
      File "C:\Users\callum\Documents\programming\maze runner.py", line 29, in <module>
        attack = choice(attack)
    NameError: name 'choice' is not defined

1 个答案:

答案 0 :(得分:1)

您的print(choice(attack))需要先分配给变量:

hit_or_miss = random.choice(attack)
print(hit_or_miss)

然后你可以做

if spider == "Y":
    if hit_or_miss == "Hit":
        print(...)

    if hit_or_miss == "Miss":
        print(...)

if spider == "N":
    if hit_or_miss == "Hit":
        print(...)

    if hit_or_miss == "Miss":
        print(...)

由于您已经知道词典,因此也可以这样做:

responses = {
    ("Y", "Hit"):  ...,
    ("Y", "Miss"): ...,
    ("N", "Hit"):  ...,
    ("N", "Miss"): ...
}

print(responses[spider, hit_or_miss])