2 min read

Python Pygame Module

pygame is a set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language.

Installation

pip install pygame

Basic Game Structure

A standard Pygame program has a setup section, a main loop (handling events, updating state, drawing), and a teardown.

import pygame

# 1. Setup
pygame.init()
screen_width = 1280
screen_height = 720
screen = pygame.display.set_mode((screen_width, screen_height))
clock = pygame.time.Clock()
running = True

player_pos = pygame.Vector2(screen.get_width() / 2, screen.get_height() / 2)
dt = 0

# 2. Main Loop
while running:
    # Poll for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # Fill the screen with a color to wipe away anything from last frame
    screen.fill("purple")

    # Draw a circle
    pygame.draw.circle(screen, "red", player_pos, 40)

    # Handle Input (Movement)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        player_pos.y -= 300 * dt
    if keys[pygame.K_s]:
        player_pos.y += 300 * dt
    if keys[pygame.K_a]:
        player_pos.x -= 300 * dt
    if keys[pygame.K_d]:
        player_pos.x += 300 * dt

    # Flip() the display to put your work on screen
    pygame.display.flip()

    # limits FPS to 60
    # dt is delta time in seconds since last frame, used for framerate-independent physics.
    dt = clock.tick(60) / 1000

pygame.quit()

Drawing Shapes

# Rectangle: (surface, color, rect_tuple)
pygame.draw.rect(screen, "green", (50, 50, 100, 100))

# Line: (surface, color, start_pos, end_pos, width)
pygame.draw.line(screen, "blue", (0, 0), (100, 100), 5)

Working with Images (Sprites)

# Load an image
player_image = pygame.image.load('player.png')

# Draw (blit) it onto the screen
screen.blit(player_image, (x, y))

Sound

sound = pygame.mixer.Sound('jump.wav')
sound.play()

programming/python/python