-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkeybindings.py
More file actions
72 lines (58 loc) · 2.31 KB
/
keybindings.py
File metadata and controls
72 lines (58 loc) · 2.31 KB
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
from typing import TYPE_CHECKING
import pygame
from pygame import Surface
if TYPE_CHECKING:
from entities.input.manager import GameAction
# This class was made so we can change/add easily new controls, without hardcoding keys in the game logic
class KeyBindings:
_instance: "KeyBindings | None" = None
def __new__(cls) -> "KeyBindings":
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._instance._init()
return cls._instance
def _init(self) -> None:
self.jump: int = pygame.K_UP
self.slide: int = pygame.K_DOWN
self.shoot: int = pygame.K_x
self.restart: int = pygame.K_r
self._defaults: dict[str, int] = {"jump": pygame.K_UP, "slide": pygame.K_DOWN, "shoot": pygame.K_x, "restart": pygame.K_r}
def reset(self) -> None:
self.jump = self._defaults["jump"]
self.slide = self._defaults["slide"]
self.shoot = self._defaults["shoot"]
self.restart = self._defaults["restart"]
def getKeyName(self, key: int) -> str:
return pygame.key.name(key).upper()
def getKeyIcon(self, key: int, size: int = 32) -> Surface | None:
from keyicons import getKeyIcon
return getKeyIcon(key, size)
def getActionForKey(self, key: int) -> "GameAction | None":
from entities.input.manager import GameAction
# TODO: Clean this conditional branching
if key == self.jump:
return GameAction.JUMP
elif key == self.slide:
return GameAction.SLIDE
elif key == self.shoot:
return GameAction.SHOOT
elif key in (pygame.K_SPACE, pygame.K_z, pygame.K_w):
return GameAction.JUMP
elif key == pygame.K_s:
return GameAction.SLIDE
elif key == self.restart:
return GameAction.RESTART
elif key == pygame.K_ESCAPE:
return GameAction.PAUSE
elif key == pygame.K_RETURN:
return GameAction.MENU_CONFIRM
elif key == pygame.K_UP:
return GameAction.MENU_UP
elif key == pygame.K_DOWN:
return GameAction.MENU_DOWN
elif key == pygame.K_LEFT:
return GameAction.MENU_LEFT
elif key == pygame.K_RIGHT:
return GameAction.MENU_RIGHT
return None
keyBindings = KeyBindings()