2016-09-20 88 views
1

我正在嘗試製作遊戲,您可以立即將用戶的輸入傳輸到計算機,而不必每次都按enter。我知道如何做到這一點,但我似乎無法找到箭頭鍵的unicode編號。有沒有unicode,或者我只是會卡住wasd?用於箭頭鍵的unicode?

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

+3

測試的功能在Windows如果您試圖處理鍵盤事件或關鍵狀態,你想要的不是Unicode。鍵盤不能這樣工作。查看文檔,瞭解它用於處理鍵盤輸入的內容。如果您使用的是按字符而不是鍵盤鍵工作的內容,則需要使用其他內容。 – user2357112

+2

「*我知道該怎麼做*」 - 你能告訴我們你是怎麼做到的嗎?一旦我們知道你到目前爲止做了什麼,我們可以描述如何處理方向鍵。 –

+0

您可以使用分別與向左,向上,向右和向下箭頭(←,↑,↓,→)對應的代碼點U + 2190至U + 2193的Unicode箭頭符號。然而你使用'msvcrt'的代碼是不正確的。詳情請參閱@Terry Jan Reedy的回答。 – martineau

回答

1

首先閱讀msvcrt的相關文檔。

msvcrt.kbhit()

返回true,如果一個按鍵正等待被讀取。

msvcrt.getch()

閱讀按鍵和返回結果字符作爲一個字節串。沒有任何東西被迴應到控制檯。如果按鍵不可用,此呼叫將被阻止,但不會等待按下Enter鍵。如果按下的鍵是特殊功能鍵,則返回'\ 000'或'\ xe0';下一次調用將返回鍵碼。使用此功能無法讀取Control-C按鍵。

請注意,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 
... 

我用下面的代碼通過實驗確定了密鑰到代碼的映射。 (在怠速運轉,並在其他GUI框架也許不是時,這將無法正常工作,與鍵盤的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' 

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

問題中沒有任何內容表明OP正在使用Windows。你知道一些沒有說明的東西嗎? – wallyk

+0

@wallyk:OP使用'msvcrt'模塊的代碼至少表示他們希望代碼在Windows上運行。所以,不,沒有明確說明。 – martineau

+0

特里:好點,但我想回答OP的問題,您需要將'getch()'值映射到箭頭字符的匹配Unicode值 - 以及在Unix模式下執行相同結果的操作。 – martineau