Learn to code with step-by-step lessons. A place for students to work through programming fundamentals and build skills.
We’re moving from text-based programs to a game window. Pygame is a library that gives you a window, shapes, colours, and keyboard input — everything you need for a simple game.
In the terminal (or your IDE’s terminal):
pip install pygame
If you use Python 3 specifically: pip3 install pygame.
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("My Game")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0)) # black background
pygame.display.flip() # show the new frame
pygame.quit()
pygame.init() — start Pygame.set_mode((width, height)) — open a window.while running: loop runs until the user closes the window.pygame.event.get() — list of things that happened (key press, mouse click, quit).pygame.QUIT — user clicked the close button.screen.fill((r, g, b)) — paint the whole screen one colour. (0, 0, 0) is black.pygame.display.flip() — make the new frame visible.In Pygame you don’t delete things from the screen. You redraw the whole frame every time. So each loop we:
screen.fill(...)).pygame.display.flip().Anything you drew last time is gone after the fill; only what you draw this time appears.
(30, 60, 100) for a blue).Next: 5.2 Coordinates and drawing — the coordinate system and drawing rectangles.