Pygame
Pygame is a set of Python modules designed for writing video games. It leverages the Simple DirectMedia Layer (SDL) library, providing cross-platform access to your computer's multimedia hardware, such as sound, video, mouse, keyboard, and joystick. The current stable version is 2.6.1, with frequent minor and bugfix releases, often bundling updates to the underlying SDL library.
Warnings
- gotcha Forgetting to call `pygame.init()` at the beginning of your script can lead to `pygame` modules being uninitialized, causing errors or unexpected behavior. Similarly, omitting `pygame.quit()` at the end can leave system resources tied up.
- gotcha Not regularly processing the event queue with `pygame.event.get()` or `pygame.event.pump()` inside your game loop will cause the window to become unresponsive and can lead to a "not responding" state, especially on Windows.
- gotcha After drawing to the screen, you must call either `pygame.display.update()` or `pygame.display.flip()` to make the changes visible to the user. Forgetting this will result in a blank or static screen.
- gotcha For optimal performance, especially with frequently blitted images, loaded `pygame.Surface` objects should be converted to the display surface's pixel format using `.convert()` or `.convert_alpha()` (for images with transparency) immediately after loading.
Install
-
pip install pygame
Imports
- pygame
import pygame
- init
pygame.init()
- display
pygame.display.set_mode((width, height))
- event
for event in pygame.event.get():
- image
pygame.image.load('path/to/image.png') - time
pygame.time.Clock()
Quickstart
import pygame
pygame.init()
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame Quickstart")
WHITE = (255, 255, 255)
RED = (255, 0, 0)
running = True
clock = pygame.time.Clock()
FPS = 60
player_rect = pygame.Rect(WIDTH // 2 - 25, HEIGHT // 2 - 25, 50, 50)
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Drawing
SCREEN.fill(WHITE) # Fill the background
pygame.draw.rect(SCREEN, RED, player_rect) # Draw a red square
pygame.display.flip() # Update the full display Surface to the screen
clock.tick(FPS) # Control frame rate
pygame.quit()