Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PYTHON:如果过了几秒钟,如何使程序停止?_Python_Time - Fatal编程技术网

PYTHON:如果过了几秒钟,如何使程序停止?

PYTHON:如果过了几秒钟,如何使程序停止?,python,time,Python,Time,所以我在做一个速度游戏。一个函数将生成一个随机字母,在这之后,我希望程序等待几秒钟。如果未按任何键,您将丢失记录并显示您的记录。如果按右键,将显示另一个随机字母。我使用了时间函数,模拟了一个持续时间在(0,2)范围内的克朗计。这就是我目前所拥有的。它能工作,问题是,它显示第一个字母,如果你按错了,你会输(好),但即使你按对了,克朗计显然会继续运行,所以它变为2,你会输。我希望它停止和重置后,我击中了关键,但我不知道该如何做。我是编程新手,如果你没有得到什么,我很抱歉 import string

所以我在做一个速度游戏。一个函数将生成一个随机字母,在这之后,我希望程序等待几秒钟。如果未按任何键,您将丢失记录并显示您的记录。如果按右键,将显示另一个随机字母。我使用了时间函数,模拟了一个持续时间在(0,2)范围内的克朗计。这就是我目前所拥有的。它能工作,问题是,它显示第一个字母,如果你按错了,你会输(好),但即使你按对了,克朗计显然会继续运行,所以它变为2,你会输。我希望它停止和重置后,我击中了关键,但我不知道该如何做。我是编程新手,如果你没有得到什么,我很抱歉

import string
import random
import msvcrt
import time

def generarletra():
    string.ascii_lowercase
    letra = random.choice(string.ascii_lowercase)
    return letra

def getchar():
    s = ''
    return msvcrt.getch().decode('utf-8')

print("\nWelcome to Key Pop It!")
opcion = int(input("\n  Press 1 to play OR\n  Press 2 for instructions"))

if(opcion == 1):
    acum=0
    while True:
        letra2 = generarletra()
        print(letra2)
        key = getchar()
        for s in range (0,2):
            print("Segundos ", s)
            time.sleep(2)
        acum = acum + 1
        if((key is not letra2) or (s == 2)):
            print("su record fue de, ", acum)
            break

elif(opcion == 2):
    print("\n\nWelcome to key pop it!\nThe game is simple, the machine is going to generate a 
random\nletter and you have to press it on your keyboard, if you take too\nlong or press the wrong 
letter, you will lose.")
else:
    print("Invalid option!")
PD:您需要在IDE中使用控制台模拟或直接从控制台运行它。由于某些原因,msvcrt库无法在IDE中工作。

时间戳解决方案:

从时间导入时间,睡眠
开始=时间()#通过创建时间戳开始测量时间
def时间(开始、持续时间):
“”“测试是否已过一段时间
Args:
开始(浮动):时间的时间戳()
持续时间(int):需要经过的秒数
返回:
布尔:“开始”后的“持续时间”秒数是否已过
"""
return start+duration
msvcrt.getch()
正在阻塞,因此您无法实际测量用户按键所用的时间。for循环在用户按下后开始。 另外,
time.sleep()
正在阻塞,因此即使用户已经按下了该键,也必须等待睡眠时间

要解决第一个问题,您可以使用
msvcrt.kbhit()
检查用户是否按了某个键,并仅在用户按了某个键时调用
msvcrt.getch()
。这样
msvcrt.getch()
将在调用它后立即返回

要解决第二个问题,只需使用
time.time()
获取循环的开始时间,并将其与循环中的当前时间进行比较。您还可以打印循环中经过的时间

以下是最终代码(还有一些额外的命名和格式更改):

从这里开始也许:
import string
import random
import msvcrt
import time

MAX_TIME = 2

def get_random_char():
    return random.choice(string.ascii_lowercase)

def get_user_char():
    return msvcrt.getch().decode('utf-8')

print("\nWelcome to Key Pop It!")
option = input("\n  Press 1 to play OR\n  Press 2 for instructions\n")

if option == "1":
    score=0
    while True:
        char = get_random_char()            
        print("\n" + char)
        start_time = time.time()
        while not msvcrt.kbhit():
            seconds_passed = time.time() - start_time
            print("seconds passed: {0:.1f}".format(seconds_passed), end="\r")
            if seconds_passed >= MAX_TIME:
                key = None
                break
        else:
            key = get_user_char()
        if key != char:
            break
        score = score + 1
    print("\nsu record fue de, ", score)

elif option == "2":
    print("""
    Welcome to key pop it!
    The game is simple, the machine is going to generate a random
    letter and you have to press it on your keyboard, if you take too
    long or press the wrong letter, you will lose.""")
else:
    print("Invalid option!")