所以我在做一个速度游戏。一个函数将生成一个随机字母,在那之后,我希望程序等待几秒钟。如果不按任何键,您将丢失并显示您的记录如果按右键,将显示另一个随机字母。我使用了时间函数,模拟了一个持续范围为(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()
是阻塞的,因此用户将不得不等待睡眠时间,即使他已经按下了键。你知道吗要解决第一个问题,您可以使用
msvcrt.kbhit()
检查用户是否按了某个键,并且仅当用户按了某个键时才调用msvcrt.getch()
。这样msvcrt.getch()
将在您调用它之后立即返回。你知道吗要解决第二个问题,只需使用
time.time()
获取循环的开始时间,并将其与循环中的当前时间进行比较。您还可以打印循环中经过的时间。你知道吗以下是最终代码(还有一些额外的命名和格式更改):
相关问题 更多 >
编程相关推荐