Python pygame Introduction
In this page:
What is Pygame?
Pygame is a third-party library for building 2D games and interactive graphics on top of SDL, handling window management, drawing, and input in a game-oriented way that general GUI toolkits like Tkinter aren't designed for. It requires a real graphical display, though browser environments like Pyodide can run it too.
Example: What is Pygame?
import pygame
print(pygame.ver)
Initializing Pygame
pygame.init() must be called before any other Pygame functionality is used -- it initializes all of Pygame's internal modules (display, audio, input) at once, and skipping it leads to confusing failures in unrelated parts of the library.
Example: Initializing Pygame
import pygame
pygame.init()
print("Pygame initialized")
pygame.quit()
The Game Loop
Every Pygame program is built around a central game loop -- an intentional infinite loop that, on each iteration, processes input events, updates game state, and redraws the screen, running continuously until the player quits.
Example: The Game Loop
import pygame
pygame.init()
running = True
frame = 0
while running and frame < 3:
frame += 1
running = frame < 3
print("Game loop ran", frame, "frames")
pygame.quit()
Handling System Events
pygame.event.get() retrieves all input events (key presses, mouse clicks, window-close requests) that have occurred since the last check. Checking for a quit event inside the game loop is essential, since without it the window's close button wouldn't actually stop the program.
Example: Handling System Events
import pygame
pygame.init()
events = pygame.event.get()
print("Events checked:", events)
pygame.quit()
Drawing Simple Shapes
pygame.draw.rect() and pygame.draw.circle() render basic shapes directly onto the screen surface each frame, forming the foundation that more complex game graphics -- sprites, animations, UI elements -- are typically built on top of.
Example: Drawing Simple Shapes
import pygame
pygame.init()
screen = pygame.Surface((100, 100))
pygame.draw.rect(screen, (255, 0, 0), (10, 10, 50, 50))
pygame.draw.circle(screen, (0, 255, 0), (50, 50), 20)
print("Shapes drawn to surface")
pygame.quit()
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects