-2

我正在 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
4

1 回答 1

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])
于 2013-09-28T11:38:01.587 回答