Open a Window
Lesson 1 of 40 in Coddy's Make Games with Pygame course.
Pygame is a Python library for making 2D games. 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
EasyMake this window ready for your first game:
- Make it 480 pixels wide and 360 tall.
- Set its title to
Move the Squarewithpygame.display.set_caption(), after theset_modeline.
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()
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Make Games with Pygame
1The Game Loop
Open a WindowFill the BackgroundPractice on your own: Pygame playground