pygame

repository·main·Indexed 27 days ago

https://github.com/pygame/pygame

A free and open-source cross-platform library for developing multimedia applications and video games using Python, abstracting common functions via the Simple DirectMedia Layer (SDL) library.

Tokens
66.6K
Snippets
86
Records
479
Agent score
93%

What's inside pygame

  1. Overview of Pygame modules

    main

    Pygame is composed of several specialized modules for different game development tasks. Key modules include:

    • pygame.display: Control the display window or screen.
    • pygame.event: Manage events and the event queue.
    • pygame.draw: Draw simple shapes onto a Surface.
    • pygame.font: Create and render TrueType fonts.
    • pygame.image: Save and load images.
    • pygame.mouse: Manage the mouse.
    • pygame.key: Manage the keyboard.
    • pygame.joystick: Manage joystick devices.
    • pygame.time: Control timing.
    • pygame.transform: Scale, rotate, and flip images.
    • pygame.cursors: Load cursor images, including standard cursors.
    • pygame.cdrom: Playback.
    • pygame.sndarray: Manipulate sounds with numpy.
    • pygame.surfarray: Manipulate images with numpy.
  2. Convert between NumPy arrays and Sound objects with pygame.sndarray

    main

    The pygame.sndarray module allows you to access and manipulate sound sample data using NumPy arrays. This module requires the external numpy package to be installed.

    Key behaviors:

    • Arrays are indexed by the X axis first, then the Y axis.
    • Samples are 8-bit or 16-bit integers depending on the data format.
    • Stereo sound files contain two values per sample; mono files contain one.
    • The array format will match the format returned by pygame.mixer.get_init().

    Note: If NumPy is not available, this module will not function and will instead return a MissingModule object.

  3. Pygame core features overview

    main

    Pygame provides several key modules for multimedia development:

    • Graphics: Tools for 2D graphics and animation, including support for images, rectangles, and polygon shapes.
    • Sound: Support for playing and manipulating sound and music (WAV, MP3, and OGG formats).
    • Input: Functions for handling keyboard, mouse, and joystick input.
    • Game Development: Specialized tools for collision detection and sprite management.
  4. Access Surface pixel data with pygame.surfarray

    main

    The pygame.surfarray module allows you to access and manipulate pygame.Surface pixel data using NumPy arrays.

    Key distinction between 'array' and 'pixels' functions:

    • array* functions: Copy the surface data into a new NumPy array. Changes to the array do not affect the original surface.
    • pixels* functions: Create an array that directly references the surface memory. Changes to the array will immediately affect the surface. These functions lock the surface for the lifetime of the array.

    Note: This module requires the NumPy package to be installed. If NumPy is unavailable, surfarray becomes a MissingModule object.

  5. Use the experimental pygame.sdl2_video module

    main

    The pygame.sdl2_video module is an experimental module designed for porting new SDL video systems.

    WARNING: This module is still in development and the API is subject to change. It is intended for pygame developers and early adopters in communication with the development team.

  6. Understand the Pygame paradigm

    main

    Pygame is a Python library designed to bridge the gap between low-level console programming and high-level game engines.

    Key characteristics include:

    • Simplicity: Unlike heavy game engines (e.g., Unity or Unreal), Pygame is a library. You can access its full functionality by simply using import pygame in your Python source code.
    • GUI Capabilities: It provides functions for input (keyboard, mouse, file states) and output (drawing geometry, filling colors, setting displays), allowing programs to run in a GUI environment rather than a text console.
    • Event-Driven: Pygame is designed to be event-driven, allowing functions to be executed selectively or almost simultaneously, leveraging Python's execution model.
    • Project Structure: A Pygame project typically consists of a single source code file accompanied by necessary assets like sound or image files in the same directory.
  7. Initialize Pygame and create a display window

    main

    To use Pygame, you must first import the package and call pygame.init() to initialize all available modules. You can then create a graphical window using pygame.display.set_mode(), which returns a Surface object representing the actual displayed graphics. Any drawing performed on this Surface will be visible on the monitor.

    Pygame represents images as Surface objects. The display.set_mode() function defaults to the best graphics modes for the hardware, but you can override these settings.

  8. Explore pygame tutorials

    main

    Pygame provides several tutorials for different skill levels and specific modules:

    • Introduction to Pygame: Basics for new users.
    • Import and Initialize: How to properly import and initialize the various pygame modules.
    • How do I move an Image?: Concepts of 2D animation, drawing, and clearing objects.
    • Sprite Module Introduction: Using the higher-level sprite module to organize game objects.
    • Surfarray Introduction: Using NumPy for efficient per-pixel effects.
    • Camera Module Introduction: Capturing images and live streams.
    • Newbie Guide: Thirteen tips for getting comfortable with the library.
    • Making Games Tutorial: A comprehensive guide for creating entire games.
  9. Handle Window Close Events

    main

    To allow a user to exit the application gracefully, you must poll the event queue in your main loop. Use pygame.event.get() to retrieve a list of events and check if any event's type matches QUIT (imported from pygame.locals). When a QUIT event is detected, call pygame.quit() followed by sys.exit() to terminate both the Pygame module and the Python process.

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
  10. Initialize Pygame and set up a display window

    main

    Before using Pygame, you must initialize its modules. Use pg.init() to attempt to initialize all imported modules. To create a window, use pg.display.set_mode() with desired dimensions and optional flags like pg.SCALED to automatically scale the window for larger displays.

    pg.init()
    screen = pg.display.set_mode((1280, 480), pg.SCALED)
    pg.display.set_caption("Monkey Fever")
    pg.mouse.set_visible(False)
    pg.init()
    screen = pg.display.set_mode((1280, 480), pg.SCALED)
    pg.display.set_caption("Monkey Fever")
    pg.mouse.set_visible(False)
  11. Handle keyboard input using KEYDOWN events

    main

    To respond to a single key press in Pygame, iterate through the event queue using pygame.event.get() and check for the KEYDOWN event type. You can then identify which specific key was pressed by inspecting the event.key attribute.

    Key constants (e.g., K_UP, K_LEFT, K_DOWN, K_RIGHT) are available in pygame.locals.

    Note: The KEYDOWN event triggers only at the moment the key is first pressed; it does not handle continuous

    import pygame, sys
    from pygame.locals import *
    
    # ... setup code ...
    
    while True:
        # ... drawing code ...
    
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_UP:
                    # Handle up press
                    pass
                elif event.key == K_LEFT:
                    # Handle left press
                    pass
                elif event.key == K_DOWN:
                    # Handle down press
                    pass
                elif event.key == K_RIGHT:
                    # Handle right press
                    pass
    
        # ... update logic ...
        pygame.display.update()
  12. Set environment variables for pygame and SDL

    main

    You can control pygame and SDL behavior using environment variables. These can be set in Python code using os.environ or via the command line.

    Important: Some variables must be set before importing pygame, while others must be set before calling specific initialization functions like pygame.init() or pygame.display.set_mode().

    In Python:

    import os
    os.environ['VARIABLE_NAME'] = 'value'

    On Windows (Command Line):

    set VARIABLE_NAME=value
    python my_application.py

    On Linux/Mac (Command Line):

    VARIABLE_NAME=value python my_application.py