0
# Input Systems
1
2
Comprehensive input handling for keyboard, mouse, and game controllers. Provides both real-time state checking and event-based input processing.
3
4
## Capabilities
5
6
### Keyboard Input
7
8
Real-time keyboard state checking and configuration functions.
9
10
```python { .api }
11
def get_focused() -> bool:
12
"""
13
Check if display is receiving keyboard input.
14
15
Returns:
16
bool: True if window has keyboard focus
17
"""
18
19
def get_pressed() -> dict[int, bool]:
20
"""
21
Get state of all keyboard buttons.
22
23
Returns:
24
dict[int, bool]: Mapping of key constants to pressed state
25
"""
26
27
def get_just_pressed() -> dict[int, bool]:
28
"""
29
Get keys that were just pressed since last call.
30
31
Returns:
32
dict[int, bool]: Mapping of key constants to just-pressed state
33
"""
34
35
def get_just_released() -> dict[int, bool]:
36
"""
37
Get keys that were just released since last call.
38
39
Returns:
40
dict[int, bool]: Mapping of key constants to just-released state
41
"""
42
43
def get_mods() -> int:
44
"""
45
Get currently pressed modifier keys.
46
47
Returns:
48
int: Bitmask of modifier key constants
49
"""
50
51
def set_mods(int) -> None:
52
"""
53
Set modifier key state.
54
55
Parameters:
56
int: Bitmask of modifier keys to set as pressed
57
"""
58
59
def set_repeat(delay: int = 0, interval: int = 0) -> None:
60
"""
61
Set key repeat rate.
62
63
Parameters:
64
delay: Milliseconds before first repeat (0 to disable)
65
interval: Milliseconds between repeats
66
"""
67
68
def get_repeat() -> tuple[int, int]:
69
"""
70
Get key repeat settings.
71
72
Returns:
73
tuple[int, int]: (delay, interval) in milliseconds
74
"""
75
76
def name(key: int) -> str:
77
"""
78
Get name of key from key constant.
79
80
Parameters:
81
key: Key constant
82
83
Returns:
84
str: Human-readable key name
85
"""
86
87
def key_code(name: str) -> int:
88
"""
89
Get key constant from key name.
90
91
Parameters:
92
name: Key name string
93
94
Returns:
95
int: Key constant
96
"""
97
```
98
99
### Unicode Text Input
100
101
Functions for handling Unicode text input for text fields and chat systems.
102
103
```python { .api }
104
def start_text_input() -> None:
105
"""
106
Start Unicode text input.
107
Enables TEXTINPUT events and on-screen keyboards on mobile.
108
"""
109
110
def stop_text_input() -> None:
111
"""
112
Stop Unicode text input.
113
Disables TEXTINPUT events.
114
"""
115
116
def set_text_input_rect(rect: Rect) -> None:
117
"""
118
Set rectangle for text input composition.
119
120
Parameters:
121
rect: Rectangle where text composition occurs
122
"""
123
```
124
125
### Mouse Input
126
127
Real-time mouse state checking and position functions.
128
129
```python { .api }
130
def get_pressed(num_buttons: int = 3) -> tuple[bool, ...]:
131
"""
132
Get mouse button states.
133
134
Parameters:
135
num_buttons: Number of buttons to check
136
137
Returns:
138
tuple[bool, ...]: Button states (left, middle, right, ...)
139
"""
140
141
def get_just_pressed() -> tuple[bool, bool, bool]:
142
"""
143
Get mouse buttons that were just pressed.
144
145
Returns:
146
tuple[bool, bool, bool]: (left, middle, right) just-pressed states
147
"""
148
149
def get_just_released() -> tuple[bool, bool, bool]:
150
"""
151
Get mouse buttons that were just released.
152
153
Returns:
154
tuple[bool, bool, bool]: (left, middle, right) just-released states
155
"""
156
157
def get_pos() -> tuple[int, int]:
158
"""
159
Get mouse cursor position.
160
161
Returns:
162
tuple[int, int]: (x, y) position relative to window
163
"""
164
165
def get_rel() -> tuple[int, int]:
166
"""
167
Get relative mouse movement since last call.
168
169
Returns:
170
tuple[int, int]: (x, y) movement in pixels
171
"""
172
173
def set_pos(pos: tuple[int, int]) -> None:
174
"""
175
Set mouse cursor position.
176
177
Parameters:
178
pos: (x, y) position to set
179
"""
180
181
def set_visible(bool) -> bool:
182
"""
183
Set mouse cursor visibility.
184
185
Parameters:
186
bool: True to show cursor, False to hide
187
188
Returns:
189
bool: Previous visibility state
190
"""
191
192
def get_visible() -> bool:
193
"""
194
Get mouse cursor visibility.
195
196
Returns:
197
bool: True if cursor is visible
198
"""
199
200
def get_focused() -> bool:
201
"""
202
Check if display is receiving mouse input.
203
204
Returns:
205
bool: True if window has mouse focus
206
"""
207
208
def set_cursor(cursor) -> None:
209
"""
210
Set mouse cursor appearance.
211
212
Parameters:
213
cursor: Cursor object or system cursor constant
214
"""
215
216
def get_cursor() -> object:
217
"""
218
Get current mouse cursor.
219
220
Returns:
221
object: Current cursor object
222
"""
223
224
def set_relative_mode(enable: bool) -> None:
225
"""
226
Enable/disable relative mouse mode.
227
In relative mode, cursor is hidden and confined to window,
228
providing unlimited mouse movement.
229
230
Parameters:
231
enable: True to enable relative mode
232
"""
233
234
def get_relative_mode() -> bool:
235
"""
236
Get relative mouse mode state.
237
238
Returns:
239
bool: True if relative mode is enabled
240
"""
241
```
242
243
### Joystick/Game Controller Input
244
245
Comprehensive game controller and joystick support.
246
247
```python { .api }
248
def init() -> None:
249
"""Initialize joystick module."""
250
251
def quit() -> None:
252
"""Uninitialize joystick module."""
253
254
def get_init() -> bool:
255
"""
256
Check if joystick module is initialized.
257
258
Returns:
259
bool: True if joystick module is initialized
260
"""
261
262
def get_count() -> int:
263
"""
264
Get number of joysticks connected.
265
266
Returns:
267
int: Number of connected joysticks
268
"""
269
270
class Joystick:
271
def __init__(self, id: int):
272
"""
273
Initialize joystick object.
274
275
Parameters:
276
id: Joystick device ID (0 to get_count()-1)
277
"""
278
279
def init(self) -> None:
280
"""Initialize the joystick for use."""
281
282
def quit(self) -> None:
283
"""Uninitialize the joystick."""
284
285
def get_init(self) -> bool:
286
"""
287
Check if joystick is initialized.
288
289
Returns:
290
bool: True if joystick is initialized
291
"""
292
293
def get_id(self) -> int:
294
"""
295
Get joystick ID.
296
297
Returns:
298
int: Joystick ID
299
"""
300
301
def get_name(self) -> str:
302
"""
303
Get joystick name.
304
305
Returns:
306
str: Joystick device name
307
"""
308
309
def get_numaxes(self) -> int:
310
"""
311
Get number of axes.
312
313
Returns:
314
int: Number of axes on joystick
315
"""
316
317
def get_axis(self, axis_number: int) -> float:
318
"""
319
Get axis value.
320
321
Parameters:
322
axis_number: Axis index
323
324
Returns:
325
float: Axis value from -1.0 to 1.0
326
"""
327
328
def get_numbuttons(self) -> int:
329
"""
330
Get number of buttons.
331
332
Returns:
333
int: Number of buttons on joystick
334
"""
335
336
def get_button(self, button: int) -> bool:
337
"""
338
Get button state.
339
340
Parameters:
341
button: Button index
342
343
Returns:
344
bool: True if button is pressed
345
"""
346
347
def get_numballs(self) -> int:
348
"""
349
Get number of trackballs.
350
351
Returns:
352
int: Number of trackballs on joystick
353
"""
354
355
def get_ball(self, ball_number: int) -> tuple[int, int]:
356
"""
357
Get trackball movement.
358
359
Parameters:
360
ball_number: Trackball index
361
362
Returns:
363
tuple[int, int]: (x, y) movement since last call
364
"""
365
366
def get_numhats(self) -> int:
367
"""
368
Get number of hat controls.
369
370
Returns:
371
int: Number of hats on joystick
372
"""
373
374
def get_hat(self, hat_number: int) -> tuple[int, int]:
375
"""
376
Get hat position.
377
378
Parameters:
379
hat_number: Hat index
380
381
Returns:
382
tuple[int, int]: Hat position (-1, 0, 1 for each axis)
383
"""
384
```
385
386
## Usage Examples
387
388
### Keyboard Input
389
390
```python
391
import pygame
392
393
pygame.init()
394
screen = pygame.display.set_mode((800, 600))
395
clock = pygame.time.Clock()
396
397
running = True
398
while running:
399
# Handle events
400
for event in pygame.event.get():
401
if event.type == pygame.QUIT:
402
running = False
403
elif event.type == pygame.KEYDOWN:
404
print(f"Key pressed: {pygame.key.name(event.key)}")
405
406
# Check real-time key states
407
keys = pygame.key.get_pressed()
408
409
# Movement with arrow keys
410
if keys[pygame.K_LEFT]:
411
print("Moving left")
412
if keys[pygame.K_RIGHT]:
413
print("Moving right")
414
if keys[pygame.K_UP]:
415
print("Moving up")
416
if keys[pygame.K_DOWN]:
417
print("Moving down")
418
419
# Check for key combinations
420
if keys[pygame.K_LCTRL] and keys[pygame.K_s]:
421
print("Ctrl+S pressed!")
422
423
pygame.display.flip()
424
clock.tick(60)
425
426
pygame.quit()
427
```
428
429
### Mouse Input
430
431
```python
432
import pygame
433
434
pygame.init()
435
screen = pygame.display.set_mode((800, 600))
436
437
running = True
438
while running:
439
for event in pygame.event.get():
440
if event.type == pygame.QUIT:
441
running = False
442
elif event.type == pygame.MOUSEBUTTONDOWN:
443
if event.button == 1: # Left click
444
print(f"Left click at {event.pos}")
445
elif event.button == 3: # Right click
446
print(f"Right click at {event.pos}")
447
elif event.type == pygame.MOUSEMOTION:
448
print(f"Mouse moved to {event.pos}, relative: {event.rel}")
449
450
# Check real-time mouse state
451
mouse_buttons = pygame.mouse.get_pressed()
452
mouse_pos = pygame.mouse.get_pos()
453
454
if mouse_buttons[0]: # Left button held
455
print(f"Left button held at {mouse_pos}")
456
457
pygame.display.flip()
458
459
pygame.quit()
460
```
461
462
### Game Controller Input
463
464
```python
465
import pygame
466
467
pygame.init()
468
pygame.joystick.init()
469
470
# Check for connected joysticks
471
joystick_count = pygame.joystick.get_count()
472
print(f"Found {joystick_count} joysticks")
473
474
joysticks = []
475
for i in range(joystick_count):
476
joystick = pygame.joystick.Joystick(i)
477
joystick.init()
478
joysticks.append(joystick)
479
print(f"Joystick {i}: {joystick.get_name()}")
480
481
screen = pygame.display.set_mode((800, 600))
482
clock = pygame.time.Clock()
483
484
running = True
485
while running:
486
for event in pygame.event.get():
487
if event.type == pygame.QUIT:
488
running = False
489
elif event.type == pygame.JOYBUTTONDOWN:
490
print(f"Controller {event.joy} button {event.button} pressed")
491
elif event.type == pygame.JOYAXISMOTION:
492
print(f"Controller {event.joy} axis {event.axis}: {event.value}")
493
elif event.type == pygame.JOYHATMOTION:
494
print(f"Controller {event.joy} hat {event.hat}: {event.value}")
495
496
# Check real-time joystick states
497
for i, joystick in enumerate(joysticks):
498
# Check axes (usually left stick X/Y, right stick X/Y, triggers)
499
num_axes = joystick.get_numaxes()
500
for axis in range(num_axes):
501
value = joystick.get_axis(axis)
502
if abs(value) > 0.1: # Dead zone
503
print(f"Joystick {i} axis {axis}: {value}")
504
505
# Check buttons
506
num_buttons = joystick.get_numbuttons()
507
for button in range(num_buttons):
508
if joystick.get_button(button):
509
print(f"Joystick {i} button {button} pressed")
510
511
pygame.display.flip()
512
clock.tick(60)
513
514
pygame.quit()
515
```
516
517
### Text Input
518
519
```python
520
import pygame
521
522
pygame.init()
523
screen = pygame.display.set_mode((800, 600))
524
font = pygame.font.Font(None, 36)
525
526
# Start text input
527
pygame.key.start_text_input()
528
529
text = ""
530
running = True
531
532
while running:
533
for event in pygame.event.get():
534
if event.type == pygame.QUIT:
535
running = False
536
elif event.type == pygame.KEYDOWN:
537
if event.key == pygame.K_BACKSPACE:
538
text = text[:-1]
539
elif event.key == pygame.K_RETURN:
540
print(f"Entered text: {text}")
541
text = ""
542
elif event.type == pygame.TEXTINPUT:
543
text += event.text
544
545
# Draw text input
546
screen.fill((255, 255, 255))
547
text_surface = font.render(text, True, (0, 0, 0))
548
screen.blit(text_surface, (10, 10))
549
550
pygame.display.flip()
551
552
pygame.key.stop_text_input()
553
pygame.quit()
554
```