Basic Application
Below is the basic pygame application. You'll want to remember how to make it.
import pygame # imports the module # RESIZABLE is only needed if you want a resizable window from pygame import RESIZABLE # initializes imported pygame modules, always needed when using pygame pygame.init() # creates resizable pygame window that is 500 pixels wide and 400 high # sets the caption of the window to "My first pygame app!" flag = RESIZABLE window = pygame.display.set_mode((500, 400), flag) pygame.display.set_caption("My first pygame app!") # this is where the game loop begins run = True while run: for event in pygame.event.get(): # checks if the close button is pressed # if so, exit the game loop if event.type == pygame.QUIT: run = False # deactivates pygame modules, opposite of pygame.init() pygame.quit()
View code on GitHub.
Running this program will create a resizable black window that is 500 pixels wide and 400 pixels tall.
Code Breakdown
- Line 1 - Import pygame.
- Line 4 - Imports RESIZABLE, which is a constant that is used later.
- Line 7 - Initializes the pygame module, which you always have to do.
- Line 11 - Sets
flag
to RESIZABLE, which we imported. It is called 'flag' becausepygame.display.set_mode
can take from 1 to 5 parameters. The first parameter is necessary and is a tuple/list of height and width, and the second option parameter is any "flags" (such as if the window should be resizable or not); these flags should bepygame.(flag)
.
- Line 12 - Creates the variable window and sets it equal to the screen (of type
pygame.Surface
) returned bypygame.display.set_mode
.
- Line 13 - Sets the window's caption to "My first pygame app!"
- Line 16 - Sets the variable run to True.
- Line 17 - Is the start of our game loop.
- Line 18 - Is what we use to get pygame events, which are discussed later.
- Line 21 - If the pygame event is QUIT, update the game state (from running to not running anymore).
- Line 24 - Deactivates the pygame module. While it isn't needed to make your code run (unlike
pygame.init()
), you should still use it at the end of your code.
Copyright © 2021 Code 4 Tomorrow. All rights reserved.
The code in this course is licensed under the MIT License.
If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.