Skip to main content
 首页 » 编程设计

PYTHON:如果几秒钟过去了,如何让程序停止

2024年11月01日7webabcd

所以我正在制作一个小速度游戏。函数将生成一个随机字母,之后,我希望程序等待几秒钟。如果什么都不按,你会输,你的记录会被显示 如果你按右键,另一个随机字母将被显示。我使用了时间函数并模拟了一个持续时间在范围 (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 中运行。

请您参考如下方法:

msvcrt.getch() 是阻塞的,所以您实际上并没有测量用户按下按键所花费的时间。 for 循环在用户已经按下它之后开始。 另外,time.sleep() 是阻塞的,因此即使用户已经按下了键,也必须等待 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!")