如何设置输入超时

myk*_*456 6 python python-3.x

如果您等待 4 秒钟,它会显示“您的时间用完了”,这很好。但是,为了保持循环继续,您必须按enter键才能继续。

我希望当它在下面打印“你用完了时间”而不是仅仅打字时,它会显示一个输入语句,比如“输入‘攻击’继续前进”,并且循环将从原来的位置继续。

from threading import Timer
import time

monsterhp = int(800)
y = 150
while monsterhp > 0:
    timeout = 4
    t = Timer(timeout, print, ['You ran out of time.'])
    t.start()
    print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = input(prompt)
    t.cancel()

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)
Run Code Online (Sandbox Code Playgroud)

abc*_*ccd 3

完成您提出的任务并不像您想象的那么容易。使用该signal模块来执行此操作更容易:(我已将您的代码与我链接的答案的修改版本合并在一起)

import signal, time

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

monsterhp = int(800)
y = 150
while monsterhp > 0:
    timeout = 4
    timeoutmsg = 'You ran out of time.'
    print(" ")
    prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
    answer = TimedInput(prompt, timeout, timeoutmsg)

    if answer == "attack":
        print("You strike the monster")
        time.sleep(1)
        monsterhp = monsterhp - y
        print("War Lord Health:", monsterhp)
Run Code Online (Sandbox Code Playgroud)

注意:这仅适用于所有 unix/mac 系统

您可以将 while 循环更改为此,以获得代码的改进版本:)

while monsterhp > 0:
        timeout = 4
        timeoutmsg = 'You ran out of time.'
        print(" ")
        prompt = "You have %d seconds Type 'attack' to hit the monster\nType here: " % timeout
        answer = TimedInput(prompt, timeout, timeoutmsg)

        if answer == "attack":
            print("You strike the monster")
            time.sleep(1)
            monsterhp = monsterhp - y
            print("War Lord Health:", monsterhp)
        elif answer == None:
            print("The War Lord has killed you, you're now dead")
            print("Thanks for playing, \nGAME OVER")
            break
Run Code Online (Sandbox Code Playgroud)