0
# pygame-ce
1
2
pygame-ce (pygame Community Edition) is a free and open-source cross-platform multimedia library designed for developing video games and multimedia applications using Python. Built on top of the Simple DirectMedia Layer (SDL), it provides comprehensive functionality for graphics rendering, sound playback, input handling, and game development with high-level abstractions for common multimedia tasks.
3
4
## Package Information
5
6
- **Package Name**: pygame-ce
7
- **Language**: Python
8
- **Installation**: `pip install pygame-ce`
9
- **License**: LGPL v2.1
10
- **Platform Support**: Windows, macOS, Linux, BSD systems
11
12
## Core Imports
13
14
```python
15
import pygame
16
```
17
18
Common initialization pattern:
19
20
```python
21
import pygame
22
import sys
23
24
# Initialize pygame
25
pygame.init()
26
27
# Your game loop here
28
# ...
29
30
# Quit pygame
31
pygame.quit()
32
sys.exit()
33
```
34
35
Access to specific modules:
36
37
```python
38
import pygame
39
from pygame import Surface, Rect, Color
40
from pygame.sprite import Sprite, Group
41
from pygame.cursors import Cursor
42
from pygame.midi import Input, Output
43
import pygame.typing # Type support
44
import pygame.freetype # Advanced fonts
45
import pygame.surfarray # NumPy integration
46
```
47
48
## Basic Usage
49
50
Complete minimal game example:
51
52
```python
53
import pygame
54
import sys
55
56
# Initialize pygame
57
pygame.init()
58
59
# Set up the display
60
screen = pygame.display.set_mode((800, 600))
61
pygame.display.set_caption("My Game")
62
63
# Game objects
64
clock = pygame.time.Clock()
65
player_rect = pygame.Rect(375, 275, 50, 50)
66
player_color = pygame.Color('blue')
67
68
# Game loop
69
running = True
70
while running:
71
# Handle events
72
for event in pygame.event.get():
73
if event.type == pygame.QUIT:
74
running = False
75
76
# Handle input
77
keys = pygame.key.get_pressed()
78
if keys[pygame.K_LEFT]:
79
player_rect.x -= 5
80
if keys[pygame.K_RIGHT]:
81
player_rect.x += 5
82
if keys[pygame.K_UP]:
83
player_rect.y -= 5
84
if keys[pygame.K_DOWN]:
85
player_rect.y += 5
86
87
# Clear screen
88
screen.fill(pygame.Color('black'))
89
90
# Draw game objects
91
pygame.draw.rect(screen, player_color, player_rect)
92
93
# Update display
94
pygame.display.flip()
95
clock.tick(60) # 60 FPS
96
97
# Quit
98
pygame.quit()
99
sys.exit()
100
```
101
102
## Architecture
103
104
pygame-ce follows a modular architecture with distinct subsystems:
105
106
- **Core System**: Base initialization, error handling, and module management
107
- **Display System**: Window creation, surface management, and screen updates
108
- **Event System**: Input event handling and custom event creation
109
- **Graphics System**: Drawing primitives, surface operations, and transformations
110
- **Audio System**: Sound playback, music, and audio mixing
111
- **Input System**: Keyboard, mouse, and joystick input handling
112
- **Game Objects**: Sprites, collision detection, and group management
113
- **Math Utilities**: Vector mathematics and geometric operations
114
115
## Capabilities
116
117
### Core System Management
118
119
Essential system functions for initializing pygame, managing modules, and handling errors. These functions form the foundation that must be called before using other pygame functionality.
120
121
```python { .api }
122
def init() -> tuple[int, int]: ...
123
def quit() -> None: ...
124
def get_init() -> bool: ...
125
def get_error() -> str: ...
126
def set_error(msg: str) -> None: ...
127
```
128
129
[Core System](./core-system.md)
130
131
### Display and Graphics
132
133
Comprehensive display management including window creation, surface operations, and drawing primitives. Handles everything from basic window setup to advanced graphics rendering and transformations.
134
135
```python { .api }
136
def set_mode(size: tuple[int, int], flags: int = 0, depth: int = 0, display: int = 0, vsync: int = 0) -> Surface: ...
137
def flip() -> None: ...
138
def update(rectangle_list: list[Rect] | None = None) -> None: ...
139
140
class Surface:
141
def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks: tuple[int, int, int, int] | None = None): ...
142
def blit(self, source: Surface, dest: tuple[int, int] | Rect, area: Rect | None = None, special_flags: int = 0) -> Rect: ...
143
```
144
145
[Display and Graphics](./display-graphics.md)
146
147
### Event Handling
148
149
Event system for processing user input and system events. Provides queued event handling with filtering capabilities and custom event creation for game logic.
150
151
```python { .api }
152
class Event:
153
def __init__(self, type: int, dict: dict | None = None): ...
154
155
def get(eventtype: int | None = None, pump: bool = True) -> list[Event]: ...
156
def poll() -> Event: ...
157
def wait(timeout: int = 0) -> Event: ...
158
def post(event: Event) -> None: ...
159
```
160
161
[Event Handling](./event-handling.md)
162
163
### Input Systems
164
165
Comprehensive input handling for keyboard, mouse, and game controllers. Provides both real-time state checking and event-based input processing.
166
167
```python { .api }
168
# Keyboard
169
def get_pressed() -> dict[int, bool]: ...
170
def get_focused() -> bool: ...
171
172
# Mouse
173
def get_pos() -> tuple[int, int]: ...
174
def get_pressed(num_buttons: int = 3) -> tuple[bool, ...]: ...
175
176
class Joystick:
177
def __init__(self, id: int): ...
178
```
179
180
[Input Systems](./input-systems.md)
181
182
### Audio System
183
184
Complete audio subsystem supporting sound effects, music playback, and multi-channel mixing. Handles various audio formats with volume control and channel management.
185
186
```python { .api }
187
class Sound:
188
def __init__(self, file: str | bytes): ...
189
def play(self, loops: int = 0, maxtime: int = 0, fade_ms: int = 0) -> Channel: ...
190
191
def init(frequency: int = 22050, size: int = -16, channels: int = 2, buffer: int = 512) -> None: ...
192
def load(filename: str) -> Sound: ...
193
```
194
195
[Audio System](./audio-system.md)
196
197
### Sprites and Game Objects
198
199
High-level game object management with sprite classes, collision detection, and group operations. Provides organized structure for managing game entities and their interactions.
200
201
```python { .api }
202
class Sprite:
203
def __init__(self): ...
204
def update(self, *args, **kwargs) -> None: ...
205
def kill(self) -> None: ...
206
207
class Group:
208
def add(self, *sprites: Sprite) -> None: ...
209
def remove(self, *sprites: Sprite) -> None: ...
210
def update(self, *args, **kwargs) -> None: ...
211
```
212
213
[Sprites and Game Objects](./sprites-game-objects.md)
214
215
### Mathematical Operations
216
217
Vector mathematics and geometric utilities for game development. Provides 2D and 3D vector operations, rectangle manipulation, and collision detection.
218
219
```python { .api }
220
class Vector2:
221
def __init__(self, x: float = 0, y: float = 0): ...
222
def normalize(self) -> Vector2: ...
223
def distance_to(self, other: Vector2) -> float: ...
224
225
class Rect:
226
def __init__(self, left: int, top: int, width: int, height: int): ...
227
def colliderect(self, rect: Rect) -> bool: ...
228
```
229
230
[Mathematical Operations](./math-operations.md)
231
232
### MIDI Support
233
234
Musical Instrument Digital Interface support for real-time musical input/output, device management, and musical utility functions for music applications.
235
236
```python { .api }
237
class Input:
238
def __init__(self, device_id: int, buffer_size: int = 4096): ...
239
def read(self, num_events: int) -> list[list]: ...
240
def poll(self) -> bool: ...
241
242
class Output:
243
def __init__(self, device_id: int, latency: int = 0, buffer_size: int = 256): ...
244
def note_on(self, note: int, velocity: int = 127, channel: int = 0) -> None: ...
245
def note_off(self, note: int, velocity: int = 0, channel: int = 0) -> None: ...
246
247
def get_device_info(device_id: int) -> tuple[str, str, int, int, int] | None: ...
248
def frequency_to_midi(frequency: float) -> int: ...
249
def midi_to_frequency(midi_note: int) -> float: ...
250
```
251
252
[MIDI Support](./midi-support.md)
253
254
### Typing Support
255
256
Type hints and protocols for enhanced development experience with pygame-ce, providing comprehensive type aliases and protocol classes for better IDE support.
257
258
```python { .api }
259
# Type aliases
260
RectLike = Union[Rect, FRect, SequenceLike[float], SequenceLike[Point], _HasRectAttribute]
261
ColorLike = Union[Color, SequenceLike[int], str, int]
262
FileLike = Union[str, bytes, PathLike[str], PathLike[bytes], IO[bytes], IO[str]]
263
264
# Protocol classes
265
class SequenceLike(Protocol[T_co]):
266
def __getitem__(self, index: int) -> T_co: ...
267
def __len__(self) -> int: ...
268
```
269
270
[Typing Support](./typing-support.md)
271
272
### Cursor Management
273
274
Comprehensive mouse cursor control including system cursors, custom bitmap cursors, and color cursors with compilation utilities.
275
276
```python { .api }
277
class Cursor:
278
def __init__(self, *args): ...
279
type: str # "system", "bitmap", or "color"
280
data: tuple
281
282
def set_cursor(*args) -> None: ...
283
def get_cursor() -> Cursor: ...
284
def compile(strings: tuple[str, ...], black: str = "X", white: str = ".", xor: str = "o") -> tuple[tuple[int, ...], tuple[int, ...]]: ...
285
286
# Pre-defined cursors
287
arrow: Cursor
288
diamond: Cursor
289
ball: Cursor
290
```
291
292
[Cursor Management](./cursor-management.md)
293
294
### Advanced Features
295
296
Specialized functionality including FreeType font rendering, comprehensive NumPy integration, camera input, version information, power management, and modern SDL2 features.
297
298
```python { .api }
299
# FreeType fonts
300
class Font:
301
def render(self, text: str, fgcolor: Color, bgcolor: Color | None = None) -> tuple[Surface, Rect]: ...
302
303
# Complete NumPy integration
304
def array2d(surface: Surface) -> numpy.ndarray: ...
305
def pixels2d(surface: Surface) -> numpy.ndarray: ...
306
def array_red(surface: Surface) -> numpy.ndarray: ...
307
def make_surface(array: numpy.ndarray) -> Surface: ...
308
309
# Version information
310
ver: str
311
vernum: PygameVersion
312
SDL: SDLVersion
313
314
# Power management
315
class PowerState:
316
battery_percent: int | None
317
on_battery: bool
318
charging: bool
319
320
# SDL2 Window management
321
class Window:
322
def __init__(self, title: str = 'pygame window', size: tuple[int, int] = (640, 480)): ...
323
```
324
325
[Advanced Features](./advanced-features.md)
326
327
## Types
328
329
Core types used throughout pygame-ce:
330
331
```python { .api }
332
class Color:
333
def __init__(self, r: int, g: int = None, b: int = None, a: int = 255): ...
334
r: int
335
g: int
336
b: int
337
a: int
338
339
class Rect:
340
def __init__(self, left: int, top: int, width: int, height: int): ...
341
x: int
342
y: int
343
width: int
344
height: int
345
w: int # alias for width
346
h: int # alias for height
347
348
class Surface:
349
def get_size() -> tuple[int, int]: ...
350
def get_rect(**kwargs) -> Rect: ...
351
352
# Event types (constants)
353
QUIT: int
354
KEYDOWN: int
355
KEYUP: int
356
MOUSEBUTTONDOWN: int
357
MOUSEBUTTONUP: int
358
MOUSEMOTION: int
359
```