PyGame is a Python wrapper for the SDL library. SDL is a cross-platform library for accessing computer multimedia hardware components (sound, video, input, etc.).
- Program Arcade Games With Python And Pygame. Table of Contents. Random names.
- Just like how Python comes with several modules like random, math, or time that provide additional functions for your programs, the Pygame framework includes several.
- The title says it all. The sound effects are very quiet. This is the link to the source code for learning purposes: http:// and the.
Py. Game - a primer - Real Python. Py. Game is a Python wrapper for the SDL library. SDL is a cross- platform library for accessing computer multimedia hardware components (sound, video, input, etc.). SDL is an extremely powerful tool for building all kinds of things, but it’s written in C, and C is hard, so we use Py. Game. In this tutorial we’ll go over the basic Py. Game logic and collision detection as well as drawing to the screen and loading outside files into our game.
The following are instructions for a Windows Computer to: Install Python Install PyGame Run a PyGame Example Note: After should see the following space.
NOTE: This tutorial assumes you have a basic understanding of the Python syntax, file structure, and OOP. Setup. Navigate to the Py.
Game download page, and find the proper binary package for your operating system and version of Python. If you’re using Python 3, make sure you download version 1. Create a new . py file and input the following code: 1. As with all Python programs, we begin by importing the modules we want to use. In this case we will be importing pygame itself and pygame. The last line initializes all the Py.
Other useful packages and applications not currently available on this page. AIDA implements the Adaptive Image Deconvolution Algorithm. Alglib, a cross-platform.
Game modules, it must be called before you do anything else with Py. Game. Building Blocks. Screen Objects. First things first: We need something to draw on, so we will create a “screen” which will be our overall canvas. In order to create a screen to display on, we call the set_mode() method of pygame.
If you run this now you’ll see our window pop up briefly and then immediately disappear as the program exits. Not very impressive, is it? In the next section we will introduce our main game loop to ensure that our program only exits when we give it the correct input. Game Loop. The main game/event loop is where all the action happens.
It runs continuously during gameplay, updating the game state, rendering the screen, and collecting input. When we create our loop we need to make sure that we have a way to get out of the loop and exit the application. To that end we will introduce some basic user input at the same time.
All user input (and some other events we will get into later) go into the Py. Game event queue, which you can access by calling pygame.
This will return a list of all the events in the queue, which we will loop through and respond to according to the type of event. For now all we care about are KEYDOWN and QUIT events: 1.
Variable to keep our main loop runningrunning=True# Our main loop! Check for KEYDOWN event; KEYDOWN is a constant defined in pygame. KEYDOWN: # If the Esc key has been pressed set running to false to exit the main loopifevent. K_ESCAPE: running=False# Check for QUIT event; if QUIT, set running to falseelifevent. QUIT: running=False.
Add these lines to the previous code and run it. You should see an empty window.
It wont go away until you press the ESC key or trigger a QUIT event by closing the window. Surfaces and Rects. Surfaces and Rects are basic building blocks in Py. Game. Think of surfaces as a blank sheet of paper that you can draw whatever you want onto. Our screen object is also a Surface.
They can hold images as well. Rects are a representation of a rectangular area that your Surface encompasses.
Let’s create a basic Surface that’s 5. Surface with a color. We’ll use white because the default window background is black and we want it to be nice and visible. We’ll then call the get_rect() method on our Surface to get the rectangular area and the x, y coordinates of our surface: 1.
Create the surface and pass in a tuple with its length and widthsurf=pygame. Surface((5. 0,5. 0))# Give the surface a color to differentiate it from the backgroundsurf.
Blit and Flip. Just creating our Surface isn’t actually enough to see it on the screen. To do that we need to Blit the Surface onto another Surface. Blit is just a technical way to say draw. You can only Blit from one Surface object to another – but remember, our screen is just another Surface object.
Here’s how we’ll draw our surf to the screen: 1. This line says "Draw surf onto screen at coordinates x: 4. The Surface to draw and the location to draw it at on the source Surface. Here we use the exact center of the screen, but when you run the code you’ll notice our surf does not end up centered on the screen. This is because blit() will draw surf starting at the top left position. Notice the call to pygame.
Blit. Flip will update the entire screen with everything that has been drawn since the last flip. Without a call to flip(), nothing will show. Sprites. What are Sprites? In programming terms a Sprite is a 2d representation of something on the screen. Essentially, a Sprite is a picture. Pygame provides a basic class called Sprite, which is meant to be extended and used to hold one or several graphical representations of an object that you want to display on the screen. We will extend the Sprite class so that we can use its built in methods.
We’ll call this new object Player. Player will extend Sprite and have only two properties for now: surf and rect.
We will also give surf a color (white in this case) just like the previous surface example except that now the Surface belongs to the Player: 1. Player(pygame. sprite. Sprite): def__init__(self): super(Player,self).__init__()self. Surface((7. 5,2. 5))self. Let’s put it all together! Define our player object and call super to give it all the properties and methods of pygame. Sprite# The surface we draw on the screen is now a property of 'player'class.
Player(pygame. sprite. Sprite): def__init__(self): super(Player,self).__init__()self. Surface((7. 5,2. 5))self. Player()# Variable to keep our main loop runningrunning=True# Our main loop!
Check for KEYDOWN event; KEYDOWN is a constant defined in pygame. KEYDOWN: # If the Esc key has been pressed set running to false to exit the main loopifevent. K_ESCAPE: running=False# Check for QUIT event; if QUIT, set running to falseelifevent.
QUIT: running=False# Draw the player to the screenscreen. Update the displaypygame.
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 screen. Once changed, try printing player. The first two attributes of the rect() are x, y coordinates of the top left corner of the rect().
When you pass Blit a Rect, it will use those coordinates to draw the surface. We will use this later to make our player move! User Input. Here’s where the fun starts! Let’s make our player controllable.
We discussed earlier that the keydown event pygame. Well, Pygame has another event method called pygame. The get_pressed() method returns a dictionary with all the keydown events in the queue. We will put this in our main loop so we get the keys at every frame. Now we’ll write a method that will take that dictionary and define the behavior of the sprite based off the keys that are pressed.
Here’s what it might look like: 1. K_UP]: self. rect. K_DOWN]: self. rect. K_LEFT]: self. rect. K_RIGHT]: self. rect.
K_UP, K_DOWN, K_LEFT, and K_RIGHT correspond to the arrow keys on the keyboard. So we check that key, and if it’s set to True, then we move our rect() in the relevant direction. Rects have two built- in methods for moving; here we use “move in place” – move_ip() – because we want to move the existing Rect without making a copy. Add the above method to our Player class and put the get_pressed() call in the main loop. Our code should now look like this: 1. Player(pygame. sprite. Sprite): def__init__(self): super(Player,self).__init__()self.
Surface((7. 5,2. 5))self. K_UP]: self. rect. K_DOWN]: self. rect. K_LEFT]: self. rect. K_RIGHT]: self. rect. Player()running=Truewhilerunning: foreventinpygame. KEYDOWN: ifevent.
K_ESCAPE: running=Falseelifevent. QUIT: running=Falsepressed_keys=pygame. Now you should be able to move your rectangle around the screen with the arrow keys. You may notice though that you can move off the screen, which is something we probably don’t want.
So let’s add a bit of logic to the update method that tests if the rectangle’s coordinates have moved beyond our 8. K_UP]: self. rect. K_DOWN]: self. rect. K_LEFT]: self. rect.
K_RIGHT]: self. rect. Keep player on the screenifself.
Here instead of using a move method, we just alter the corresponding coordinates for top, bottom, left, or right. Now let’s add some enemies! First let’s create a new sprite class called ‘Enemy’. We will follow the same formula we used for the player class: 1. Enemy(pygame. sprite. Sprite): def__init__(self): super(Enemy,self).__init__()self. Surface((2. 0,1. 0))self.
There are a couple differences here that we should talk about. First off, when we call get_rect() on our surface, we are setting the center property x coordinate to 8. Random is a python library that we will import at the beginning of our file in the complete code (import random).
Why the random number? Simple: We want our incoming enemies to start past the right side of the screen (8. We also use random to set a speed property for the enemies. This way we will have some enemies that are fast and some that are slow.
Our update() method for the enemies takes no arguments (we don’t care about input for enemies) and simply moves the enemy toward the left side of the screen at a rate of speed. And the last if statement in the update method tests to see if the enemy has gone past the left side of the screen with the right side of its rectangle (so that they don’t just disappear as soon as they touch the side of the screen). When they pass the side of the screen we call Sprites’ built- in kill() method to delete them from their sprite group thereby preventing them from being rendered. Kill does not release the memory taken by the enemy and relies on you no longer having a reference to it so the Python garbage collector will take care of it. Groups. Another super useful object that Py. Game provides are Sprite groups.
They are exactly what they sound like – Groups of Sprites. So why do we use Sprite Groups instead of a list?
Well, sprite groups have several methods built into them that will help us later with collisions and updating. Let’s make a Group right now that will hold all the Sprites in our game.
Notes for hacking, developing, and modifying pygame. Building pygame. See the wiki page: Compilation to figure out how to compile pygame on different platforms. Keeping up with developments. Try and discuss changes on the mailing list. Especially if you plan to do a big change, let other people know about it on the mailing list.
Most developers are not on irc all of the time - and some never. So if you need a more realtime chat try and organise a time on the mailing list. Email lets people communicate in their own time zones. The svn wiki page has links to various tools..
So you can read the commit logs. Commit logs are important to keep them short, and also to summarise the changes you have made. Buildbots, pygame compiled on every change. There is a pygame github mirror of the bitbucket, which is updated every time there is a commit to master.
The set up more buildbots issue tracks developments in the buildbots. Links to individual buildbot pages. Generating docs. python makeref. The makeref. py program runs Sphinx to generate HTML docs and src/docs/{module}_doc. C headers from re. Structured. Text source.
The re. Structured. Text . rst files are stored in the re. ST/source and re. ST/source/ref directories. An online re. Structured.
Text primer can be found at the Python site. Sphinx specific markup is described in the. Sphinx Documentation.
The Python Sphinx package itself depends on Docutils, Jinja. Pygments. For Python 2. Sphinx will also grab and install its dependencies. Sphinx can be downloaded from Py. Pi or using easy- install. For Python 3. x only the latest repository versions work.
Be sure to install Sphinx last so it does not grab the wrong dependency versions. Jinja. 2==dev. hg clone http: //bitbucket.
Running tests. To run the tests from the test subdirectory in the Pygame distibution. To run the tests from the pygame.
In either case the - -help command line option will give usage instructions. Code style. Try and follow the code style of the particular file you are editing. Use 4 spaces instead of tabs, and Pep- 8 generally. Make sure your editor doesn't insert tabs. Try to keep things under 8.
Try not to mix in white space commits with other code commits. This makes reading diffs easier if you separate the whitespace updates from the actual changes. Writing tests. Tests are in the test/ directory. Please see test/README. A naming convention is used for all tests. So from the name of a module, class, method, or function, you can find the tests for it. Each module has a test file. eg.
In that file there are methods for each of the classes, functions and methods. So Surface. blit has a 'test_blit' method. There can be multiple test methods for each method. Surface. blit. Add extra words at the end of the method name to make multiple tests for the same method. Methods named with todo at the front "todo_blit" are methods that need to be written. Or finished. By default all of the todo tests are skipped by the test runner. You can however, make the todo_ tests fail - to see how many more tests need to be finished. Tests can use tags in order to organise them. There are optionally [modulename]_tags.
A test/surface_tags. You can use tags to skip tests on different platforms, or to choose different tests to exclude or run. There are some test related tools + code in test/util/ . To see if anything in a module is not documented.. To generate some test stubs for your unittests from an existing file..