APC Australia

Make your own games in Python

Ready to take the ultimate Python coding step? Darren Yates explains how you can create your own simple games with Pygame.

-

It’s pretty hard to escape the ‘retro-gaming’ boom at the moment — the success of the NES Classic Edition has also given light to other classic console rebuilds, such as the sub-$100 Atari Flashback series and the Sega Mega Drive retro issue you’ll find in discount retailers, all with a swag of built-in games to remind us how fun sidescroll­ers and platformer­s were back in the 1970s, ‘80s and ‘90s. The simpler 8/16-bit graphics are still as enticing as they were all those years ago and show that being popular doesn’t require a hard drive full of triangles.

The Python programmin­g language may have a diverse range of occupation­s these days, but it isn’t averse to surprising­ly good gaming, thanks to the popular Pygame module.

INTRODUCIN­G PYGAME

You can write games in any computer language, but Python’s popularity means that gaming functional­ity is pretty well advanced here. Now to be sure, you can code games in Python straight off the bat, but to make things easier, a whole bunch of multimedia modules, functions and extras have been combined into a collection called ‘Pygame’. It’s not part of the basic Python installer you download but, once installed, you can begin taking advantage of its functional­ity through an ‘import’ statement at the top of your code.

Because Python is an interpreti­ve language (meaning it runs within an interprete­r rather than being compiled into machine code prior to operation), it’s estimated to be a good order-ofmagnitud­e slower than C-based code, so Pygame uses the SDL (Simple DirectMedi­a Layer) library, which is full of fast C-code, to speed up timecritic­al components and provides links or ‘hooks’ for you to attach your Python code. The result is speed and simpler code where you need it.

INSTALLING PYGAME

Pygame runs on Windows, Linux and

Mac OS X (meaning its cross-platform), but we’ll confine ourselves to just working in the Windows domain. Even so, installing it is a bit trickier than just double-clicking on an installer file. One of the utilities included in the Python Windows distributi­on is ‘Pip’, Python’s package manager. It runs at the command prompt and we’ll use it to install Pygame.

If you haven’t already, download and install the latest Python 3.6.x for Windows from python.org. Next, we recommend you download the latest appropriat­e version of Pygame from the University of California’s Laboratory of Fluorescen­ce Dynamics, mainly because they not only house an extraordin­ary collection of Python libraries, but they also have the latest pre-built Pygame packages or ‘wheels’ ready to install (head to tinyurl.com/3dlndgh).

Beware, though, as there are different options depending on your versions of Windows (32 or 64-bit) and Python (2.7, or 3.4, 3.5 or 3.6). If you’re using the standard 32-bit Windows version of Python 3.6, at time of writing the file you needed is ‘pygame-1.9.3-cp36-cp36m-win32.whl’. These ‘.whl’ files are known in Python as ‘wheels’ and are basically a modified zip file (they’re also kind-of like ‘deb’ archives in Debian Linux if you’re coming from there).

To get Pygame into a Windows’ version of Python so it knows where to find it, the easiest way is to first copy the pygame.whl file you downloaded to Python’s Script folder (c:/users/<name>/ AppData/Local/Programs/Python/ <PythonVers­ion>/Scripts). Once you’ve done that, start a command prompt in that ‘Scripts’ subfolder (use Windows Explorer, open the folder, hold the Shift key down, right-click in the file pane and select ‘Open command window here’ from the context menu). Now in the command prompt, run the command:

pip3 install pygame-1.9.3cp36-cp36m-win32.whl

...(or your particular version of the Pygame wheel) and allow it to do the rest. You should get a ‘successful­ly installed’ message if everything has gone smoothly. If you do, you can now run a simple test in the Python Shell. Type:

import pygame

...and press Enter. If you get no error messages, congrats — Pygame is installed and ready to work. The good news also is you only have to do this process once (at least only once for each major Python release and any Pygame updates you choose to install).

WHAT CAN PYGAME DO?

Unfortunat­ely, we don’t have a hope of covering everything Pygame can do in a few short pages, but there are some pretty impressive executions to show what is possible.

Pygame has been around since 2001 and, in that time, it’s built up a pretty solid following, particular­ly for platformer­s and sidescroll­ers. One of the best I’ve seen so far is a Pygame implementa­tion of Super Mario Bros Level 1 by Justin Meister ( tinyurl.com/

pcemwbo). It’s meant for ‘educationa­l purposes only’, but if it isn’t pixelperfe­ct, if it’d have to be damn close, right down to the well-known 8-bit soundtrack.

If you look over at the pygame.org website ( pygame.org/tags/all), you’ll find a showcase of games at various stages of completion. What’s great about this is getting to look at any available source code — reading and tracing through source code is one of the best ways of growing your coding muscles and understand­ing how a language or feature works (short of starting your own work from scratch).

As we’ve said many times before, rarely is there one way something must be done, so if you’re interested in trying out Pygame and writing your own games, read Pygame source code, plus the documentat­ion and tutorials, as your way into coding. You’ll find everything over at pygame.org.

THE 2048 GAME

One of my new favourite games is 2048 (OK, so I missed the bus on this one), a cool sliding block puzzle game that’s

incredibly addictive and great for learning binary numbers. If you haven’t seen it before, I’ll apologise now for the time you’ll spend playing this addictive game. The premise is simple enough — move the tiles until you get two like-value tiles next to each other. Move them again in that plane and they merge into a single tile with the value of the two. Each move also adds another base-level ‘2’ tile to the puzzle.

Yes, it’s a clone of 1024 and you could argue even ‘Threes’, but it’s available in everything from Android to iOS, browsers, there’s even a version of the Nintendo 3DS. The original 2048 source was written by Gabriele Cirulli in Javascript, which has enabled it to now adorn webpages everywhere (you’ll find the source for his version at gabrieleci­rulli.github.io/2048). But you’ll also find a number of Python ports on the web and one I want to take a quick look at is available on GitHub by Lewis Deane ( tinyurl.com/hc3c2cl). This particular version is roughly 300 lines of code, but once you get into it, it’s not too difficult to follow. It’s actually a nice intro into the basics of Pygame and how to use it for simple games (got to crawl before you can walk).

As you can see from the pics, we’ve found a couple of small, easy modificati­ons to the code that make it a little easier to read, by changing the value label font from a thin ‘monospace’ to a larger, thicker ‘Arial Black’. You can do this by changing lines 21 and 22 from:

myfont = pygame.font. SysFont(“monospace”, 25)

scorefont = pygame.font. SysFont(“monospace, 50) ...and making them:

myfont = pygame.font. SysFont(“arial_ black”, 50)

scorefont = pygame.font. SysFont(“arial_ black”, 50)

The other change is modifying how those value labels are positioned on the tiles. The tile labels show ‘2’,‘4’, ‘8’ and so on, but as the values can span up to four digits (as in ‘2048’), the code author uses a simple offset codebranch in the printMatri­x() function to move the horizontal start position of the value labels as appropriat­e. The original settings were designed for a 25-point monospace type, but to work with our wider 50-point Arial Black font, the ‘offset’ values need to be changed from -10, -15, -20 and -25 to -10, -30, -50 and -70 in code lines 98 to 104, respective­ly, in the 2048.py file.

The overall result might not be to everyone’s taste, but I find it easier to read. In any case, that’s one of the points of learning to code — if you have an app’s source code, you can modify the thing to suit your own individual needs.

PYGAME INTRO

The 2048 game obviously doesn’t push Pygame all that hard, but it’s enough to get us started and learn the basic flow. The thing to remember is that this is still Python, so for the most part, you still control the functional code and flow of your game. You could probably do this game without Pygame, but again, it gives us a gentle intro.

What Pygame essentiall­y does in this instance is handle all of the Windows applicatio­n programmin­g interface (API) calls to display windows, labels, shapes, colours, capture keyboard key-presses and so on, allowing us to just deal with coding the actual game.

The first step is importing the Pygame module into your game, using the line: import pygame Next, you have to initialise it, using: pygame.init()

From there, you can now set up a display panel, what Pygame describes as a ‘surface’, and set the pixel size of the surface to whatever you want to work with. For the 2048 game, the codeline involved is: SURFACE = pygame.display. set_ mode((600, 700), 0, 32)

So the game area is 600 x 700 pixels, the ‘0’ indicates any additional control signals or ‘flags’ used (none) and the colour-depth is 32-bit, although these last two parameters are optional.

“That’s one of the points of learning to code — if you have the app’s source code, you can modify the thing to suit your own individual needs.”

EVENTS

From here, Pygame’s involvemen­t in 2048 is mostly monitoring actions or ‘events’. Events are triggers for further actions, for example, an event can be a key pressed (or released) on the keyboard, it can be a mouse-button, you can even create your own ‘userevents’.

Look at the 2048 code’s main() function and you’ll see that much of it is located within a while-loop. The condition for this loop is ‘True’, which means it just loops continuous­ly.

The first line within the while-loop searches the current stack of events using a for-loop: for event in pygame. event.get():

An event is recorded by Pygame and stored in an event stack. While there are no events recorded, the code flow skips the for-loop since ‘pygame.event’ is empty. But as soon as an event is logged, this for-loop is activated.

Now for each event found in the stack, we want the game to do something. In the case of 2048, that ‘something’ is moving and controllin­g the game tiles based on the direct of the keyboard arrow-key pressed. The event for a key-press is ‘KEYDOWN’ and once detected, further code then checks to see which key was pressed and performs the appropriat­e action. All of the basic code features you see in this game — for- and while-loops, if-then conditiona­ls, functions — we’ve covered in our Python Masterclas­s over the last few months, so long-time readers should be able to follow it relatively easily.

One thing I always find helpful at this point is to slowly step through the game code, particular­ly when it’s a tile slider like 2048 with discrete game steps and just mentally process what the code does each time you press a key — it’s one of the best ways I know for getting a quick understand­ing of what the code does and how it works.

From here, Pygame comes with a stack of useful functions ideally suited for platform games, particular­ly ‘sprites’, two-dimensiona­l graphical assets you can control as part of your game, plus collision-detection or being able to detect when two objects enter the same pixel space or ‘collide’. Through SDL, it can also take advantage of GPU hardware accelerati­on for extra game graphic performanc­e (although not on all platforms).

TRY IT OUT

Pygame isn’t the last word in Python gaming, but if the idea of manually developing your own sprite and tile structures and code is driving you loopy or you’re just struggling to get that game idea out from your head and into your computer, give Pygame a whirl. You’ll find all the documentat­ion at the Pygame.org website, along with a number of intro guides to get you started ( pygame.org/docs/tut/pygameIntr­o.html). There’s a neat little tutorial on that page that shows how to create a bouncing ball within a surface in just a handful of code lines.

What’s great about learning Python is that, once you get the basics under your belt, you can start moving freely between the many coding groups that build their work around this excellent coding language. So what are you waiting for?

 ??  ?? Simple ‘ Bouncing Ball’ example from Pygame.org ( tinyurl.com/h3xyr4r).
Simple ‘ Bouncing Ball’ example from Pygame.org ( tinyurl.com/h3xyr4r).
 ??  ?? Pygame installs using Python’s Pip package manager.
Pygame installs using Python’s Pip package manager.
 ??  ?? How the first three moves work in the Python version of 2048.
How the first three moves work in the Python version of 2048.
 ??  ?? One of a number of Android versions of the 2048 puzzle game.
One of a number of Android versions of the 2048 puzzle game.
 ??  ?? The popular 2048 puzzle game has been ported to Python via Pyjama.
The popular 2048 puzzle game has been ported to Python via Pyjama.
 ??  ?? We’ve added some font mods to make the Python 2048 game more visible.
We’ve added some font mods to make the Python 2048 game more visible.
 ??  ?? Low-cost bundled retro consoles are all the rage right now.
Low-cost bundled retro consoles are all the rage right now.
 ??  ?? The Nintendo Classic Mini, poster- child for budget retro- gaming.
The Nintendo Classic Mini, poster- child for budget retro- gaming.
 ??  ?? If ‘import Pygame’ creates no errors in Python Shell, you’re good to go.
If ‘import Pygame’ creates no errors in Python Shell, you’re good to go.
 ??  ?? This Pygame version of level 1 of Super Mario Bros is pretty decent.
This Pygame version of level 1 of Super Mario Bros is pretty decent.

Newspapers in English

Newspapers from Australia