python - 方向键的unicode?

标签 python python-2.7 unicode python-unicode

我正在尝试制作一款游戏,您可以立即将用户的输入传输到计算机,而不必每次都按enter。我知道该怎么做,但我似乎找不到箭头键的 unicode 编号。是否有unicode,或者我只是会被wasd困住?

class _GetchUnix:
    def __init__(self):
        import tty, sys
    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
class _GetchWindows:
    def __init__(self):
        import msvcrt
    def __call__(self):
        import msvcrt
        return msvcrt.getch()
class _Getch:
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()
    def __call__(self): return self.impl()
getch = Getch()

我使用getch.impl()作为试错输入,就像调用函数时按下一个键一样,它返回该键,然后继续。如果没有按下任何键,它就会继续前进。
我正在使用 Python 2.7.10

最佳答案

首先阅读 msvcrt 的相关文档。

msvcrt.kbhit()

Return true if a keypress is waiting to be read.

msvcrt.getch()

Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keypress is not already available, but will not wait for Enter to be pressed. If the pressed key was a special function key, this will return '\000' or '\xe0'; the next call will return the keycode. The Control-C keypress cannot be read with this function.

请注意,getch 会阻塞并需要两次调用特殊功能键,其中包括箭头键(它们最初返回 b'\xe0)。

然后使用 sys.platform 并编写两个版本的 get_arrow 函数。

import sys
if sys.platform == 'win32':
    import msvcrt as ms
    d = {b'H': 'up', b'K': 'lt', b'P': 'dn', b'M': 'rt'}
    def get_arrow():
        if ms.kbhit() and ms.getch() == b'\xe0':
            return d.get(ms.getch(), None)
        else:
            return None
else:  # unix
...

我通过以下代码实验确定了键到代码的映射。 (这在 IDLE 中运行时不起作用,并且可能在其他 GUI 框架中不起作用,因为 getch 与键盘的 GUI 处理冲突。)

>>> import msvcrt as ms
>>> for i in range(8): print(ms.getch())
...
b'\xe0'
b'H'
b'\xe0'
b'K'
b'\xe0'
b'P'
b'\xe0'
b'M'

我在 Windows 上测试了该功能

while True:
    dir = get_arrow()
    if dir: print(dir)

关于python - 方向键的unicode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39583798/

相关文章:

python 子进程模块在执行批处理文件时卡住

php - 我怎样才能知道标点字符在 UTF 8 中的形式?

java - 非法 unicode 转义序列值 :\n (0x6E)

python - 如何有效地将点云数据的大型 numpy 数组转换为下采样的二维数组?

python - 从类的交叉引用中省略模块名称

python - 如何用逗号分割包含一组字符串的列表?

python - ttk.Treeview - 无法更改行高

python - 没有部分的 Configparser 集

javascript - 国际日期 "String"正在减去而不是保留其原始格式

ios - UISearchController 无法识别元音变音、Swift、iOS