In the last post, we got introduced to what pygame is, a few facts about it, an overview of the game we will be making and then a basic development environment setup for working through the series. In this post, we'll start building a video game with pygame.
But before we go any further, I need to make it clear that I'm assuming the following things about you:
- You understand basic English. Trust me, this is not a given.
- You possess basic knowledge of the Python programming language. If not, check out this coding resource to learn.
- You're following along on a Mac, Linux or Windows Laptop or Desktop. You can't use your smartphone for this I'm afraid.
- You've setup a basic development environment and are ready to get coding. If not, then go through the previous post before proceeding with this one
Alright, let's dive in !
Pygame boilerplate.
To get started making a game in pygame, the first step is always to initialize and setup pygame to work in our local environment. If you successfully downloaded and added the starting folder from the previous post, then all you have to do is open the main.py file at the root of the project's directory structure. You should see the following boilerplate:
import pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 720, 400
WINDOW = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Gino")
def main():
"""main code for the game.
"""
game_running = True
while game_running:
# Poll for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
pygame.display.update()
pygame.quit()
if __name__ == '__main__':
main()
Let's quickly walk through what each of the weird new functions on the screen right now actually does:
-
import pygame
: tells the Python interpreter to add everything in the pygame package into our file when it begins executing this file. -
pygame.init()
: is a pygame method (function) which sets up all the modules we need before we can begin using them in our program. i.e it “starts up” pygame so we can begin working with things like graphics, sound, and input. This should always be placed at the top of the file, right after theimport
statements. -
WINDOW = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
: creates a blank canvas (screen) where we can start building our game and sets it's width and height to the values of the constantsSCREEN_WIDTH
andSCREEN_HEIGHT
respectively. Feel free to change the values of these constants to whatever you want them to be, this is your game after all. -
pygame.display.set_caption('Gino')
: sets the title of the game window that will be displayed. This should ideally be the name of the game you want to make. In my case I'm going with Gino, but feel free to come up with a different name. - I decided to package the main gameplay loop and logic inside a custom function called main. I must stress that this is a personal decision on my part and not a rule that you must follow in your own projects. Also, if you choose to follow my idea, your function doesn't have to be called main. You can use a different function name.
- Within my main function, the line
while game_running:
helps to setup a game loop that will run forever (if you let it). And within that loop, the linefor event in pygame.event.get():
enables our program to look into the pygame event queue for any event we want. Then, the lineif event.type == pygame.QUIT
helps our program know when the player hits the ❌ on the game window and then we terminate the game loop by settinggame_running = False
and the game ends without any issues. We'll discuss the _pygame event queue in more detail in future posts_ - The line
pygame.update.display()
, adds a new Surface on the canvas at every cycle (loop). This concept is explained a bit more later on in this post. - The line
if __name__ == '__main__':
tells the python interpreter to run our main function only when the main.py file is executed as a standalone program. Click here to learn more about how that works.
Alright, now that we're done with the walkthrough, let's run the code and see what happens. Open your terminal (or Command Prompt / Powershell if on Windows) and type in either of the following commands:
python main.py
OR (mostly for Linux users)
python3 main.py
then hit the ENTER key on your keyboard. You should see something like this:
Let's make the background white
Our game has a white background, so naturally we need to make the background color of the screen WHITE. To achieve this though, we have to tell the blank canvas earlier named WINDOW to create a new Surface with it's background color set to white.
I'm sure you're now thinking about all or one of the following questions:
- Why is this Surface thing he keeps mentioning ?
- Why do we need a new Surface ?
- How do I actually do that ?
To answer the first question:
A Surface is the most basic layout unit in Pygame. i.e Everything displayed on the screen is displayed as a Surface
For your second question, it would be helpful to imagine the pygame canvas as a pile or stack of sheets of paper, each displaying a different variation of a particular drawing that can not be erased (Assume we made this drawing with a pen instead of a pencil). With in mind, it becomes clear that the only way to make any changes in what is displayed would be to add sheet of paper or, in our case, a new layer or Surface at the top of the stack. Here's something to help your imagination:
This process of adding a new Surface on top all others is essentially the function of the pygame.display.update()
shown earlier. In a nutshell:
All new changes on the canvas in pygame are achieved by layering newer Surfaces with slight variations in what is drawn on them over the older ones.
Lastly, in order to actually do this in our code, we simply have to call the fill()
method on our canvas WINDOW and pass it a tuple representing the RGB value of our the color we want. So within our main function, we'll simply add the following line:
...
def main():
"""main code for the game.
"""
game_running = True
while game_running:
...
WINDOW.fill((255, 255, 255)) # White
pygame.display.update()
pygame.quit()
...
NOTE: You can also pass the name of the color as a string. i.e WINDOW.fill('white')
would work as well.
It's a good idea to refactor the color out into it's own constant so it's more reusable. Remember, being lazy is part of your job as a developer and making things reusable helps you stay lazy:
...
WHITE = (255, 255, 255)
def main():
"""main code for the game.
"""
game_running = True
while game_running:
...
WINDOW.fill(WHITE)
pygame.display.update()
pygame.quit()
...
When you're done making these changes, run your code again and you should see something like this:
That's it, we're done. View the full code on Github
Alright, today we got to initialize and setup pygame in order to build our game, We learned a little bit about Surfaces and how pygame handles the process of updating the canvas during game play and finally, we changed the color of our game's canvas (screen) from the initial black color to a more appropriate white.
Congrats !!! we just got pygame to run on our computer. You're an even more badass Pygamer now.
Ready to level up ? In the next post, we'll begin to look at ways to display game elements on the screen. But for now:
Thanks for reading
Top comments (0)