Open a Window
Lesson 1 of 41 in Coddy's Make Games with Pygame course.
In this course you write a whole pygame program yourself, starting from an empty window. A pygame game opens a window and redraws it many times a second. Each picture is a frame.
The code in the editor is the smallest pygame program that keeps a window open:
pygame.init()
screen = pygame.display.set_mode((400, 300))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()pygame.init() starts pygame. pygame.display.set_mode((400, 300)) opens a window 400 pixels wide and 300 tall, and returns the surface you draw on.
The while running: loop is the game loop. One pass of it makes one frame. pygame.event.get() hands you what happened since the last frame, such as a key press or a click on the window's close button, which arrives as pygame.QUIT. pygame.display.flip() shows the finished frame.
pygame.display.set_caption("My Game") sets the title at the top of the window. Your games run in the browser here, and the same code opens a real window on your computer.
Challenge
EasyGet the window ready for your first game.
- Change the size in
set_modeto(480, 360). - Under the
set_modeline, addpygame.display.set_caption("Move the Square").
Press Play: a bigger window opens, titled Move the Square. Then Check.
Try it yourself
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.display.flip()
pygame.quit()
All lessons in Make Games with Pygame
1The Game Loop
Open a WindowFill the BackgroundPractice on your own: Pygame playground