Cross-platform library for developing multimedia applications and video games in Python built on top of SDL
Surface creation, manipulation, and image loading/saving. Surfaces are pygame's fundamental building blocks for graphics - they represent images in memory that can be drawn on, transformed, and blitted to other surfaces.
Create surfaces for drawing and image manipulation.
class Surface:
def __init__(self, size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None):
"""
Create a new Surface object representing an image.
Args:
size (tuple[int, int]): (width, height) in pixels
flags (int): Special surface properties
depth (int): Color depth in bits per pixel
masks: Color bit masks for advanced surface creation
"""
def Surface(size: tuple[int, int], flags: int = 0, depth: int = 0, masks = None) -> pygame.Surface:
"""Create a new Surface - functional interface."""Core methods for drawing on surfaces and combining them.
def blit(self, source: pygame.Surface, dest: tuple[int, int], area: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect:
"""
Draw one surface onto another.
Args:
source (pygame.Surface): Surface to draw
dest (tuple[int, int]): (x, y) position to draw at
area (pygame.Rect, optional): Portion of source to draw
special_flags (int): Blending flags
Returns:
pygame.Rect: Area that was affected
"""
def blits(self, blit_sequence: list, doreturn: int = 1) -> list[pygame.Rect]:
"""
Draw many surfaces onto this surface.
Args:
blit_sequence (list): List of (source, dest) or (source, dest, area) tuples
doreturn (int): Whether to return list of affected rectangles
Returns:
list[pygame.Rect]: List of affected areas if doreturn=1
"""
def fill(self, color, rect: pygame.Rect = None, special_flags: int = 0) -> pygame.Rect:
"""
Fill surface with a solid color.
Args:
color: Color to fill with
rect (pygame.Rect, optional): Area to fill (None for entire surface)
special_flags (int): Blending flags
Returns:
pygame.Rect: Area that was filled
"""Convert surfaces between pixel formats and create copies.
def convert(self, surface: pygame.Surface = None) -> pygame.Surface:
"""
Convert surface to same pixel format as display for faster blitting.
Args:
surface (pygame.Surface, optional): Surface to match format with
Returns:
pygame.Surface: New surface with converted format
"""
def convert_alpha(self, surface: pygame.Surface = None) -> pygame.Surface:
"""
Convert surface to same pixel format as display with alpha channel.
Args:
surface (pygame.Surface, optional): Surface to match format with
Returns:
pygame.Surface: New surface with converted format and alpha
"""
def copy(self) -> pygame.Surface:
"""
Create an identical copy of the surface.
Returns:
pygame.Surface: New surface that is an exact copy
"""Direct pixel manipulation for advanced graphics operations.
def get_at(self, pos: tuple[int, int]) -> pygame.Color:
"""
Get color of a single pixel.
Args:
pos (tuple[int, int]): (x, y) pixel position
Returns:
pygame.Color: Color at the specified position
"""
def get_at_mapped(self, pos: tuple[int, int]) -> int:
"""
Get mapped pixel value at position.
Args:
pos (tuple[int, int]): (x, y) pixel position
Returns:
int: Mapped pixel value
"""
def set_at(self, pos: tuple[int, int], color) -> None:
"""
Set color of a single pixel.
Args:
pos (tuple[int, int]): (x, y) pixel position
color: Color to set
"""
def get_rect(self, **kwargs) -> pygame.Rect:
"""
Get rectangular area of the surface.
Args:
**kwargs: Keyword arguments to position the rectangle
Returns:
pygame.Rect: Rectangle representing surface area
"""Access surface dimensions, format, and properties.
def get_size(self) -> tuple[int, int]:
"""Get (width, height) of surface."""
def get_width(self) -> int:
"""Get width of surface in pixels."""
def get_height(self) -> int:
"""Get height of surface in pixels."""
def get_flags(self) -> int:
"""Get surface flags."""
def get_bitsize(self) -> int:
"""Get bits per pixel."""
def get_bytesize(self) -> int:
"""Get bytes per pixel."""
def get_masks(self) -> tuple[int, int, int, int]:
"""Get RGBA bit masks."""
def get_shifts(self) -> tuple[int, int, int, int]:
"""Get RGBA bit shifts."""
def get_losses(self) -> tuple[int, int, int, int]:
"""Get RGBA precision losses."""
def get_pitch(self) -> int:
"""Get bytes per row."""
def map_rgb(self, color) -> int:
"""
Map RGB color to pixel value for this surface's format.
Args:
color: Color to map
Returns:
int: Mapped pixel value
"""
def unmap_rgb(self, mapped_int: int) -> pygame.Color:
"""
Unmap pixel value to RGB color for this surface's format.
Args:
mapped_int (int): Mapped pixel value
Returns:
pygame.Color: RGB color
"""
def set_masks(self, masks: tuple[int, int, int, int]) -> None:
"""
Set RGBA bit masks for this surface.
Args:
masks (tuple[int, int, int, int]): (R, G, B, A) bit masks
"""
def set_shifts(self, shifts: tuple[int, int, int, int]) -> None:
"""
Set RGBA bit shifts for this surface.
Args:
shifts (tuple[int, int, int, int]): (R, G, B, A) bit shifts
"""Control surface transparency and color key effects.
def set_alpha(self, alpha: int, flags: int = 0) -> None:
"""
Set alpha transparency for the surface.
Args:
alpha (int): Transparency value (0-255, 0=transparent, 255=opaque)
flags (int): Alpha blending flags
"""
def get_alpha(self) -> int:
"""
Get current alpha transparency value.
Returns:
int: Alpha value (0-255) or None if per-pixel alpha
"""
def set_colorkey(self, color, flags: int = 0) -> None:
"""
Set transparent color key.
Args:
color: Color to make transparent (None to unset)
flags (int): Colorkey flags
"""
def get_colorkey(self) -> pygame.Color:
"""
Get current colorkey.
Returns:
pygame.Color: Current colorkey color or None
"""
def get_palette(self) -> list[pygame.Color]:
"""
Get color palette for indexed color surfaces.
Returns:
list[pygame.Color]: List of colors in palette or None if not palette surface
"""
def get_palette_at(self, index: int) -> pygame.Color:
"""
Get single palette color by index.
Args:
index (int): Palette index
Returns:
pygame.Color: Color at specified palette index
"""
def set_palette(self, palette: list) -> None:
"""
Set color palette for indexed color surface.
Args:
palette (list): List of colors for palette
"""
def set_palette_at(self, index: int, color) -> None:
"""
Set single palette color by index.
Args:
index (int): Palette index
color: Color to set at index
"""Control the drawable area of a surface.
def set_clip(self, rect: pygame.Rect = None) -> None:
"""
Set clipping area for drawing operations.
Args:
rect (pygame.Rect, optional): Clipping rectangle (None to reset)
"""
def get_clip(self) -> pygame.Rect:
"""
Get current clipping area.
Returns:
pygame.Rect: Current clipping rectangle
"""Lock surface for direct pixel access.
def lock(self) -> None:
"""Lock surface for pixel access (required for some operations)."""
def unlock(self) -> None:
"""Unlock surface after pixel access."""
def mustlock(self) -> bool:
"""
Check if surface must be locked for pixel access.
Returns:
bool: True if locking is required
"""
def get_locked(self) -> bool:
"""
Check if surface is currently locked.
Returns:
bool: True if surface is locked
"""
def get_locks(self) -> tuple:
"""
Get information about current surface locks.
Returns:
tuple: Lock information
"""Advanced surface manipulation including subsurfaces and buffer access.
def subsurface(self, rect: pygame.Rect) -> pygame.Surface:
"""
Create a subsurface that shares pixel data with parent.
Args:
rect (pygame.Rect): Area of parent surface to reference
Returns:
pygame.Surface: New subsurface
"""
def get_parent(self) -> pygame.Surface:
"""Get parent surface of a subsurface."""
def get_abs_parent(self) -> pygame.Surface:
"""Get absolute parent surface."""
def get_offset(self) -> tuple[int, int]:
"""Get offset of subsurface within parent."""
def get_abs_offset(self) -> tuple[int, int]:
"""Get absolute offset within top-level parent."""
def scroll(self, dx: int = 0, dy: int = 0) -> None:
"""
Shift surface image by dx, dy pixels.
Args:
dx (int): Horizontal shift
dy (int): Vertical shift
"""
def get_view(self, kind: str = '2') -> pygame.BufferProxy:
"""
Get array interface view of surface pixels.
Args:
kind (str): View type ('0', '1', '2', '3', or 'r', 'g', 'b', 'a')
Returns:
pygame.BufferProxy: Array interface to pixel data
"""
def get_buffer(self) -> pygame.BufferProxy:
"""
Get buffer object for surface.
Returns:
pygame.BufferProxy: Buffer interface to surface data
"""
def get_bounding_rect(self, min_alpha: int = 1) -> pygame.Rect:
"""
Get smallest rectangle containing non-transparent pixels.
Args:
min_alpha (int): Minimum alpha value to consider non-transparent
Returns:
pygame.Rect: Bounding rectangle of visible pixels
"""
def premul_alpha(self) -> pygame.Surface:
"""
Return copy with premultiplied alpha values.
Returns:
pygame.Surface: New surface with premultiplied alpha
"""Functions for loading and saving images from/to files.
def load(file, namehint: str = "") -> pygame.Surface:
"""
Load an image from file or file-like object.
Args:
file: File path, file object, or file-like object
namehint (str): Hint about file format
Returns:
pygame.Surface: New surface with loaded image
"""
def save(surface: pygame.Surface, file, namehint: str = "") -> None:
"""
Save surface as an image file.
Args:
surface (pygame.Surface): Surface to save
file: File path or file object to save to
namehint (str): Hint about desired file format
"""
def get_extended() -> bool:
"""
Check if extended image formats are supported.
Returns:
bool: True if extended formats available
"""
def get_sdl_image_version() -> tuple[int, int, int]:
"""
Get SDL_image library version.
Returns:
tuple[int, int, int]: (major, minor, patch) version
"""import pygame
pygame.init()
# Create surfaces
screen = pygame.display.set_mode((800, 600))
surface = pygame.Surface((100, 100))
# Fill surface with color
surface.fill((255, 0, 0)) # Red
# Draw surface onto screen
screen.blit(surface, (50, 50))
# Get surface properties
width, height = surface.get_size()
print(f"Surface size: {width}x{height}")
pygame.display.flip()import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Load image
try:
image = pygame.image.load("player.png")
# Convert for better performance
image = image.convert_alpha()
except pygame.error as e:
print(f"Could not load image: {e}")
# Create fallback surface
image = pygame.Surface((50, 50))
image.fill((0, 255, 0))
# Get image rectangle for positioning
image_rect = image.get_rect()
image_rect.center = (400, 300)
# Draw image
screen.blit(image, image_rect)
pygame.display.flip()
# Save screenshot
pygame.image.save(screen, "screenshot.png")import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Create surface with alpha channel
alpha_surface = pygame.Surface((100, 100), pygame.SRCALPHA)
alpha_surface.fill((255, 0, 0, 128)) # Semi-transparent red
# Create surface with colorkey transparency
colorkey_surface = pygame.Surface((100, 100))
colorkey_surface.fill((255, 0, 255)) # Magenta background
colorkey_surface.set_colorkey((255, 0, 255)) # Make magenta transparent
# Draw a shape that won't be transparent
pygame.draw.circle(colorkey_surface, (0, 255, 0), (50, 50), 30)
# Blit both surfaces
screen.fill((255, 255, 255))
screen.blit(alpha_surface, (100, 100))
screen.blit(colorkey_surface, (300, 100))
pygame.display.flip()import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Create surface for pixel manipulation
pixel_surface = pygame.Surface((200, 200))
pixel_surface.fill((0, 0, 0))
# Set individual pixels
for x in range(0, 200, 2):
for y in range(0, 200, 2):
color_value = ((x + y) * 255) // 400
pixel_surface.set_at((x, y), (color_value, 0, 255 - color_value))
# Read pixel color
center_color = pixel_surface.get_at((100, 100))
print(f"Center pixel color: {center_color}")
# Draw to screen
screen.blit(pixel_surface, (300, 200))
pygame.display.flip()import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Create a large surface
large_surface = pygame.Surface((300, 300))
large_surface.fill((100, 100, 100))
# Draw pattern on large surface
for i in range(0, 300, 20):
pygame.draw.line(large_surface, (255, 255, 0), (0, i), (300, i), 2)
# Create subsurface (shares pixel data with parent)
sub_surface = large_surface.subsurface(pygame.Rect(50, 50, 200, 200))
# Draw on subsurface (affects parent too)
pygame.draw.circle(sub_surface, (255, 0, 0), (100, 100), 50)
# Use clipping to restrict drawing area
large_surface.set_clip(pygame.Rect(0, 0, 150, 150))
pygame.draw.rect(large_surface, (0, 255, 0), (0, 0, 300, 300), 5) # Only draws in clipped area
# Draw to screen
screen.blit(large_surface, (200, 100))
pygame.display.flip()