Here is an example that implements all that we learned in this chapter. It creates a window, creates an object to draw to the screen, and then moves that object each iteration.
import pygame RED = (255, 0, 0) BLACK = (0, 0, 0) x = y = 0 width = 100 height = 50 # initializes imported pygame modules pygame.init() # creates pygame window that is 500 pixels wide and 400 high # sets the caption of the window to "My first pygame app!" window = pygame.display.set_mode((500, 400)) pygame.display.set_caption("My first pygame app!") # this is where the game loop begins run = True while run: # change the coordinates x, y = x + 1, y + 1 # draw a black screen over the previous frame window.fill(BLACK) # draw a new rectangle and update the screen pygame.draw.rect(window, RED, (x, y, width, height)) pygame.display.update() 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 # deactivate pygame modules, opposite of pygame.init() pygame.quit()
View code on GitHub (useful for line numbers)
If you're having trouble understanding the code, here's a full breakdown:
- Line 1 - Imports the pygame module.
- Lines 3-7 - Defines the background color black, the red color that we want our rectangle to be, and our rectangle's 4 attributes (top-left x, top-left y, width, and height).
- Line 10 - Initializes the pygame module so that we can use it.
- Line 14 - Creates the window (just like in the basic window).
- Line 15 - Sets window caption (also just like in the basic window).
- Line 18 - Sets run to True.
- Line 19 - The start of the game loop.
- Line 21 - Change both the x and y coordinates using variable swapping (mentioned in 14.4 Variable Swapping).
- Line 24 - Clear the previous frame by drawing black over it.
- Line 27 - Draw the rectangle onto the screen (just like how we did it in move objects).
- Line 28 - Update the screen. (this must be done if you want to see anything on the screen beside the initial black).
- Line 30-34 -
pygame.event.get()returns a list of pygame events. If the close button is pressed, that will add a pygame event of type
pygame.QUITto the list returned by
pygame.event.get(). So, if the event's type is
pygame.QUIT, then update the game state from running to not running.
- Line 37 - Deactivate the pygame module.
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 firstname.lastname@example.org for inquiries.