Let's get started
In this section we will look at the basics of how PyGame works and get a basic implenentation working. It won't do too much at this stage but the next sections of the tutorial will build opon this to start making things interesting.
The template below is a good starting point for creating programs / games using PyGame. When creating a game, starting by copying in this code is a good way to begin.
The code below is a basic template for building a game in PyGame. There are other ways we could build this out but what we have below is a good simple starting point with the flexibility to do quite a lot.
If you put the above code into a file, save it and run it you should get a basic window open up similar to the one to the right.
Let's break this down and understand what's going on :
This section is really just if you are interested but here I will build up the template piece by piece to see what effect the different sections have on your program. This can help you to understand what each sections is doing.
If you create a file and build it up following these code nippets it will help give you a better understanding of what each part of the code is doing.
The following code is the bare minimum required to get a window up and running :
You'll notice if you run it that the window pops up but then immediately disappears. This is because there is no game loop to keep the program running. Let's add that back in to keep the window open :
Running the program now you will notice that the window stays open but if we try to close it by pressing the X button at the top nothing happens. That's because that button doesn't actually close the program. What it actually does is tell the OS (operating system) to send a message to the program that it should quit. The program can then do any tasks that it needs to do (eg. close files, check with the user about saving things etc) before actually quitting. We haven't got any code yet to close the program so let's put that in now.
You'll notice that we've now taken out that temporary filler code on line 13 and replaced it with a for loop which allows us to grab all the events which have occurred since the last time through the loop and work through them one by one.
On line 15 we check if the event is of type QUIT and if it is then we shut down the program.
This for loop will be expanded in future parts of the tutorial with more if statements to allow you to detect other event types such as keyboard presses or mouse movements or presses.
Checking for events should always be the first thing we do in our game loop.
The last bit we will look at here is filling in the window with a background colour. Let's add in a variable to hold the background colour (because it's good programming practice to do this rather than just hard code the values).
If you save and run this code you'll notice that nothing seems to change. The window is still black. That's because although we've put in the command to fill the window, rendering actions aren't applied straight away. They wait until we call the command to update the display. We always do this action as the last thing in our game loop so let's add that in now :
The reason for this behaviour is that it improves performance. Certain drawing actions may overlap on others. This means that each pixel will be updated only once rather than potentially multiple times. Asking the OS to draw to the screen is also quite a complex job so doing it only once saves resources and makes everything work that little bit quicker and smoother.
The remaining bits of the template will be expanded on in future parts of the tutorial so I won't discuss them now. Until we get more functionality in they won't have any noticeable impact on your program. They are in the template for convenience and will make it easier and quicker to get into doing the fun stuff later on.
Programming languages like Python are what are known as procedural languages. The code is executed one line after the other starting at the top and working down to the bottom (with a few exceptions like loops and function calls adjusting the path here and there). When we get to the bottom the program is finished and it stops.
A game however needs to continue running and continuously react to your inputs. We create a loop in our code to get it to keep running whilst we are playing the game. These loops are known as game loops and they typically take on a particular pattern which fits the way a game is structured.
At the beginning of the loop, identify all the interacctions which have occured (keyboard presses, mouse movements etc).
Here is where we put code to update the details of all the game elements. Move the enemies. Work out if health needs to change. Update the state of the character based upon any inputs that have happened. etc.
Finally, draw everything to the screen in their updated states.
You don't have to do things in this order and we could in fact mix all the code for these three stages in together. For smaller, simpler games this may seem to be a quicker and easier approach. As your game gets bigger and more complex however it is going to be easier to manage if you break your code up into these three distinct sections.
When building a PyGame program there are two points two things which commonly trip students up. They are easy to avoid though if you are aware of them.
If you name your program pygame.py then when you go to run it you will get an error stating that the pygame library can't be found. This is because of the way python works with respect to libraries. If you name your file as pygame.py then Python gets confused when you try to load the pygame library and things that your file is the library. It then tries to load PyGame from your file instead of the actual PyGame file.
This is really easy to avoid, just never name your file pygame.py.
This is lines 24 to 27 in the template above. Every time you create a new game loop (for different screens in your game, which you will learn about later) you will also need to include these lines as the first thing in your loop.
If you don't then your game will function fine at first but will soon become unresponsive.
The reason for this is that PyGame creates a queue for events which are passed to it by the OS (operating system). This queue builds up as the OS is constantly sending events (even though most of these events are not of interest to us they are still generated and added to the queue). Every time we call pygame.event.get() all the events currently in the queue are returned to us and the queue is cleared. If we don't call pygame.event.get() then the queue keeps growing and eventually overwhelms the computer (consuming too much memory).
So even if you don't need to react to any particular events in your game during a particular game loop, always include these lines of code anyway and you won't run into any issues. It will also mean that when you click the close button it will actually work.
Even though our program doesn't do too much just yet we can still tinker with a few elements to make sure we understand them.
Have a go at the following :
1. Change the numbers after the variable declarations for WINDOW_WIDTH and WINDOW_HEIGHT. What happens?
2. Can you change the dimensions of the game window to emulate a mobile phone screen?
3. Change the string 'My Game!' to something else. Save it and run your program again. Can you see what has changed?
4. Colours are created as a series of values representing the amount of Red, Green and Blue. 0 means none and 255 means full intensity. You can see above that we have full intensity for each of Red, Green and Blue and this sets the colour to white. If you tinker with those 3 values on the line setting the value for the variable BACKGROUND, changing the values to new values between 0 and 255 you can set the background to a heap of different colours.
If you set the values to (255, 0, 0) for instance, save and run your program you should see the background of the window change to red. See if you can find the combinations of values required to create the following colours :