0
# Advanced Features
1
2
Specialized functionality including FreeType font rendering, comprehensive NumPy integration, camera input, version information, power management, and modern SDL2 features through the _sdl2 subpackage.
3
4
## Capabilities
5
6
### FreeType Font Rendering
7
8
Advanced font rendering with TrueType/OpenType font support, providing superior text quality and control.
9
10
```python { .api }
11
def init(cache_size: int = 64, resolution: int = 72) -> None:
12
"""
13
Initialize FreeType module.
14
15
Parameters:
16
cache_size: Maximum number of glyphs to cache
17
resolution: DPI resolution for font rendering
18
"""
19
20
def quit() -> None:
21
"""Quit FreeType module."""
22
23
def get_init() -> bool:
24
"""Check if FreeType is initialized."""
25
26
def was_init() -> bool:
27
"""Check if FreeType was ever initialized."""
28
29
def get_version() -> str:
30
"""Get FreeType version string."""
31
32
class Font:
33
def __init__(self, fontpath: str | None = None, size: int = 0, font_index: int = 0, resolution: int = 0, ucs4: bool = False):
34
"""
35
Create FreeType font object.
36
37
Parameters:
38
fontpath: Path to font file (None for default)
39
size: Font size in points
40
font_index: Font face index for collections
41
resolution: DPI resolution (0 for default)
42
ucs4: Enable UCS-4 Unicode support
43
"""
44
45
# Font properties
46
name: str # Font family name
47
path: str # Font file path
48
size: int # Font size in points
49
height: int # Line height in pixels
50
ascender: int # Ascender height
51
descender: int # Descender depth
52
53
# Style properties
54
style: int # Style flags
55
underline: bool # Underline enabled
56
strong: bool # Bold enabled
57
oblique: bool # Italic enabled
58
wide: bool # Wide character spacing
59
60
# Rendering properties
61
antialiased: bool # Anti-aliasing enabled
62
kerning: bool # Kerning enabled
63
vertical: bool # Vertical text layout
64
rotation: int # Text rotation angle
65
fgcolor: Color # Foreground color
66
bgcolor: Color # Background color
67
68
def render(self, text: str, fgcolor: Color | None = None, bgcolor: Color | None = None, style: int = 0, rotation: int = 0, size: int = 0) -> tuple[Surface, Rect]:
69
"""
70
Render text to new surface.
71
72
Parameters:
73
text: Text to render
74
fgcolor: Foreground color (None for font default)
75
bgcolor: Background color (None for transparent)
76
style: Style flags
77
rotation: Rotation angle in degrees
78
size: Font size override (0 for font default)
79
80
Returns:
81
tuple[Surface, Rect]: Rendered surface and bounding rectangle
82
"""
83
84
def render_to(self, surf: Surface, dest: tuple[int, int], text: str, fgcolor: Color | None = None, bgcolor: Color | None = None, style: int = 0, rotation: int = 0, size: int = 0) -> Rect:
85
"""
86
Render text directly to surface.
87
88
Parameters:
89
surf: Target surface
90
dest: (x, y) destination position
91
text: Text to render
92
fgcolor: Foreground color
93
bgcolor: Background color
94
style: Style flags
95
rotation: Rotation angle
96
size: Font size override
97
98
Returns:
99
Rect: Bounding rectangle of rendered text
100
"""
101
102
def get_rect(self, text: str, style: int = 0, rotation: int = 0, size: int = 0) -> Rect:
103
"""
104
Get bounding rectangle for text without rendering.
105
106
Parameters:
107
text: Text to measure
108
style: Style flags
109
rotation: Rotation angle
110
size: Font size override
111
112
Returns:
113
Rect: Bounding rectangle
114
"""
115
116
def get_metrics(self, text: str, size: int = 0) -> list[tuple]:
117
"""
118
Get detailed metrics for each character.
119
120
Parameters:
121
text: Text to analyze
122
size: Font size override
123
124
Returns:
125
list[tuple]: List of (min_x, max_x, min_y, max_y, advance_x, advance_y) for each character
126
"""
127
128
def get_default_font() -> str:
129
"""Get path to default font."""
130
131
def SysFont(name: str, size: int, bold: bool = False, italic: bool = False) -> Font:
132
"""
133
Create font from system fonts.
134
135
Parameters:
136
name: Font family name
137
size: Font size in points
138
bold: Enable bold style
139
italic: Enable italic style
140
141
Returns:
142
Font: System font object
143
"""
144
```
145
146
### NumPy Integration (surfarray)
147
148
High-performance array operations for surface manipulation using NumPy.
149
150
```python { .api }
151
def array2d(surface: Surface) -> numpy.ndarray:
152
"""
153
Copy surface pixels to 2D array.
154
155
Parameters:
156
surface: Source surface
157
158
Returns:
159
numpy.ndarray: 2D array of pixel values
160
"""
161
162
def pixels2d(surface: Surface) -> numpy.ndarray:
163
"""
164
Get reference to surface pixels as 2D array.
165
166
Parameters:
167
surface: Source surface
168
169
Returns:
170
numpy.ndarray: 2D array referencing surface pixels
171
"""
172
173
def array3d(surface: Surface) -> numpy.ndarray:
174
"""
175
Copy surface to 3D RGB array.
176
177
Parameters:
178
surface: Source surface
179
180
Returns:
181
numpy.ndarray: 3D array with RGB channels
182
"""
183
184
def pixels3d(surface: Surface) -> numpy.ndarray:
185
"""
186
Get reference to surface as 3D RGB array.
187
188
Parameters:
189
surface: Source surface
190
191
Returns:
192
numpy.ndarray: 3D array referencing surface RGB
193
"""
194
195
def array_alpha(surface: Surface) -> numpy.ndarray:
196
"""
197
Copy alpha channel to array.
198
199
Parameters:
200
surface: Source surface with alpha
201
202
Returns:
203
numpy.ndarray: 2D array of alpha values
204
"""
205
206
def pixels_alpha(surface: Surface) -> numpy.ndarray:
207
"""
208
Get reference to alpha channel as array.
209
210
Parameters:
211
surface: Source surface with alpha
212
213
Returns:
214
numpy.ndarray: 2D array referencing alpha channel
215
"""
216
217
def array_red(surface: Surface) -> numpy.ndarray:
218
"""
219
Copy red color channel to array.
220
221
Parameters:
222
surface: Source surface
223
224
Returns:
225
numpy.ndarray: 2D array of red channel values
226
"""
227
228
def array_green(surface: Surface) -> numpy.ndarray:
229
"""
230
Copy green color channel to array.
231
232
Parameters:
233
surface: Source surface
234
235
Returns:
236
numpy.ndarray: 2D array of green channel values
237
"""
238
239
def array_blue(surface: Surface) -> numpy.ndarray:
240
"""
241
Copy blue color channel to array.
242
243
Parameters:
244
surface: Source surface
245
246
Returns:
247
numpy.ndarray: 2D array of blue channel values
248
"""
249
250
def array_colorkey(surface: Surface) -> numpy.ndarray:
251
"""
252
Copy colorkey mask to array.
253
254
Parameters:
255
surface: Source surface with colorkey
256
257
Returns:
258
numpy.ndarray: 2D array of colorkey mask
259
"""
260
261
def pixels_red(surface: Surface) -> numpy.ndarray:
262
"""
263
Get reference to red channel as array.
264
265
Parameters:
266
surface: Source surface
267
268
Returns:
269
numpy.ndarray: 2D array referencing red channel
270
"""
271
272
def pixels_green(surface: Surface) -> numpy.ndarray:
273
"""
274
Get reference to green channel as array.
275
276
Parameters:
277
surface: Source surface
278
279
Returns:
280
numpy.ndarray: 2D array referencing green channel
281
"""
282
283
def pixels_blue(surface: Surface) -> numpy.ndarray:
284
"""
285
Get reference to blue channel as array.
286
287
Parameters:
288
surface: Source surface
289
290
Returns:
291
numpy.ndarray: 2D array referencing blue channel
292
"""
293
294
def make_surface(array: numpy.ndarray) -> Surface:
295
"""
296
Create surface from array.
297
298
Parameters:
299
array: NumPy array of pixel data
300
301
Returns:
302
Surface: New surface from array data
303
"""
304
305
def blit_array(surface: Surface, array: numpy.ndarray) -> None:
306
"""
307
Copy array values directly to surface.
308
309
Parameters:
310
surface: Target surface
311
array: Source array data
312
"""
313
314
def map_array(surface: Surface, array3d: numpy.ndarray) -> numpy.ndarray:
315
"""
316
Map 3D array to surface pixel format.
317
318
Parameters:
319
surface: Reference surface for pixel format
320
array3d: 3D RGB array to map
321
322
Returns:
323
numpy.ndarray: Mapped pixel array
324
"""
325
```
326
327
### NumPy Integration (sndarray)
328
329
Audio array manipulation for advanced sound processing.
330
331
```python { .api }
332
def array(sound: Sound) -> numpy.ndarray:
333
"""
334
Copy sound samples to array.
335
336
Parameters:
337
sound: Source sound object
338
339
Returns:
340
numpy.ndarray: Array of audio samples
341
"""
342
343
def samples(sound: Sound) -> numpy.ndarray:
344
"""
345
Get reference to sound samples as array.
346
347
Parameters:
348
sound: Source sound object
349
350
Returns:
351
numpy.ndarray: Array referencing sound samples
352
"""
353
354
def make_sound(array: numpy.ndarray) -> Sound:
355
"""
356
Create sound from array.
357
358
Parameters:
359
array: NumPy array of audio samples
360
361
Returns:
362
Sound: New sound object
363
"""
364
```
365
366
### Camera Input
367
368
Real-time camera capture for computer vision and augmented reality applications.
369
370
```python { .api }
371
def init(backend: str | None = None) -> None:
372
"""
373
Initialize camera module.
374
375
Parameters:
376
backend: Camera backend to use (None for auto-detect)
377
"""
378
379
def quit() -> None:
380
"""Quit camera module."""
381
382
def get_backends() -> list[str]:
383
"""
384
Get available camera backends.
385
386
Returns:
387
list[str]: List of available backends
388
"""
389
390
def list_cameras() -> list[str]:
391
"""
392
Get list of available cameras.
393
394
Returns:
395
list[str]: Camera device names
396
"""
397
398
class Camera:
399
def __init__(self, device: str | int, size: tuple[int, int] = (640, 480), mode: str = 'RGB'):
400
"""
401
Initialize camera object.
402
403
Parameters:
404
device: Camera device name or index
405
size: (width, height) capture resolution
406
mode: Color mode ('RGB', 'YUV', 'HSV')
407
"""
408
409
def start(self) -> None:
410
"""Start camera capture."""
411
412
def stop(self) -> None:
413
"""Stop camera capture."""
414
415
def get_image(self, surface: Surface | None = None) -> Surface:
416
"""
417
Capture image from camera.
418
419
Parameters:
420
surface: Optional surface to capture into
421
422
Returns:
423
Surface: Captured image
424
"""
425
426
def query_image(self) -> bool:
427
"""
428
Check if new image is available.
429
430
Returns:
431
bool: True if new image ready
432
"""
433
434
def get_raw(self) -> bytes:
435
"""
436
Get raw image data.
437
438
Returns:
439
bytes: Raw image buffer
440
"""
441
```
442
443
### Version Information
444
445
Runtime version checking and compatibility information for pygame-ce and underlying SDL.
446
447
```python { .api }
448
# Version strings and tuples
449
ver: str # pygame-ce version string (e.g., "2.5.5")
450
vernum: PygameVersion # pygame-ce version tuple with comparison support
451
rev: str # Revision/build information
452
SDL: SDLVersion # SDL version information
453
454
class PygameVersion(tuple):
455
"""pygame-ce version tuple with comparison and property access."""
456
457
@property
458
def major(self) -> int:
459
"""Major version number."""
460
461
@property
462
def minor(self) -> int:
463
"""Minor version number."""
464
465
@property
466
def patch(self) -> int:
467
"""Patch version number."""
468
469
class SDLVersion(tuple):
470
"""SDL version tuple with comparison and property access."""
471
472
@property
473
def major(self) -> int:
474
"""SDL major version number."""
475
476
@property
477
def minor(self) -> int:
478
"""SDL minor version number."""
479
480
@property
481
def patch(self) -> int:
482
"""SDL patch version number."""
483
```
484
485
### Power Management
486
487
Battery and power state monitoring for mobile and laptop applications.
488
489
```python { .api }
490
class PowerState:
491
"""
492
Power and battery status information.
493
Immutable dataclass containing current power state.
494
"""
495
496
battery_percent: int | None # Battery percentage (0-100) or None if unknown
497
battery_seconds: int | None # Estimated battery seconds remaining or None
498
on_battery: bool # True if running on battery power
499
no_battery: bool # True if no battery is present
500
charging: bool # True if battery is charging
501
charged: bool # True if battery is fully charged
502
plugged_in: bool # True if AC power is connected
503
has_battery: bool # True if device has a battery
504
505
def get_power_info() -> PowerState:
506
"""
507
Get current power and battery status.
508
509
Returns:
510
PowerState: Current power state information
511
"""
512
```
513
514
### Modern SDL2 Features
515
516
Advanced window management and modern SDL2 functionality.
517
518
```python { .api }
519
class Window:
520
def __init__(self, title: str = 'pygame window', size: tuple[int, int] = (640, 480), position: tuple[int, int] | None = None, fullscreen: bool = False, **kwargs):
521
"""
522
Create modern SDL2 window.
523
524
Parameters:
525
title: Window title
526
size: (width, height) window size
527
position: (x, y) window position (None for centered)
528
fullscreen: Create fullscreen window
529
**kwargs: Additional window options
530
"""
531
532
# Window properties
533
id: int # Window ID
534
size: tuple[int, int] # Window size
535
position: tuple[int, int] # Window position
536
title: str # Window title
537
538
# Window state
539
borderless: bool # Borderless window
540
resizable: bool # Resizable window
541
always_on_top: bool # Always on top
542
543
def close(self) -> None:
544
"""Close window."""
545
546
def destroy(self) -> None:
547
"""Destroy window."""
548
549
def hide(self) -> None:
550
"""Hide window."""
551
552
def show(self) -> None:
553
"""Show window."""
554
555
def maximize(self) -> None:
556
"""Maximize window."""
557
558
def minimize(self) -> None:
559
"""Minimize window."""
560
561
def restore(self) -> None:
562
"""Restore window."""
563
564
def set_windowed(self) -> None:
565
"""Set windowed mode."""
566
567
def set_fullscreen(self, desktop: bool = False) -> None:
568
"""
569
Set fullscreen mode.
570
571
Parameters:
572
desktop: Use desktop fullscreen (borderless windowed)
573
"""
574
575
def set_title(self, title: str) -> None:
576
"""Set window title."""
577
578
def get_title(self) -> str:
579
"""Get window title."""
580
581
def set_icon(self, surface: Surface) -> None:
582
"""Set window icon."""
583
584
def set_size(self, size: tuple[int, int]) -> None:
585
"""Set window size."""
586
587
def get_size(self) -> tuple[int, int]:
588
"""Get window size."""
589
590
def set_position(self, position: tuple[int, int], centered: bool = False) -> None:
591
"""
592
Set window position.
593
594
Parameters:
595
position: (x, y) position
596
centered: Center on screen if True
597
"""
598
599
def get_position(self) -> tuple[int, int]:
600
"""Get window position."""
601
602
def set_opacity(self, opacity: float) -> None:
603
"""
604
Set window opacity.
605
606
Parameters:
607
opacity: Opacity value (0.0 to 1.0)
608
"""
609
610
def get_opacity(self) -> float:
611
"""Get window opacity."""
612
```
613
614
### Mask-based Collision Detection
615
616
Pixel-perfect collision detection using bitmasks.
617
618
```python { .api }
619
class Mask:
620
def __init__(self, size: tuple[int, int], fill: bool = False):
621
"""
622
Create collision mask.
623
624
Parameters:
625
size: (width, height) mask dimensions
626
fill: Fill mask initially
627
"""
628
629
def get_size(self) -> tuple[int, int]:
630
"""Get mask dimensions."""
631
632
def get_at(self, pos: tuple[int, int]) -> int:
633
"""
634
Get bit at position.
635
636
Parameters:
637
pos: (x, y) position
638
639
Returns:
640
int: Bit value (0 or 1)
641
"""
642
643
def set_at(self, pos: tuple[int, int], value: int = 1) -> None:
644
"""
645
Set bit at position.
646
647
Parameters:
648
pos: (x, y) position
649
value: Bit value to set
650
"""
651
652
def overlap(self, othermask: Mask, offset: tuple[int, int]) -> tuple[int, int] | None:
653
"""
654
Find overlap with another mask.
655
656
Parameters:
657
othermask: Other mask to test
658
offset: (x, y) offset of other mask
659
660
Returns:
661
tuple[int, int] | None: First overlap point or None
662
"""
663
664
def overlap_area(self, othermask: Mask, offset: tuple[int, int]) -> int:
665
"""
666
Get overlap area with another mask.
667
668
Parameters:
669
othermask: Other mask
670
offset: Offset of other mask
671
672
Returns:
673
int: Number of overlapping pixels
674
"""
675
676
def count(self) -> int:
677
"""Count set bits in mask."""
678
679
def outline(self, every: int = 1) -> list[tuple[int, int]]:
680
"""
681
Get outline points of mask.
682
683
Parameters:
684
every: Sample every N points
685
686
Returns:
687
list[tuple[int, int]]: Outline points
688
"""
689
690
def from_surface(surface: Surface, threshold: int = 127) -> Mask:
691
"""
692
Create mask from surface alpha/colorkey.
693
694
Parameters:
695
surface: Source surface
696
threshold: Alpha threshold for mask creation
697
698
Returns:
699
Mask: Generated collision mask
700
"""
701
```
702
703
## Usage Examples
704
705
### FreeType Font Rendering
706
707
```python
708
import pygame
709
import pygame.freetype
710
711
pygame.init()
712
pygame.freetype.init()
713
714
screen = pygame.display.set_mode((800, 600))
715
716
# Load custom font
717
font = pygame.freetype.Font("arial.ttf", 24)
718
719
# Basic text rendering
720
text_surface, text_rect = font.render("Hello World!", (255, 255, 255))
721
screen.blit(text_surface, (100, 100))
722
723
# Render with styles
724
font.style = pygame.freetype.STYLE_BOLD | pygame.freetype.STYLE_UNDERLINE
725
bold_surface, bold_rect = font.render("Bold Underlined", (255, 0, 0))
726
screen.blit(bold_surface, (100, 150))
727
728
# Render directly to surface
729
font.render_to(screen, (100, 200), "Direct Render", (0, 255, 0))
730
731
# Get text metrics without rendering
732
rect = font.get_rect("Measured Text")
733
print(f"Text size: {rect.size}")
734
735
pygame.display.flip()
736
pygame.freetype.quit()
737
pygame.quit()
738
```
739
740
### NumPy Surface Manipulation
741
742
```python
743
import pygame
744
import numpy as np
745
746
pygame.init()
747
screen = pygame.display.set_mode((800, 600))
748
749
# Create test surface
750
surface = pygame.Surface((100, 100))
751
surface.fill((255, 0, 0)) # Red
752
753
# Get array reference to surface pixels
754
pixels = pygame.surfarray.pixels2d(surface)
755
756
# Modify pixels using NumPy
757
# Create gradient effect
758
for x in range(100):
759
for y in range(100):
760
pixels[x, y] = int(255 * (x + y) / 200)
761
762
# Changes are immediately visible on surface
763
del pixels # Release array reference
764
765
# Create surface from NumPy array
766
array = np.random.randint(0, 255, (200, 200), dtype=np.uint8)
767
noise_surface = pygame.surfarray.make_surface(array)
768
769
# Blit to screen
770
screen.blit(surface, (100, 100))
771
screen.blit(noise_surface, (300, 100))
772
773
pygame.display.flip()
774
pygame.quit()
775
```
776
777
### Camera Capture
778
779
```python
780
import pygame
781
import pygame.camera
782
783
pygame.init()
784
pygame.camera.init()
785
786
# List available cameras
787
cameras = pygame.camera.list_cameras()
788
print(f"Available cameras: {cameras}")
789
790
if cameras:
791
# Create camera object
792
camera = pygame.camera.Camera(cameras[0], (640, 480))
793
camera.start()
794
795
screen = pygame.display.set_mode((640, 480))
796
clock = pygame.time.Clock()
797
798
running = True
799
while running:
800
for event in pygame.event.get():
801
if event.type == pygame.QUIT:
802
running = False
803
804
# Capture image if available
805
if camera.query_image():
806
image = camera.get_image()
807
screen.blit(image, (0, 0))
808
809
pygame.display.flip()
810
clock.tick(30) # 30 FPS for camera
811
812
camera.stop()
813
814
pygame.camera.quit()
815
pygame.quit()
816
```
817
818
### Advanced Window Management
819
820
```python
821
import pygame
822
import pygame._sdl2.video as video
823
824
pygame.init()
825
826
# Create modern SDL2 window
827
window = video.Window("Advanced Window", size=(800, 600))
828
829
# Window manipulation
830
window.set_opacity(0.9) # Semi-transparent
831
window.maximize()
832
window.set_always_on_top(True)
833
834
# Multiple windows
835
window2 = video.Window("Second Window", size=(400, 300), position=(900, 100))
836
837
# Get window properties
838
print(f"Window ID: {window.id}")
839
print(f"Window size: {window.size}")
840
print(f"Window position: {window.position}")
841
842
# Event handling for windows
843
running = True
844
while running:
845
for event in pygame.event.get():
846
if event.type == pygame.QUIT:
847
running = False
848
elif event.type == pygame.WINDOWEVENT:
849
if event.window == window.id:
850
print(f"Window event: {event}")
851
852
window.destroy()
853
window2.destroy()
854
pygame.quit()
855
```
856
857
### Pixel-Perfect Collision with Masks
858
859
```python
860
import pygame
861
862
pygame.init()
863
screen = pygame.display.set_mode((800, 600))
864
865
# Load images with transparency
866
sprite1_img = pygame.image.load("sprite1.png").convert_alpha()
867
sprite2_img = pygame.image.load("sprite2.png").convert_alpha()
868
869
# Create masks from images
870
mask1 = pygame.mask.from_surface(sprite1_img)
871
mask2 = pygame.mask.from_surface(sprite2_img)
872
873
# Position sprites
874
pos1 = (100, 100)
875
pos2 = (150, 120)
876
877
# Check for pixel-perfect collision
878
offset = (pos2[0] - pos1[0], pos2[1] - pos1[1])
879
collision_point = mask1.overlap(mask2, offset)
880
881
if collision_point:
882
print(f"Collision at: {collision_point}")
883
884
# Get overlap area
885
overlap_area = mask1.overlap_area(mask2, offset)
886
print(f"Overlap area: {overlap_area} pixels")
887
888
# Draw sprites and collision info
889
screen.fill((255, 255, 255))
890
screen.blit(sprite1_img, pos1)
891
screen.blit(sprite2_img, pos2)
892
893
if collision_point:
894
# Draw collision point
895
collision_world = (pos1[0] + collision_point[0], pos1[1] + collision_point[1])
896
pygame.draw.circle(screen, (255, 0, 0), collision_world, 5)
897
898
pygame.display.flip()
899
pygame.quit()
900
```
901
902
## Constants
903
904
FreeType style constants:
905
906
```python { .api }
907
# FreeType style flags
908
STYLE_DEFAULT: int # Default style
909
STYLE_NORMAL: int # Normal style
910
STYLE_OBLIQUE: int # Italic/oblique
911
STYLE_STRONG: int # Bold
912
STYLE_UNDERLINE: int # Underlined text
913
STYLE_WIDE: int # Wide character spacing
914
```