Complete Guide to Pygame Display, Audio, and Geometry Features
Display Management
The pygame.display module controls window creation and rendering. The primary method for creating a window is set_mode().
pg.display.set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface
The size parameter defines window dimensions as a tuple (width, height). Setting it to (0, 0) creates a fullscreen window matching screen resolution. Specifying zero for either dimension matches the corresponding screen dimension.
Additional parameters are combined using bitwise OR:
| Flag | Description |
|---|---|
| FULLSCREEN | Fullscreen mode |
| HWSURFACE | Hardware acceleration in fullscreen |
| DOUBLEBUF | Double buffering for OpenGL mode |
| OPENGL | OpenGL rendering context |
| RESIZABLE | Allow window resizing |
| NOFRAME | Hide window decorations |
| SCALED | Scale window for high DPI displays |
| SHOWN | Show window (default) |
| HIDDEN | Hide window |
Example of creating a 400x300 fullscreen hidden window:
pg.display.set_mode((400, 300), pg.FULLSCREEN | pg.HIDDEN)
The SCALED flag enables automatic scaling on high-resolution displays. For resizable windows with scaled content, combine pg.SCALED | pg.RESIZABLE.
Use pg.display.get_surface() to retrieve the current window surface with out storing a reference.
Window Properties
Set window title with set_caption() and icon with set_icon():
pg.display.set_caption(title) -> None
pg.display.set_icon(Surface) -> None
Display Module Functions
get_surface() -> Surface: Retrieve window surfaceflip() -> None: Refresh window surfaceupdate(rectangle=None) -> None: Optimized refreshget_desktop_sizes() -> list: Monitor resolutionsget_window_size() -> tuple: Current window dimensionsget_window_position() -> tuple: Window positionset_window_position((x, y)) -> None: Set window locationget_active() -> bool: Check if window is activeiconify() -> bool: Minimize windowset_allow_screensaver(bool=True) -> None: Control screensaver during gameplayget_allow_screensaver() -> bool: Check screensaver settingmessage_box(title, message=None, message_type='info', ...) -> int: Create dialog boxes
Audio Handling
The pygame.mixer module manages sound playback. Use pre_init() to configure audio settings:
pg.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=512, ...) -> None
Create sound objects with Sound() and play them:
sound = pg.mixer.Sound("click.ogg")
sound.play()
Controls include:
play(loops=0): Play sound with loop countstop(): Stop playbackfadeout(time): Gradual volume reduction
Background music uses the music submodule:
pg.mixer.music.load("bgm.ogg")
pg.mixer.music.play(-1)
Mixer Management
Audio is managed through channels. Default channel count is 8:
set_num_channels(count) -> None: Adjust channel countget_num_channels() -> count: Get current channel countset_reserved(count) -> count: Reserve channels for important soundsget_busy() -> bool: Check if audio is playing
Sound object methods:
set_volume(value) -> None: Volume control (0.0 to 1.0)get_volume() -> value: Current volume levelget_length() -> seconds: Duration in secondsget_raw() -> bytes: Raw audio data
Channel operations:
Channel.play(Sound, ...) -> None: Play on specific channelChannel.stop() -> None: Stop playbackChannel.fadeout(time) -> None: Fade outChannel.set_volume(value) -> None: Set channel volume
Geometry Operations
The pygame.Rect class represents rectangular areas:
r = Rect(0, 1, 2, 3)
x, y, w, h = r
Common rectangle operations:
move(x, y) -> Rect: Move rectangleinflate(x, y) -> Rect: Expand rectangleclip(Rect) -> Rect: Intersection areacolliderect(Rect) -> bool: Collision detectioncollidelist(list) -> index: Find first collisioncollidelistall(list) -> indices: All collision
Floating-point rectangles (FRect) were added in version 2.2.1:
r = pg.FRect(1.3, 1.5, 2, 5)
Vector Mathematics
Pygame supports 2D and 3D vectors via Vector2 and Vector3 classes:
vec = pg.Vector2(10, 10)
vec2 = pg.Vector2(5, 5)
result = vec + vec2
Vector operations include:
- Arithmetic:
+,-,*,/ - Length calculations:
length(),length_squared() - Normalization:
normalize(),is_normalized() - Rotation:
rotate(angle),rotate_rad(angle) - Interpolation:
lerp(Vector2, float),slerp(Vector2, float) - Projection:
project(Vector2)
Mathematical Utilities
The pygame.math module provides mathematical helpers:
pg.math.clamp(value, min, max) -> float
Linear intrepolation:
pg.math.lerp(a, b, value, do_clamp=True) -> float
Smooth step interpolation:
pg.math.smoothstep(a, b, value) -> float
Inverse linear interpolation:
pg.math.invlerp(a, b, value) -> float
Range mapping:
pg.math.remap(i_min, i_max, o_min, o_max, value) -> float
Geometric Objects
The experimental geometry module (2.4.0+) includes:
- Circle
- Line
- Polygon
These provide similar functionality to Rect but for different geometric shapes.