在实现上一个版本的Drawing Machine的时候,最头疼的问题就是键盘输入完要按个回车。于是调研如何处理键盘事件,发现在Python还真不是个简单的事情。Stackoverflow里面给出了一个比较全面的方案分析:http://stackoverflow.com/questions/13207678/whats-the-simplest-way-of-detecting-keyboard-input-in-python-from-the-terminal,不过每个方案看起来都挺繁琐,而且还需要操作系统的支持。那篇问答最后提出了基于pninput的实现看起来比较简洁,但可惜的repl.it并不支持。。。鉴于repl.it也不支持pygame,后面Ghost Game的实现也要切换到本地环境运行了。


from pynput import keyboard
 
def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False# Collect events until released

with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()