fox*_*eSs 0 python multithreading python-3.x
我正在制作一个蛇游戏,要求玩家按下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)
Run Code Online (Sandbox Code Playgroud)
那么为什么getch()它没有用thread1()呢?
问题是你在key里面创建一个局部变量thread1而不是覆盖现有的变量.快速简便的解决方案是宣布key全球内部thread1.
最后,你应该考虑使用锁.我不知道是否有必要,但我想如果你key在同时打印出来的同时尝试在线程中写入一个值,我可能会发生奇怪的事情.
工作代码:
import threading, time
from msvcrt import getch
key = "lol"
def thread1():
global key
lock = threading.Lock()
while True:
with lock:
key = getch()
threading.Thread(target = thread1).start()
while True:
time.sleep(1)
print(key)
Run Code Online (Sandbox Code Playgroud)