Cross-platform library for developing multimedia applications and video games in Python built on top of SDL
npx @tessl/cli install tessl/pypi-pygame@2.6.00
# Pygame
1
2
A comprehensive cross-platform library for developing multimedia applications and video games in Python. Built on top of the Simple DirectMedia Layer (SDL), pygame provides a high-level interface for graphics rendering, sound playback, input handling, and game development utilities, abstracting complex low-level operations into intuitive Python APIs.
3
4
## Package Information
5
6
- **Package Name**: pygame
7
- **Language**: Python
8
- **Installation**: `pip install pygame`
9
- **Version**: 2.6.1
10
- **License**: LGPL
11
12
## Core Imports
13
14
```python
15
import pygame
16
```
17
18
For specific modules:
19
20
```python
21
import pygame.display
22
import pygame.image
23
import pygame.mixer
24
from pygame.locals import * # Import all constants
25
```
26
27
## Basic Usage
28
29
```python
30
import pygame
31
import sys
32
33
# Initialize pygame
34
pygame.init()
35
36
# Set up display
37
screen = pygame.display.set_mode((800, 600))
38
pygame.display.set_caption("My Game")
39
40
# Game loop
41
clock = pygame.time.Clock()
42
running = True
43
44
while running:
45
# Handle events
46
for event in pygame.event.get():
47
if event.type == pygame.QUIT:
48
running = False
49
50
# Fill screen with color
51
screen.fill((0, 0, 0)) # Black
52
53
# Draw something
54
pygame.draw.circle(screen, (255, 0, 0), (400, 300), 50)
55
56
# Update display
57
pygame.display.flip()
58
clock.tick(60) # 60 FPS
59
60
pygame.quit()
61
sys.exit()
62
```
63
64
## Architecture
65
66
Pygame is organized into three categories of modules:
67
68
- **Required Modules**: Core functionality that must be present (base, constants, math, Rect, Color, Surface)
69
- **Standard Modules**: Standard game features that can be missing in stripped distributions (display, draw, event, input)
70
- **Optional Modules**: Extended functionality that may not be available (font, mixer, advanced features)
71
72
The library follows a graceful degradation pattern where missing optional modules are replaced with helpful error messages rather than crashes.
73
74
## Capabilities
75
76
### Core System and Initialization
77
78
Essential pygame initialization, configuration, and core utilities including the main init/quit cycle, error handling, and version information.
79
80
```python { .api }
81
def init() -> tuple[int, int]:
82
"""Initialize all pygame modules, returns (numpass, numfail)"""
83
84
def quit() -> None:
85
"""Uninitialize all pygame modules"""
86
87
def get_init() -> bool:
88
"""Returns True if pygame is initialized"""
89
```
90
91
[Core System](./core-system.md)
92
93
### Graphics and Display
94
95
Display window management, screen surface creation, and display configuration including fullscreen mode, window properties, and OpenGL integration.
96
97
```python { .api }
98
def set_mode(size: tuple[int, int], flags: int = 0, depth: int = 0, display: int = 0, vsync: int = 0) -> pygame.Surface:
99
"""Create a display surface"""
100
101
def flip() -> None:
102
"""Update the full display surface"""
103
104
def update(rectangle: pygame.Rect = None) -> None:
105
"""Update portions of the display"""
106
```
107
108
[Graphics and Display](./graphics-display.md)
109
110
### Drawing and Shapes
111
112
Primitive shape drawing functions for creating graphics including lines, circles, rectangles, polygons, and advanced drawing with antialiasing.
113
114
```python { .api }
115
def rect(surface: pygame.Surface, color, rect: pygame.Rect, width: int = 0, border_radius: int = 0) -> pygame.Rect:
116
"""Draw a rectangle on a surface"""
117
118
def circle(surface: pygame.Surface, color, center: tuple[int, int], radius: int, width: int = 0) -> pygame.Rect:
119
"""Draw a circle on a surface"""
120
121
def line(surface: pygame.Surface, color, start_pos: tuple[int, int], end_pos: tuple[int, int], width: int = 1) -> pygame.Rect:
122
"""Draw a line on a surface"""
123
```
124
125
[Drawing and Shapes](./drawing-shapes.md)
126
127
### Advanced Drawing
128
129
High-precision graphics primitives with antialiasing, filled shapes, and complex drawing operations for professional-quality rendering including bezier curves, pie charts, and textured polygons.
130
131
```python { .api }
132
def aacircle(surface: pygame.Surface, x: int, y: int, r: int, color) -> None:
133
"""Draw an antialiased circle"""
134
135
def filled_polygon(surface: pygame.Surface, points: list[tuple[int, int]], color) -> None:
136
"""Draw a filled polygon"""
137
138
def bezier(surface: pygame.Surface, points: list[tuple[int, int]], steps: int, color) -> None:
139
"""Draw a bezier curve"""
140
```
141
142
[Advanced Drawing](./advanced-drawing.md)
143
144
### Surface and Image Operations
145
146
Surface creation, manipulation, and image loading/saving including pixel access, transformations, color operations, and format conversions.
147
148
```python { .api }
149
class Surface:
150
def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None): ...
151
def blit(self, source: 'Surface', dest: tuple[int, int], area: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect: ...
152
def fill(self, color, rect: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect: ...
153
def get_rect(self, **kwargs) -> pygame.Rect: ...
154
```
155
156
[Surface and Image Operations](./surface-image.md)
157
158
### Event Handling and Input
159
160
Event queue management and input handling including keyboard, mouse, and joystick events with filtering and custom event creation.
161
162
```python { .api }
163
def get(eventtype = None, pump: bool = True, exclude = None) -> list[pygame.event.Event]:
164
"""Get events from the queue"""
165
166
def poll() -> pygame.event.Event:
167
"""Get a single event from the queue"""
168
169
def wait(timeout: int = 0) -> pygame.event.Event:
170
"""Wait for a single event"""
171
```
172
173
[Event Handling and Input](./event-input.md)
174
175
### Input Devices
176
177
Keyboard and mouse input handling including state checking, position tracking, text input, and cursor management with comprehensive support for all input methods.
178
179
```python { .api }
180
def get_pressed() -> ScancodeWrapper:
181
"""Get the state of all keyboard keys"""
182
183
def get_pos() -> tuple[int, int]:
184
"""Get the mouse cursor position"""
185
186
def set_cursor(*args) -> None:
187
"""Set mouse cursor appearance (system, bitmap, or color cursors)"""
188
```
189
190
[Input Devices](./input-devices.md)
191
192
### Joystick and Gamepad Support
193
194
Complete gamepad, joystick, and game controller support including analog sticks, triggers, buttons, d-pads, and haptic feedback for comprehensive game input handling.
195
196
```python { .api }
197
def get_count() -> int:
198
"""Get number of connected joysticks"""
199
200
class Joystick:
201
def __init__(self, id: int): ...
202
def get_axis(self, axis_number: int) -> float: ...
203
def get_button(self, button: int) -> bool: ...
204
def rumble(self, low_frequency: float, high_frequency: float, duration: int) -> bool: ...
205
```
206
207
[Joystick and Gamepad Support](./joystick-gamepad.md)
208
209
### Audio and Sound
210
211
Audio system including sound effects, music streaming, mixing channels, and volume control with support for multiple audio formats.
212
213
```python { .api }
214
class Sound:
215
def __init__(self, file_or_buffer): ...
216
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> pygame.mixer.Channel: ...
217
def stop(self) -> None: ...
218
def get_volume(self) -> float: ...
219
def set_volume(self, value: float) -> None: ...
220
```
221
222
[Audio and Sound](./audio-sound.md)
223
224
### Text and Font Rendering
225
226
Font loading and text rendering including system fonts, TrueType fonts, text metrics, and styling options.
227
228
```python { .api }
229
class Font:
230
def __init__(self, filename, size: int): ...
231
def render(self, text: str, antialias: bool, color, background = None) -> pygame.Surface: ...
232
def size(self, text: str) -> tuple[int, int]: ...
233
def get_height(self) -> int: ...
234
```
235
236
[Text and Font Rendering](./text-font.md)
237
238
### Game Object Management
239
240
Sprite and collision system for managing game objects including sprite groups, collision detection algorithms, and update/rendering workflows.
241
242
```python { .api }
243
class Sprite:
244
def __init__(self): ...
245
def update(self, *args): ...
246
def kill(self) -> None: ...
247
248
class Group:
249
def __init__(self, *sprites): ...
250
def update(self, *args): ...
251
def draw(self, surface: pygame.Surface) -> None: ...
252
```
253
254
[Game Object Management](./game-objects.md)
255
256
### Mathematical Utilities
257
258
Mathematical functions and vector operations including 2D/3D vectors, collision detection math, and utility functions for game calculations.
259
260
```python { .api }
261
class Vector2:
262
def __init__(self, x: float = 0, y: float = 0): ...
263
def dot(self, vector: 'Vector2') -> float: ...
264
def cross(self, vector: 'Vector2') -> float: ...
265
def normalize(self) -> 'Vector2': ...
266
def rotate(self, angle: float) -> 'Vector2': ...
267
268
class Vector3:
269
def __init__(self, x: float = 0, y: float = 0, z: float = 0): ...
270
```
271
272
[Mathematical Utilities](./math-utils.md)
273
274
### Time and Animation
275
276
Timing control, frame rate management, and animation support including clock objects, delays, and timer events for smooth gameplay.
277
278
```python { .api }
279
class Clock:
280
def __init__(self): ...
281
def tick(self, framerate: int = 0) -> int: ...
282
def get_fps(self) -> float: ...
283
def get_time(self) -> int: ...
284
285
def get_ticks() -> int:
286
"""Get milliseconds since pygame.init() was called"""
287
288
def wait(milliseconds: int) -> int:
289
"""Pause the program for an amount of time"""
290
```
291
292
[Time and Animation](./time-animation.md)
293
294
### Transform and Image Processing
295
296
Image transformation operations including scaling, rotation, flipping, and advanced image processing filters.
297
298
```python { .api }
299
def scale(surface: pygame.Surface, size: tuple[int, int]) -> pygame.Surface:
300
"""Resize a surface to new resolution"""
301
302
def rotate(surface: pygame.Surface, angle: float) -> pygame.Surface:
303
"""Rotate an image"""
304
305
def flip(surface: pygame.Surface, xbool: bool, ybool: bool) -> pygame.Surface:
306
"""Flip an image vertically and horizontally"""
307
```
308
309
[Transform and Image Processing](./transform-image.md)
310
311
## Core Types and Constants
312
313
### Rect Class
314
315
```python { .api }
316
class Rect:
317
def __init__(self, left: int, top: int, width: int, height: int): ...
318
319
# Position properties
320
x: int
321
y: int
322
top: int
323
left: int
324
bottom: int
325
right: int
326
center: tuple[int, int]
327
328
# Size properties
329
width: int
330
height: int
331
size: tuple[int, int]
332
333
# Methods
334
def move(self, x: int, y: int) -> 'Rect': ...
335
def inflate(self, x: int, y: int) -> 'Rect': ...
336
def colliderect(self, rect: 'Rect') -> bool: ...
337
def contains(self, rect: 'Rect') -> bool: ...
338
def union(self, rect: 'Rect') -> 'Rect': ...
339
def clip(self, rect: 'Rect') -> 'Rect': ...
340
```
341
342
### Color Class
343
344
```python { .api }
345
class Color:
346
def __init__(self, r: int, g: int = None, b: int = None, a: int = 255): ...
347
348
# Color components
349
r: int # Red (0-255)
350
g: int # Green (0-255)
351
b: int # Blue (0-255)
352
a: int # Alpha (0-255)
353
354
# Color space properties
355
cmy: tuple[float, float, float]
356
hsva: tuple[float, float, float, float]
357
hsla: tuple[float, float, float, float]
358
359
# Methods
360
def normalize(self) -> tuple[float, float, float, float]: ...
361
def lerp(self, color: 'Color', t: float) -> 'Color': ...
362
def grayscale(self) -> 'Color': ...
363
```
364
365
### Event Class
366
367
```python { .api }
368
class Event:
369
def __init__(self, type: int, **attributes): ...
370
371
type: int # Event type constant
372
# Dynamic attributes based on event type
373
```
374
375
### Key Constants
376
377
```python { .api }
378
# Common key constants
379
K_ESCAPE: int
380
K_SPACE: int
381
K_RETURN: int
382
K_UP: int
383
K_DOWN: int
384
K_LEFT: int
385
K_RIGHT: int
386
K_a: int # through K_z
387
K_0: int # through K_9
388
389
# Event type constants
390
QUIT: int
391
KEYDOWN: int
392
KEYUP: int
393
MOUSEBUTTONDOWN: int
394
MOUSEBUTTONUP: int
395
MOUSEMOTION: int
396
397
# Display flag constants
398
FULLSCREEN: int
399
DOUBLEBUF: int
400
HWSURFACE: int
401
OPENGL: int
402
RESIZABLE: int
403
```