Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Complete Guide to Pygame Display, Audio, and Geometry Features

Tech Aug 6 2

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 surface
  • flip() -> None: Refresh window surface
  • update(rectangle=None) -> None: Optimized refresh
  • get_desktop_sizes() -> list: Monitor resolutions
  • get_window_size() -> tuple: Current window dimensions
  • get_window_position() -> tuple: Window position
  • set_window_position((x, y)) -> None: Set window location
  • get_active() -> bool: Check if window is active
  • iconify() -> bool: Minimize window
  • set_allow_screensaver(bool=True) -> None: Control screensaver during gameplay
  • get_allow_screensaver() -> bool: Check screensaver setting
  • message_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 count
  • stop(): Stop playback
  • fadeout(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 count
  • get_num_channels() -> count: Get current channel count
  • set_reserved(count) -> count: Reserve channels for important sounds
  • get_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 level
  • get_length() -> seconds: Duration in seconds
  • get_raw() -> bytes: Raw audio data

Channel operations:

  • Channel.play(Sound, ...) -> None: Play on specific channel
  • Channel.stop() -> None: Stop playback
  • Channel.fadeout(time) -> None: Fade out
  • Channel.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 rectangle
  • inflate(x, y) -> Rect: Expand rectangle
  • clip(Rect) -> Rect: Intersection area
  • colliderect(Rect) -> bool: Collision detection
  • collidelist(list) -> index: Find first collision
  • collidelistall(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.

Tags: pygame

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.