Open a Window
Part of the The Game Loop section of Coddy's Pygame journey. Lesson 1 of 32.
In this section you write a whole pygame program yourself, starting from an empty window. If you did section 1, this is the loop you have been using, now line by line. 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()
All lessons in The Game Loop
1Move a Square
Open a WindowFill the BackgroundPractice on your own: Pygame playground