diff options
Diffstat (limited to 'pycameltris')
-rw-r--r-- | pycameltris/controller.py | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/pycameltris/controller.py b/pycameltris/controller.py new file mode 100644 index 0000000..3532fd9 --- /dev/null +++ b/pycameltris/controller.py @@ -0,0 +1,87 @@ +import enum + +import pygame + + +class Input(enum.Enum): + ROTATE_CLOCKWISE = 0 + ROTATE_COUNTER_CLOCKWISE = 1 + MOVE_LEFT = 2 + MOVE_RIGHT = 3 + MOVE_DOWN = 4 + PAUSE = 5 + QUIT = 6 + + +class JoystickController: + + class PS3Controller(enum.Enum): + CROSS = 0 + CIRCLE = 1 + TRIANGLE = 2 + SQUARE = 3 + DOWN = 14 + LEFT = 15 + RIGHT = 16 + + def __init__(self, joystick): + self.joystick = joystick + self.mapping = { + Input.ROTATE_CLOCKWISE: JoystickController.PS3Controller.CROSS, + Input.ROTATE_COUNTER_CLOCKWISE: JoystickController.PS3Controller.CIRCLE, + Input.MOVE_LEFT: JoystickController.PS3Controller.LEFT, + Input.MOVE_RIGHT: JoystickController.PS3Controller.RIGHT, + Input.MOVE_DOWN: JoystickController.PS3Controller.DOWN, + } + self.downevent = pygame.JOYBUTTONDOWN + self.upevent = pygame.JOYBUTTONUP + + def is_pressed(self, input_: Input): + return self.joystick.get_button(self.mapping[input_].value) + + + def get_input_down(self, event): + for key, value in self.mapping.items(): + if value.value == event.button: + return key + + return None + + def get_input_up(self, event): + for key, value in self.mapping.items(): + if value.value == event.button: + return key + + return None + + +class KeyboardController: + def __init__(self, keyboard): + self.keyboard = keyboard + self.mapping = { + Input.ROTATE_CLOCKWISE: pygame.K_f, + Input.ROTATE_COUNTER_CLOCKWISE: pygame.K_d, + Input.MOVE_LEFT: pygame.K_h, + Input.MOVE_RIGHT: pygame.K_l, + Input.MOVE_DOWN: pygame.K_j, + Input.QUIT: pygame.K_q, + } + self.downevent = pygame.KEYDOWN + self.upevent = pygame.KEYUP + + def is_pressed(self, input_: Input): + return self.keyboard.get_pressed()[self.mapping[input_]] + + def get_input_down(self, event): + for key, value in self.mapping.items(): + if value == event.key: + return key + + return None + + def get_input_up(self, event): + for key, value in self.mapping.items(): + if value == event.key: + return key + + return None |