【发布时间】:2012-12-26 16:41:38
【问题描述】:
我正在制作一个蛇游戏,它要求玩家在不停止游戏进程的情况下按下WASD 键来获取玩家的输入。所以我不能在这种情况下使用input(),因为这样游戏就会停止计时以获取输入。
我发现了一个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 而不是使用线程。它的功能可以让您轻松知道正在按下键盘上的哪个键,因此您不必纠结于线程。
-
为什么在这个例子中仍然使用线程?没必要。使用正常的运行循环。
标签: python multithreading python-3.x