random.choice只选择一个选项

2024-09-30 10:32:51 发布

您现在位置:Python中文网/ 问答频道 /正文

所以每次循环时,它只会在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.")

Tags: answerimportnoneyousignaltimetimeoutrandom
1条回答
网友
1楼 · 发布于 2024-09-30 10:32:51

更新:

当您需要一个单词的副本以后才可用时,您可以在循环中分配attackwords

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

剩下的代码(elif。。etc)应按预期工作,无需任何修改


目前,您正在将attackwords赋值给random.choice()返回的一个特定值

要获得您想要的行为,只需运行random.choice()您真正想要的单词出现的地方

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

相关问题 更多 >

    热门问题