如何创建一个使用 Python 检测按键的"run-loop"函数?



我是python3的新手,我一直在练习一些基本程序,但现在我被我写的一个小蛇类型的游戏卡住了。到目前为止,我编写的代码按顺序包括以下部分:

  1. 进口模块

  2. 类从用户那里获得密钥而不需要按下";输入";

  3. 由模块线程(名为move_alt()(调用的函数。

t = threading.Thread(target=move_alt) # this is immediately after the portion of code

如第3(点所述

4(move_forward()函数使用字符列表创建映射;位置字符";从地图的中心向右开始,直到它撞上一个";墙的特征";。此函数名为move_forward()

t.setDaemon(True)
t.start()
move_forward()

这个想法是启动一个线程与move_forward函数同时运行,该函数的目标是2(中描述的函数,从用户那里获取一个键,并根据按下的键对move_forward函数进行一些操作,例如(更具体地说(move_up或move_down等。

我不知道如何正确使用线程模块,所以我的代码没有按预期工作。相反,程序会在不同时运行move_forward函数的情况下运行线程,直到我不按键(这是在线程内完成的(,它才做任何事情。事实上,在刚开始运行程序时,它试图绘制地图(字符列表(,但只绘制了一些字符,然后就卡住了。

如果我的解释不有效,很抱歉,但英语不是我的第一语言,我往往写得太多了。

第页。S=我没有把上面的代码放在上面,因为它太长了,因为我做了一些评论和东西来学习(不要忘记(

经过深思熟虑,我终于能够使程序按预期工作。首先,线程模块不是最好的选择,但出于某种原因,我把线程(用于并发目的(与我试图做的事情混淆了。所以过了一段时间,我就不再使用这个想法了。我设法使它工作的方式实际上是使用另一个名为";键盘";(对于linux用户,由于某些原因,您必须将该模块用作root用户(。以下是使用该模块的一点代码:

def onkeypressw(event): this function is used as a condition in the "while loop" for the move_up condition
global stopw
if event.name == 's' or event.name == "a" or event.name == "d":
stopw = True
keyboard.on_press(onkeypressw)

def onkeypressw1(event): # this function is used as condition in the if sentence in the main function to call move_up() function
global runw1
if event.name == "w":
runw1 = True
else:
runw1 = False
keyboard.on_press(onkeypressw1)

然后在主函数中,我有一个while True循环在运行,其中我有一些if语句,它们运行四个可能的移动函数之一:move_up、move_down、move_left、move_right,这取决于我按下的键(w-s-d-a(。在这些";移动功能";有while循环来绘制地图并使用字符列表移动字符位置(比如说蛇头(,直到我按下另一个按钮。因此,例如,如果在主功能中;w";程序将运行move_ up函数并移动字符位置;墙字符";或者我按下";s、 d或a";。我为";而循环";是:1(一个用于墙字符,2(";不停止";所以它会绘制列表,直到我撞到墙上或stopw=True。我知道你可以使用其他模块编写这些代码,并用更少的工作获得相同的结果,但我想使用尽可能多的基本代码来更快地学习python3,因为我以前有使用C编程的经验。附言:这里有一个移动功能,以防有人好奇:

def move_up():
global c, f
global map1
global stopw
while f> 0 and not stopw:
map1[f, c] = " o " # f represents the rows and c the columns, I replaced the initial position character "_" for "o"
f = f - 1 # up one row
map1[f, c] = " _ " # I put the position character "_" at the new position
cls() # clear the screen
time.sleep(0.4) # add a little delay just to modify the snake speed
stopw = False # reset the boolean

最新更新