【发布时间】:2012-03-27 03:25:10
【问题描述】:
有谁知道如何捕捉游戏的击键(即使用键盘导航一个简单的基于 ascii 的游戏,其中 8 = 上,2 = 下,4 左等......并且不需要按回车,进入一次击键就是目标。)?我找到了这段代码,这看起来是个好主意,但我想不通。添加 cmets,或将我发送到有关该主题的文章等,将有很大帮助。我知道很多人都有这个问题。先谢谢了?
try:
from msvcrt import kbhit
except ImportError:
import termios, fcntl, sys, os
def kbhit():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
while True:
try:
c = sys.stdin.read(1)
return True
except IOError:
return False
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
【问题讨论】:
-
你可以使用一个游戏库,比如pygame,它支持按键作为事件。
-
如果无法从
msvcrt包中导入,这个sn-p 所做的只是定义一个kbhit()方法。 -
学习pygame有多复杂?我对编程很陌生。我希望能够相对较快地实现一些东西。
-
检查 gamedev 堆栈溢出:gamedev.stackexchange.com