How do i run a python game?
Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Make a 2D Side-Scroller Game With PyGame Show
When I started learning computer programming late in the last millennium, it was driven by my desire to write computer games. I tried to figure out how to
write games in every language and on every platform I learned, including Python. That’s how I discovered By the end of this article, you’ll be able to:
This primer assumes you have a basic understanding of writing Python programs, including user-defined functions, imports,
loops, and conditionals. You should also be familiar with how to open files on your platform. A basic understanding of object-oriented
Python is helpful as well. You can get all of the code in this article to follow along: Background and Setup
To install You can verify the install by loading one of the examples that comes with the library:
If a game window appears, then Basic PyGame ProgramBefore getting down to specifics, let’s take a look at a basic
When you run this program, you’ll see a window that looks like this: Let’s break this code down, section by section:
That’s the PyGame ConceptsAs Initialization and ModulesThe After importing the Displays and SurfacesIn addition to the modules, In Images and RectsYour basic As mentioned above, Okay, that’s enough theory. Let’s design and write a game! Basic Game DesignBefore you start writing any code, it’s always a good idea to have some design in place. Since this is a tutorial game, let’s design some basic gameplay for it as well:
When he was describing software projects, a former colleague of mine used to say, “You don’t know what you do until you know what you don’t do.” With that in mind, here are some things that won’t be covered in this tutorial:
You’re free to try your hand at adding these and other features to your own program. Let’s get started! Importing and Initializing PyGameAfter you import
The Setting Up the DisplayNow you need something to draw on! Create a screen to be the overall canvas:
You create the screen to use by calling If you run this program now, then you’ll see a window pop up briefly and then immediately disappear as the program exits. Don’t blink or you might miss it! In the next section, you’ll focus on the main game loop to ensure that your program exits only when given the correct input. Setting Up the Game LoopEvery game from Pong to Fortnite uses a game loop to control gameplay. The game loop does four very important things:
Every cycle of the game loop is called a frame, and the quicker you can do things each cycle, the faster your game will run. Frames continue to occur until some condition to exit the game is met. In your design, there are two conditions that can end the game loop:
The first thing the game loop does is process user input to
allow the player to move around the screen. Therefore, you need some way to capture and process a variety of input. You do this using the Processing EventsKey presses, mouse movements, and even joystick movements are some of the ways in which a user can provide input. All user input results in an
event being generated. Events can happen at any time and often (but not always) originate outside the program. All events in Every event in You access the list of all active events in the queue by
calling
Let’s take a closer look at this game loop:
When you add these lines to the previous code and run it, you’ll see a window with a blank or black screen: The window won’t disappear until you press the Esc key, or otherwise trigger a Drawing on the ScreenIn the sample program, you drew on the screen using two commands:
Now you’ll learn about a third way to draw to the screen: using a Recall that a
After the screen is filled with white on line 45, a new Using .blit() and .flip()Just creating a new
The
The coordinates The reason why the image looks off-center is that
Notice the call to SpritesIn your game design, the player starts on the left, and obstacles come in from the right. You can represent all the obstacles with In programming terms, a sprite is a 2D representation of something on the screen. Essentially, it’s a picture. PlayersHere’s how you use
You first define Next, you define and initialize
Run this code. You’ll see a white rectangle at roughly the middle of the screen: What do you think would happen if you changed line 59 to
When you pass a User InputSo far, you’ve learned how to set up Earlier, you saw that Put this in your game loop right after the event handling loop. This returns a dictionary containing the keys pressed at the beginning of every frame:
Next, you write a method in
Then you can call
Now you can move your player rectangle around the screen with the arrow keys: You may notice two small problems:
To keep the player on the screen, you need to add some logic to detect if the
Here, instead of using Now let’s add some enemies! EnemiesWhat’s a game without enemies? You’ll use the techniques you’ve already learned to create a basic enemy class, then create a lot of them for your player to avoid. First, import the
Then create a new sprite class called
There are four notable differences between
So, what does Sprite GroupsAnother super useful class that Let’s see how to create sprite groups. You’ll create
two different
Here’s what that looks like in code:
When you call Now that you have an
Now, anything put into There’s just one problem… You don’t have any enemies! You could create a bunch of enemies at the beginning of the game, but the game would quickly become boring when they all left the screen a few seconds later. Instead, let’s explore how to keep a steady supply of enemies coming as the game progresses. Custom EventsThe design calls for enemies to appear at regular intervals. This means that at set intervals, you need to do two things:
You already have code that handles random events. The event loop is designed to look for random events occurring every frame and deal with them appropriately. Luckily, Let’s see how to create a custom event that’s generated every few seconds. You can create a custom event by naming it:
Next, you need to insert this new event into the event queue at regular intervals throughout the game. That’s where the Add the code to handle your new event:
Whenever the event handler sees the new However, that’s not the only reason there’s a group for just Collision DetectionYour game design calls for the game to end whenever an enemy collides with the player. Checking for collisions is a basic technique of game programming, and usually requires some non-trivial math to determine whether two sprites will overlap each other. This is where a framework like For this tutorial, you’ll use a method called
Here’s what that looks like in code:
Line 135 tests whether At this point, you’ve got the basic elements of a game in place: Now, let’s dress it up a bit, make it more playable, and add some advanced capabilities to help it stand out. Sprite ImagesAlright, you have a game, but let’s be honest… It’s kind of ugly. The player and enemies are just white blocks on a black background. That was state-of-the-art when Pong was new, but it just doesn’t cut it anymore. Let’s replace all those boring white rectangles with some cooler images that will make the game feel like an actual game. Earlier, you learned that images on disk can be loaded into a Altering the Object ConstructorsBefore you use images to represent the player and enemy sprites, you need to make some changes to their constructors. The code below replaces the code used previously:
Let’s unpack line 31 a bit. Line 32 uses Nothing else needs to change. The image is still a Here’s what similar changes to the
Running the program now should show that this is the same game you had before, except now you’ve added some nice graphics skins with images. But why stop at just making the player and enemy sprites look nice? Let’s add a few clouds going past to give the impression of a jet flying through the sky. Adding Background ImagesFor background clouds, you use the same principles as you did for
Here’s what
That should all look very familiar. It’s pretty much the same as To have clouds appear at certain intervals, you’ll use event creation code similar to what you used to create new enemies. Put it right below the enemy creation event:
This says to wait 1000 milliseconds, or one second, before creating the next Next, create a new
Next, add a handler for the new
Finally, make sure the
Line 172 updates the original Note that each new
You create multiple groups so that you can change the way sprites move or behave without impacting the movement or behavior of other sprites. Game SpeedWhile testing the game you may have noticed that the enemies move a little fast. If not, then that’s okay, as different machines will see different results at this point. The reason for this is that the game loop processes frames as fast as the processor and environment will allow. Since all the sprites move once per frame, they can move hundreds of times each second. The number of frames handled each second is called the frame rate, and getting this right is the difference between a playable game and a forgettable one. Normally, you want as high a frame rate
as possible, but for this game, you need to slow it down a bit for the game to be playable. Fortunately, the module Using
The second calls
The argument passed to Passing in a smaller frame rate will result in more time in each frame for calculations, while a larger frame rate provides smoother (and possibly faster) gameplay: Play around with this number to see what feels best for you! Sound EffectsSo far, you’ve focused on gameplay and the visual aspects of your game. Now let’s explore
giving your game some auditory flavor as well. The name As with most things
After the system is initialized, you can get your sounds and background music setup:
Lines 138 and 139 load a background sound clip and begin playing it. You can tell the sound clip to loop and never end by setting the named parameter Lines 143 to 145 load
three sounds you’ll use for various sound effects. The first two are rising and falling sounds, which are played when the player moves up or down. The last is the sound used whenever there is a collision. You can add other sounds as well, such as a sound for whenever an So, how do you use the sound effects? You want to play each sound when a certain event occurs. For example, when the ship moves up, you want to play
For a collision between the player and an enemy, you play the sound for when collisions are detected:
Here, you stop any other sound effects first, because in a collision the player is no longer moving. Then you play the collision sound and continue execution from there. Finally, when the game is over, all sounds should stop. This is true whether the game ends due to a collision or the user exits manually. To do this, add the following lines at the end of the program after the loop:
Technically, these last few lines are not required, as the program ends right after this. However, if you decide later on to add an intro screen or an exit screen to your game, then there may be more code running after the game ends. That’s it! Test it again, and you should see something like this: A Note on SourcesYou may have noticed the comment on lines 136-137 when the background music was loaded, listing the source of the music and a link to the Creative Commons license. This was done because the creator of that sound required it. The license requirements stated that in order to use the sound, both proper attribution and a link to the license must be provided. Here are some sources for music, sound, and art that you can search for useful content:
As you make your games and use downloaded content such as art, music, or code from other sources, please be sure that you are complying with the licensing terms of those sources. ConclusionThroughout this tutorial, you’ve learned how game programming with
To do this, you used a subset of the You can find all of the code, graphics, and sound files for this article by clicking the link below: Feel free to leave comments below as well. Happy Pythoning! Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Make a 2D Side-Scroller Game With PyGame How do I run the Python snake game?How To implement Snake Game in Python?. Installing Pygame.. Create the Screen.. Create the Snake.. Moving the Snake.. Game Over when Snake hits the boundaries.. Adding the Food.. Increasing the Length of the Snake.. Displaying the Score.. How do I run a Python program?To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!
Do any games run on Python?Video games
Disney's Toontown Online is written in Python and uses Panda3D for graphics. Eve Online uses Stackless Python. Mount & Blade is written in Python. Pirates of the Caribbean Online is written in Python and uses Panda3D for graphics.
|