我正在制作一款蛇形游戏,要求玩家在不停止游戏过程的情况下按下WASD
键来获得玩家的输入。所以我不能在这种情况下使用input()
,因为那时游戏停止滴答作响以获得输入。如何使用线程获取python 3中的键盘输入?
我发现了一个getch()
函数,它可以在不按下输入的情况下立即给出输入,但是此函数也会停止游戏滴答以获取输入,如input()
。我决定使用线程模块在不同的线程中通过getch()
获得输入。问题是getch()在不同的线程中不工作,我不知道为什么。
import threading, time
from msvcrt import getch
key = "lol" #it never changes because getch() in thread1 is useless
def thread1():
while True:
key = getch() #this simply is almost ignored by interpreter, the only thing it
#gives is that delays print() unless you press any key
print("this is thread1()")
threading.Thread(target = thread1).start()
while True:
time.sleep(1)
print(key)
那么,为什么getch()
是无用的,当它是thread1()
?
你可能要考虑安装和使用pygame的,而不是使用线程。它具有让您轻松知道键盘上哪个键被按下的功能,所以您不必使用线程。 – Michael0x2a