输入和睡眠有问题。time()

2024-05-15 02:08:54 发布

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

我正在尝试做一个基于文本的小游戏,但是我遇到了一个while循环的问题。我已经试验了好几个小时了!如果你能帮助我,我将不胜感激。感谢您阅读:D

我基本上是想让用户在计时器用完之前按下一个按钮,如果他不及时,熊就会吃掉他

这是我的密码:

import time
cash = 0
def dead():
    print("You are dead!")
    main()
    points = 0
def adventure_1(inventory, cash):
    points = 0
    time1 = 2
    if time1 < 3:
        time.sleep(1)
        time1 -= 1
        bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")



        #Ran out of time death
        if time1 == 0:
            dead()

        #Climb away from bear
        elif bear == 'c' or 'C':
            print("Your safe from the bear")
            points += 1
            print("You recieved +2 points")#Recieve points
            print("You now have : ",points,"points")
            adventure_2()#continue to adventure 2


        #Invalid input death
        elif bear != 's' or 'S':
            dead()


def adventure_2(inventory, cash):
    points = 2
    time = 5

Tags: toyouinputiftimedefcashpoints
2条回答
t_0 = time.time()
bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")
if abs(t_0 - time.time()) > time_threshold:
    #player has died

在python中,input语句使程序流等待,直到播放器输入一个值

if time1 < 3:
        time.sleep(1)
        time1 -= 1
        #line below causes the error
        bear = input("A bear is near... Hide Quickly! Enter: (C) to CLIMB a Tree")

为了克服这一点,你可以使用一些类似于下面的代码,这是一个工作的例子。我们可以通过使用计时器来查看玩家是否输入了任何内容,如果他没有输入任何内容,我们可以捕获异常并继续程序流

from threading import Timer

def input_with_timeout(x):    
    t = Timer(x,time_up) # x is amount of time in seconds
    t.start()
    try:
        answer = input("enter answer : ")
    except Exception:
        print 'pass\n'
        answer = None

    if answer != True:  
        t.cancel()       

def time_up():
    print 'time up...'

input_with_timeout(5) 

因此,正如您所见,我们可以通过使用计时器来计算播放机花费的时间,然后继续捕获未发送输入的异常,最后继续执行我们的程序,从而解决等待播放机输入值的问题

相关问题 更多 >

    热门问题