summaryrefslogtreecommitdiff
path: root/pycameltris/controller.py
blob: 98785368cbaa55ff7353fce53a02a8e637e93bea (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
        START = 9
        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,
                Input.PAUSE: JoystickController.PS3Controller.START,
                }
        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,
                Input.PAUSE: pygame.K_RETURN,
                }
        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