← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 14 of 15

Python pygame Introduction

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?

python
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

python
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

python
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

python
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

python
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()

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.