-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinput_manager.py
More file actions
367 lines (298 loc) · 14.2 KB
/
input_manager.py
File metadata and controls
367 lines (298 loc) · 14.2 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import pygame
import time
from pygame.locals import JOYDEVICEADDED, JOYDEVICEREMOVED, JOYBUTTONUP, JOYBUTTONDOWN, JOYAXISMOTION
import settings
class PlayerInput:
""" Entrées pour un joueur. """
def __init__(self) -> None:
# mouvement sur l'axe horizontal (x) et sur l'axe vertical (y)
self.__movement = (0.0, 0.0)
self.__focus_next_button = False
self.__focus_prev_button = False
self.__solve_button = False
self.__show_name = False
self.__pause = False
# sert à détecter de l'activité
self.__last_activity_time = time.time() - settings.INACTIVITY_THRESHOLD
def touch(self) -> None:
""" Touche les entrées du joueur pour indiquer qu'il y a de l'activité. """
self.__last_activity_time = time.time()
@property
def last_activity_time(self) -> float:
return self.__last_activity_time
@property
def movement(self) -> tuple:
return self.__movement
@movement.setter
def movement(self, new_movement: tuple) -> None:
self.__movement = new_movement
self.touch()
@property
def focus_next_button(self) -> bool:
return self.__focus_next_button
@focus_next_button.setter
def focus_next_button(self, value: bool) -> None:
self.__focus_next_button = value
self.touch()
@property
def focus_prev_button(self) -> bool:
return self.__focus_prev_button
@focus_prev_button.setter
def focus_prev_button(self, value: bool) -> None:
self.__focus_prev_button = value
self.touch()
@property
def solve_button(self) -> bool:
return self.__solve_button
@solve_button.setter
def solve_button(self, value: bool) -> None:
self.__solve_button = value
self.touch()
@property
def show_name(self) -> bool:
return self.__show_name
@show_name.setter
def show_name(self, value: bool) -> None:
self.__show_name = value
self.touch()
@property
def pause(self) -> bool:
return self.__pause
@pause.setter
def pause(self, value: bool) -> None:
self.__pause = value
self.touch()
class __InputManager:
""" Gestionnaire d'entrée (clavier ou gamepads). """
__INPUT_KEYBOARD_PLAYER_ONE = {'up': pygame.K_w, 'down': pygame.K_s, 'right': pygame.K_d, 'left': pygame.K_a,
'switch_plus': pygame.K_2, 'switch_minus': pygame.K_1, 'action': pygame.K_f, 'show_name': pygame.K_n, 'pause': pygame.K_SPACE}
__INPUT_KEYBOARD_PLAYER_TWO = {'up': pygame.K_UP, 'down': pygame.K_DOWN, 'right': pygame.K_RIGHT, 'left': pygame.K_LEFT,
'switch_plus': pygame.K_0, 'switch_minus': pygame.K_9, 'action': pygame.K_p, 'show_name': pygame.K_NUMLOCK, 'pause': pygame.K_RCTRL}
__PLAYER_ONE = 0
__PLAYER_TWO = 1
__DEAD_ZONE = 0.05
__INVALID_INSTANCE_ID = -99 # identifiant (invalide) de contrôleur de jeu
def __init__(self) -> None:
"""Initialise le gestionnaire d'entrée (clavier ou gamepads)."""
self.__player_inputs = [PlayerInput(), PlayerInput()]
self.__joysticks = None
self.__player_one_instance_id = self.__INVALID_INSTANCE_ID
self.__player_two_instance_id = self.__INVALID_INSTANCE_ID
self.__assign_gamepads()
def __assign_gamepads(self) -> None:
if self.get_gamepad_count() == 1:
# Un seul gamepad -> on l'assigne au joueur 1
self.__joysticks = [pygame.joystick.Joystick(0), ]
self.__player_one_instance_id = self.__joysticks[0].get_instance_id(
)
self.__player_two_instance_id = self.__INVALID_INSTANCE_ID
elif self.get_gamepad_count() == 2:
# Deux gamepads -> on tente de préserver les identifiants connus
self.__joysticks = [pygame.joystick.Joystick(
i) for i in range(self.get_gamepad_count())]
found_player_one_instance_id = False
found_player_two_instance_id = False
for joystick in self.__joysticks:
if joystick.get_instance_id() == self.__player_one_instance_id:
found_player_one_instance_id = True
elif joystick.get_instance_id() == self.__player_two_instance_id:
found_player_two_instance_id = True
if not found_player_one_instance_id and found_player_two_instance_id:
# identifiant du joueur 1 introuvé, mais celui du joueur 2 oui -> on préserve l'identifiant du joueur 2
self.player_in_game(
self.__player_two_instance_id, self.__player_one_instance_id)
elif found_player_one_instance_id and not found_player_two_instance_id:
# identifiant du joueur 1 trouvé, mais pas celui du joueur 2 -> on préserve l'identifiant du joueur 1
self.player_in_game(
self.__player_one_instance_id, self.__player_two_instance_id)
elif not found_player_one_instance_id and not found_player_two_instance_id:
# aucun identifiant trouvé -> on assigne de nouveaux identifiants
self.__player_one_instance_id = self.__joysticks[0].get_instance_id(
)
self.__player_two_instance_id = self.__joysticks[1].get_instance_id(
)
def player_in_game(self, player_found, player_not_found):
for joystick in self.__joysticks:
if joystick.get_instance_id() != player_found:
player_not_found = joystick.get_instance_id()
@staticmethod
def get_gamepad_count() -> int:
"""
Retourne le nombre de gamepads présentement branchés.
:return: nombre de gamepads branchés
"""
return pygame.joystick.get_count()
def manage_keyboard_event(self, event: pygame.event) -> bool:
"""
Gère un événement du clavier.
:param event: l'événement généré par pygame
:return: aucun
"""
player_one_input = self.__player_inputs[self.__PLAYER_ONE]
player_two_input = self.__player_inputs[self.__PLAYER_TWO]
if event.type == pygame.KEYDOWN:
# Événements liés au joueur 1
self.trigger_event_keyboard_down(
event, player_one_input, self.__INPUT_KEYBOARD_PLAYER_ONE)
# Événements liés au joueur 2
self.trigger_event_keyboard_down(
event, player_two_input, self.__INPUT_KEYBOARD_PLAYER_TWO)
elif event.type == pygame.KEYUP:
# Événements liés au joueur 1
self.trigger_event_keyboard_up(
event, player_one_input, self.__INPUT_KEYBOARD_PLAYER_ONE)
# Événements liés au joueur 2
self.trigger_event_keyboard_up(
event, player_two_input, self.__INPUT_KEYBOARD_PLAYER_TWO)
return True
def trigger_event_keyboard_down(self, event, player_input, INPUT_KEYBOARD):
"""
Gère les evenements liée aux touches du clavié appuyée d'un joueur
param: event: l'événement généré par pygame,
player_input : movement d'un joueur,
INPUT_KEYBOARD : touche possible d'un joueur
return : aucun
"""
input_x, input_y = player_input.movement
activity = False
if event.key == INPUT_KEYBOARD['left']:
input_x = -1.0
activity = True
elif event.key == INPUT_KEYBOARD['right']:
input_x = 1.0
activity = True
if event.key == INPUT_KEYBOARD['up']:
input_y = -1.0
activity = True
elif event.key == INPUT_KEYBOARD['down']:
input_y = 1.0
activity = True
if activity:
player_input.movement = input_x, input_y
if event.key == INPUT_KEYBOARD['switch_plus']:
player_input.focus_next_button = True
player_input.focus_prev_button = False
elif event.key == INPUT_KEYBOARD['switch_minus']:
player_input.focus_prev_button = True
player_input.focus_next_button = False
elif event.key == INPUT_KEYBOARD['action']:
player_input.solve_button = True
elif event.key == INPUT_KEYBOARD['show_name']:
if player_input.show_name:
player_input.show_name = False
else:
player_input.show_name = True
elif event.key == INPUT_KEYBOARD['pause']:
if player_input.pause:
player_input.pause = False
else:
player_input.pause = True
def trigger_event_keyboard_up(self, event, player_input, INPUT_KEYBROAD):
"""
Gère les evenements liée aux touches du clavié relachée d'un joueur
param: event: l'événement généré par pygame,
player_input : movement d'un joueur,
INPUT_KEYBOARD : touche possible d'un joueur
return : aucun
"""
input_x, input_y = player_input.movement
activity = False
if event.key in [INPUT_KEYBROAD['left'], INPUT_KEYBROAD['right']]:
input_x = 0.0
activity = True
if event.key in [INPUT_KEYBROAD['up'], INPUT_KEYBROAD['down']]:
input_y = 0.0
activity = True
if activity:
player_input.movement = input_x, input_y
if event.key == INPUT_KEYBROAD['switch_plus']:
player_input.focus_next_button = False
elif event.key == INPUT_KEYBROAD['switch_minus']:
player_input.focus_prev_button = False
elif event.key == INPUT_KEYBROAD['action']:
player_input.solve_button = False
def manage_gamepad_event(self, event: pygame.event) -> None:
"""
Gère un événement de contrôleur de jeu (gamepad).
:param event: l'événement généré par pygame
:return: aucun
"""
# Admission exclusive des événements de contrôleurs de jeu (gamepads) au-delà de ce point
if event.type not in [JOYDEVICEADDED, JOYDEVICEREMOVED, JOYBUTTONDOWN, JOYBUTTONUP, JOYAXISMOTION]:
return
# Vérification si il y a ajout ou retrait d'un contrôleur de jeu (gamepad)
if event.type in [JOYDEVICEADDED, JOYDEVICEREMOVED]:
self.__assign_gamepads()
# Prise en charge d'un événement sur un des contrôleur de jeu (gamepad) branchés
elif self.__joysticks:
# Événements liés au joueur 1
if event.instance_id == self.__player_one_instance_id:
player_one_input = self.__player_inputs[self.__PLAYER_ONE]
self.trigger_event_gamepad(event, player_one_input)
# Événements liés au joueur 2
elif event.instance_id == self.__player_two_instance_id:
player_two_input = self.__player_inputs[self.__PLAYER_TWO]
self.trigger_event_gamepad(event, player_two_input)
def trigger_event_gamepad(self, event: pygame.event, player_input):
"""
Gère les evenements liée aux touches du gamepad d'un joueur
param: event: l'événement généré par pygame,
player_input : movement d'un joueur,
return : aucun
"""
if event.type == JOYBUTTONDOWN:
if event.button == settings.NEXT_BUTTON:
player_input.focus_next_button = True
player_input.focus_prev_button = False
elif event.button == settings.PREV_BUTTON:
player_input.focus_next_button = False
player_input.focus_prev_button = True
if event.button == settings.SOLVE_BUTTON:
player_input.solve_button = True
if event.button == settings.SHOW_NAME_BUTTON:
if player_input.show_name:
player_input.show_name = False
else:
player_input.show_name = True
if event.button == settings.START_BUTTON:
if player_input.pause:
player_input.pause = False
else:
player_input.pause = True
if event.type == JOYBUTTONUP:
if event.button == settings.NEXT_BUTTON:
player_input.focus_next_button = False
elif event.button == settings.PREV_BUTTON:
player_input.focus_prev_button = False
if event.button == settings.SOLVE_BUTTON:
player_input.solve_button = False
if event.type == JOYAXISMOTION:
input_x, input_y = player_input.movement
previous_input_x, previous_input_y = player_input.movement
if event.axis == settings.HORIZONTAL_AXIS: # axe horizontal
input_x = event.value
if event.axis == settings.VERTICAL_AXIS: # axe vertical
input_y = event.value
# Application de la zone morte (dead zone)
if abs(input_x) < self.__DEAD_ZONE:
input_x = 0
if abs(input_y) < self.__DEAD_ZONE:
input_y = 0
# Application du mouvement si il y a un changement (va aussi toucher l'indicateur d'activité)
if input_x != previous_input_x or input_y != previous_input_y:
player_input.movement = input_x, input_y
def player_input(self, player_id: int) -> PlayerInput:
"""
Retourne l'état des entrées pour le joueur spécifié (player_id)
:param player_id: identification du joueur
:return: l'objet PlayerInput décrivant les entrées pour le joueur spécifié
"""
assert player_id in [self.__PLAYER_ONE, self.__PLAYER_TWO]
return self.__player_inputs[player_id]
# ensemble des entrées pour les joueurs
inputs = None
def init() -> None:
""" Initialise le gestionnaire d'entrées. """
global inputs
if not inputs:
inputs = __InputManager()