有时间限制的数学测验(同步函数)高级python

2024-03-28 11:10:17 发布

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

所以我想运行两个程序,一个计时器和一个数学问题。但输入似乎总是停止计时器功能,甚至根本不运行。有什么办法让它绕过这个问题吗? 我将保持示例简单。在

import time

start_time = time.time()
timer=0
correct = answer
answer = input("9 + 9 = ") 
#technically a math question here
#so here until i enter the input prevents computer reading the code
while True:
    timer = time.time() - start_time
    if timer > 3:
#3 seconds is the limit
    print('Wrong!')
quit()

所以我想让玩家在不到3秒的时间内回答问题。在

3秒后游戏将打印错误并退出

如果玩家在三秒钟内回答,计时器将被“终止”或在触发“错误”并退出之前停止

希望你能理解,并真心感谢你的帮助


Tags: theanswerimport程序功能示例inputhere
1条回答
网友
1楼 · 发布于 2024-03-28 11:10:17

在Windows上,您可以使用msvcrt模块的kbhit和{}函数(我稍微更新了一下code example):

import sys
import time
import msvcrt


def read_input(caption, timeout=5):
    start_time = time.time()
    print(caption)
    inpt = ''
    while True:
        if msvcrt.kbhit():  # Check if a key press is waiting.
            # Check which key was pressed and turn it into a unicode string.
            char = msvcrt.getche().decode(encoding='utf-8')
            # If enter was pressed, return the inpt.
            if char in ('\n', '\r'): # enter key
                return inpt
            # If another key was pressed, concatenate with previous chars.
            elif char >= ' ': # Keys greater or equal to space key.
                inpt += char
        # If time is up, return the inpt.
        if time.time()-start_time > timeout:
            print('\nTime is up.')
            return inpt

# and some examples of usage
ans = read_input('Please type a name', timeout=4)
print('The name is {}'.format(ans))
ans = read_input('Please enter a number', timeout=3)
print('The number is {}'.format(ans))

我不确定您在其他操作系统上到底要做什么(researchtermios,tty,select)。在

另一种可能是curses模块,它也有一个getch函数,您可以将它设置为nodelay(1)(非阻塞),但是对于Windows,您必须首先从Christopher Gohlke's website下载诅咒。在

^{pr2}$

相关问题 更多 >