-
Notifications
You must be signed in to change notification settings - Fork 13
/
keypress.py
62 lines (50 loc) · 1.85 KB
/
keypress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Key press acquisition and interpretation.
This module is closely bound to the view
component. If a different view component is used,
a corresponding keypress module must be used
with it. For example, we could have a pure textual
"glass tty" interface using curses, and in that case
we would need to use curses functions to obtain keystrokes.
"""
import sys
import graphics
# Internal codes for commands.
LEFT = "Left"
RIGHT = "Right"
UP = "Up"
DOWN = "Down"
UNMAPPED = "Unmapped"
CLOSE = "Close" # When the window is closed
# We can bind different areas of the keyboard to the
# commands. "Left", "right", etc are Tk codes for the
# arrow keys. "jil," are a similar spatial pattern under
# the right hand.
KEY_BINDINGS = { # Arrow keys, as interpreted by Tk and graphics.py
"Left": LEFT, "Right": RIGHT, "Up": UP, "Down": DOWN,
# left-hand --- some people use this pattern?
"a": LEFT, "w": UP, "s": RIGHT, "z": DOWN,
# VI / Vim editor movement
"h": LEFT, "j": DOWN, "k": UP, "l": RIGHT,
# Numeric keypad (one common mapping)
"4": LEFT, "6": RIGHT, "8": UP, "2": DOWN
}
class Command(object):
"""Interpret keyboard input as commands from the
set LEFT, RIGHT, UP, DOWN, and UNMAPPED for a
key that does not have a binding.
"""
def __init__(self, game_view):
self.game_view = game_view
def next(self):
try:
key = self.game_view.get_key()
if key not in KEY_BINDINGS:
return UNMAPPED
else:
return KEY_BINDINGS[key]
except graphics.graphics.GraphicsError as e:
# This happens when the close button is pressed.
if self.game_view.win.isClosed():
return CLOSE
raise e