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

2024-09-30 14:34:33 发布

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

所以我在做一个速度游戏。一个函数将生成一个随机字母,在那之后,我希望程序等待几秒钟。如果不按任何键,您将丢失并显示您的记录如果按右键,将显示另一个随机字母。我使用了时间函数,模拟了一个持续范围为(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中工作。你知道吗


Tags: tokey函数importyoustringifis
2条回答

时间戳解决方案:

from time import time, sleep

start = time()  # start time measuring by creating timestamp


def time_passed(start, duration):
    """tests if an amount of time has passed
    Args:
        start(float): timestamp of time()
        duration(int): seconds that need to pass
    Returns:
        bool: are 'duration' seconds over since 'start'
    """
    return start + duration <= time()


# Use as condition for while
while not time_passed(start, 5):
    sleep(1)

# ... or if statements or <younameit>
if time_passed(start, 5):
    print("Do something if 5 seconds are over")

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!")

相关问题 更多 >