random.choice只选择一个选项

时间:2017-05-22 04:28:46

标签: python python-3.x

因此,每次循环时,它只会选择attackword中的一个选项。我想在每次循环时随机选择一个。

注意:超时需要与%d保持一致。

    from threading import Timer
    import time
    import random
    import signal

    attackword = ['strike', 'damage']
    attackwords = random.choice(attackword)

    monsterhp = int(800)
    y = 150
    while monsterhp > 0:
        def TimedInput(prompt='', timeout=20, timeoutmsg=None):
            def timeout_error(*_):

                raise TimeoutError

            signal.signal(signal.SIGALRM, timeout_error)
            signal.alarm(timeout)
            try:
                answer = input(prompt)
                signal.alarm(0)
                return answer
            except TimeoutError:
                if timeoutmsg:
                    print(timeoutmsg)
                signal.signal(signal.SIGALRM, signal.SIG_IGN)
                return None
        timeout = 4
        timeoutmsg = 'You ran out of time.'
        print(" ")
        prompt = "You have %d seconds Type %s to hit the monster\nType here: " % (timeout, attackwords)
        answer = TimedInput(prompt, timeout, timeoutmsg)

            if answer == attackwords:
                print("You strike the monster")
                time.sleep(1)
                monsterhp = monsterhp - y
                print("War Lord Health:", monsterhp)
            elif answer != attackwords and answer != None:
                print("Incorrect answer. No damage dealt.")

1 个答案:

答案 0 :(得分:2)

<强>更新

如果您需要稍后提供该单词的副本,您可以在循环内指定attackwords

attackwords = random.choice(attackword)行之前添加prompt,并将prompt的参数保留为% (timeout, attackwords)

其余代码(elif ...等)应按预期工作,无需修改。

目前,您要将attackwords分配给random.choice()返回的一个特定值。

要获得您想要的行为,只需运行random.choice()您想要显示该字词的位置。

prompt = "You have %d seconds Type %s to hit the monster\nType here: " % (timeout, random.choice(attackword))