forked from junior-devleague/hookrace-blog-platformer
/
controller.py
63 lines (52 loc) · 1.53 KB
/
controller.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
61
62
63
from enum import Enum, IntEnum
from sdl2 import SDL_Keycode, SDL_KEYDOWN, SDL_KEYUP, SDL_QUIT, \
SDLK_SPACE, SDLK_a, SDLK_d, SDLK_q, SDLK_r
from sdl2.ext import get_events
class Input(Enum):
NONE = 1
LEFT = 2
RIGHT = 3
JUMP = 4
RESTART = 5
QUIT = 6
class Direction(IntEnum):
LEFT = -1
NONE = 0
RIGHT = 1
class Controller:
inputs = {
Input.NONE: False,
Input.LEFT: False,
Input.RIGHT: False,
Input.JUMP: False,
Input.RESTART: False,
Input.QUIT: False
}
def handle_input(self) -> None:
events = get_events()
for event in events:
if event.type == SDL_QUIT:
self.inputs[Input.QUIT] = True
elif event.type == SDL_KEYDOWN:
self.inputs[to_input(event.key.keysym.sym)] = True
elif event.type == SDL_KEYUP:
self.inputs[to_input(event.key.keysym.sym)] = False
@property
def direction(self) -> Direction:
return Direction((1 if self.inputs[Input.RIGHT] else 0)
- (1 if self.inputs[Input.LEFT] else 0))
def has_input(self, input_type: Input) -> bool:
return self.inputs[input_type]
def to_input(key: SDL_Keycode) -> Input:
if key == SDLK_a:
return Input.LEFT
elif key == SDLK_d:
return Input.RIGHT
elif key == SDLK_SPACE:
return Input.JUMP
elif key == SDLK_r:
return Input.RESTART
elif key == SDLK_q:
return Input.QUIT
else:
return Input.NONE