我使用终端和pythons curses模块制作了游戏。我使用kbinput函数操纵蛇。这适用于数字键盘和标准字母,但是,当我尝试使用方向键时,它会抛出异常_cureses_error: no input
如果我按住键,最终其中一个命令将最终通过。我有完全阻塞模式,所以获得无输入异常是没有意义的。
我尝试了一个快速测试,看看它是否在一个线程中运行是一个问题,但在我的测试用例中,方向键工作正常。
相关功能如下:
def game():
screen=curses.initscr()
curses.start_color()
curses.raw()
curses.cbreak()
curses.noecho()
screen.keypad(True)
try:
gtime=time.time()
b=Board(screen)
s=Snake(b)
#thread.start_new_thread(steps,(s,b))
thread.start_new_thread(kbinput,(s,b,screen))
....
def kbinput(snake,b,screen):
while snake.alive==True:
key=""
key=screen.getkey()
b.key=key
if key=="q":
snake.alive=False
break
elif (key == "8" or key == "i" or key == 'KEY_UP') and snake.direction != 3: snake.direction=1
elif (key == "6" or key == "l" or key == 'KEY_RIGHT') and snake.direction != 4: snake.direction=2
elif (key == "4" or key == "j" or key == 'KEY_LEFT') and snake.direction != 2: snake.direction=4
elif (key == "5" or key == "k" or key == 'KEY_DOWN') and snake.direction != 1: snake.direction=3
return
编辑: 托马斯是正确的,问题似乎是线程化kbinput。为了解决这个问题,我对这些函数进行了这些更改:
def game():
screen=curses.initscr()
curses.start_color()
curses.raw()
curses.cbreak()
curses.noecho()
screen.keypad(True)
curses.halfdelay(1)
curses.init_pair(1,curses.COLOR_RED,curses.COLOR_BLACK)
curses.init_pair(2,curses.COLOR_GREEN,curses.COLOR_BLACK)
try:
gtime=time.time()
b=Board(screen)
s=Snake(b)
#thread.start_new_thread(kbinput,(s,b,screen))
while s.alive and s.x != 0 and s.x != b.width-1 and s.y !=1 and s.y != b.height-2:
kbinput(s,b,screen)
gtime=time.time()
update(s,b,screen)
if snake_check(s) == True: break
def kbinput(snake,b,screen):
#while snake.alive==True:
key=""
key2=screen.getch()
if key2==-1: return
try:key=chr(key2)
except:pass
if key=="q":
snake.alive=False
#break
elif (key == "8" or key == "i" or key2 == curses.KEY_UP) and snake.direction != 3: snake.direction=1
elif (key == "6" or key == "l" or key2 == curses.KEY_RIGHT) and snake.direction != 4: snake.direction=2
elif (key == "4" or key == "j" or key2 == curses.KEY_LEFT) and snake.direction != 2: snake.direction=4
elif (key == "5" or key == "k" or key2 == curses.KEY_DOWN) and snake.direction != 1: snake.direction=3
return
答案 0 :(得分:1)
而不是寻找字符串文字
key == 'KEY_UP')
寻找定义常数
key == curses.KEY_UP)
虽然如评论中所述,但这需要getch
方法。
然而,这一行表明一个更严重的问题:
thread.start_new_thread(kbinput,(s,b,screen))
一般来说,Curses不是线程安全的(并且python的curses绑定受此限制):