Tag Archives: wireframe

Create Boing!, our Python tribute to Pong

via Raspberry Pi

Following on from yesterday’s introduction to Pong, we’re sharing Boing!, the Python-based tribute to Pong created by Eben Upton exclusively for Code the Classics. Read on to get a detailed look at the code for Boing!

You can find the download link for the Boing! code in the Code the Classics book, available now in a variety of formats. Be sure to stick with today’s blog post until the end, for a special Code the Classics offer.

From Pong to Boing!

To show how a game like Pong can be coded, we’ve created Boing! using Pygame Zero, a beginner-friendly tool for making games in Python. It’s a good starting point for learning how games work – it takes place on a single screen without any scrolling, there are only three moving objects in the game (two bats and a ball), and the artificial intelligence for the computer player can be very simple – or even non-existent, if you’re happy for the game to be multiplayer only. In this case, we have both single-player and two-player modes.

The code can be divided into three parts. First, there’s the initial startup code. We import from other Python modules so we can use their code from ours. Then we check to make sure that the player has sufficiently up-to-date versions of Python and Pygame Zero. We set the WIDTH and HEIGHT variables, which are used by Pygame Zero when creating the game window. We also create two small helper functions which are used by the code.

The next section is the largest. We create four classes: Impact, Ball, Bat, and Game. The first three classes inherit from Pygame Zero’s Actor class, which amongst other things keeps track of an object’s location in the game world, and takes care of loading and displaying sprites. Bat and Ball define the behaviour of the corresponding objects in the game, while Impact is used for an animation which is displayed briefly whenever the ball bounces off something. The Game class’s job is to create and keep track of the key game objects, such as the two bats and the ball.

Further down, we find the update and draw functions. Pygame Zero calls these each frame, and aims to maintain a frame rate of 60 frames per second. Gameplay logic, such as updating the position of an object or working out if a point has been scored, should go in update, while in draw we tell each of the Actor objects to draw itself, as well as displaying backgrounds, text, and suchlike.

Our update and draw functions make use of two global variables: state and game. At any given moment, the game can be in one of three states: the main menu, playing the game, or the game-over screen. The update and draw functions read the state variable and run only the code relevant to the current state. So if state is currently State.MENU, for example, update checks to see if the SPACE bar or the up/down arrows are pressed and updates the menu accordingly, and draw displays the menu on the screen. The technical term for this kind of system is ‘finite state machine’.

The Game class’s job is to create and keep track of the key game objects

The game variable references an instance of the Game class as described above. The __init__ (constructor) method of Game optionally receives a parameter named controls. When we create a new Game object for the main menu, we don’t provide this parameter and so the game will therefore run in attract mode – in other words, while you’re on the main menu, you’ll see two computer-controlled players playing against each other in the background. When the player chooses to start a new game, we replace the existing Game instance with a new one, initialising it with information about the controls to be used for each player – if the controls for the second player are not specified, this indicates that the player has chosen a single-player game, so the second will be computer-controlled.

Two types of movement

In Boing!, the Bat and Ball classes inherit from Pygame Zero’s Actor class, which provides a number of ways to specify an object’s position. In this game, as well as games in later chapters, we’re setting positions using the x and y attributes, which by default specify where the centre of the sprite will be on the screen. Of course, we can’t just set an object’s position at the start and be done with it – if we want it to move as the game progresses, we need to update its position each frame. In the case of a Bat, movement is very simple. Each frame, we check to see if the relevant player (which could be a human or the computer) wants to move – if they do, we either subtract or add 4 from the bat’s Y coordinate, depending on whether they want to move up or down. We also ensure that the bat does not go off the top or bottom of the screen. So, not only are we only moving along a single axis, our Y coordinate will always be an integer (i.e. a whole number). For many games, this kind of simple movement is sufficient. Even in games where an object can move along both the X and Y axes, we can often think of the movement along each axis as being separate. For example, in the next chapter’s game, Cavern, the player might be pressing the right arrow key and therefore moving along the X axis at 4 pixels per frame, while also moving along the Y axis at 10 pixels per frame due to gravity. The movement along each axis is independent of the other.

Able to move at any angle, the ball needs to move at the same speed regardless of its direction

For the Ball, things get a bit more complicated. Not only can it move at any angle, it also needs to move at the same speed regardless of its direction. Imagine the ball moving at one pixel per frame to the right. Now imagine trying to make it move at a 45° angle from that by making it move one pixel right and one pixel up per frame. That’s a longer distance, so it would be moving faster overall. That’s not great, and that’s before we’ve even started to think about movement in any possible direction.

The solution is to make use of vector mathematics and trigonometry. In the context of a 2D game, a vector is simply a pair of numbers: X and Y. There are many ways in which vectors can be used, but most commonly they represent positions or directions.

You’ll notice that the Ball class has a pair of attributes, dx and dy. Together these form a vector representing the direction in which the ball is heading. If dx and dy are 1 and 0.5, then each time the ball moves, it’ll move by one pixel on the X axis and a half a pixel on the Y axis. What does it mean to move half a pixel? When a sprite is drawn, Pygame Zero will round its position to the nearest pixel. So the end result is that our sprite will move down the screen by one pixel every other frame, and one pixel to the right every frame (Figure 1).

We still need to make sure that our object moves at a consistent speed regardless of its direction. What we need to do is ensure that our direction vector is always a ‘unit vector’ – a vector which represents a distance of one (in this case, one means one pixel, but in some games it will represent a different distance, such as one metre). Near the top of the code you’ll notice a function named normalised. This takes a pair of numbers representing a vector, uses Python’s math.hypot function to calculate the length of that vector, and then divides both the X and Y components of the vector by that length, resulting in a vector which points in the same direction but has a length of one (Figure 2).

Vector maths is a big field, and we’ve only scratched the surface here. You can find many tutorials online, and we also recommend checking out the Vector2 class in Pygame (the library on top of which Pygame Zero is built).

Try Boing!

Update Raspbian to try Boing! and other Code the Classics games on your Raspberry Pi.

The full BOING! tutorial, including challenges, further explanations, and a link to the downloadable code can be found in Code the Classics, the latest book from Raspberry Pi Press.

We’re offering £1 off Code the Classics if you order it before midnight tomorrow from the Raspberry Pi Press online store. Visit the store now, or use the discount code PONG at checkout if you make a purchase before midnight tomorrow.

As always, Code the Classics is available as a free PDF from the Wireframe website, but we highly recommend purchasing the physical book, as it’s rather lovely to look at and would make a great gift for any gaming and/or coding enthusiast.

The post Create Boing!, our Python tribute to Pong appeared first on Raspberry Pi.

Code a Kung-Fu Master style beat-’em-up | Wireframe #32

via Raspberry Pi

Punch and kick your way through a rabble of bad dudes in a simple scrolling beat-’em-up. Mark Vanstone shows you how

Although released to tie in with Jackie Chan’s Spartan X, Kung-Fu Master was originally inspired by the Bruce Lee film, Game of Death.

Kung-Fu Master

Kung-Fu Master hit arcades in 1984. Its side-scrolling action, punching and kicking through an army of knife-throwing goons, helped create the beat-’em-up genre. In fact, its designer, Takashi Nishiyama, would go on to kickstart the Street Fighter series at Capcom, and later start up the Fatal Fury franchise at SNK.

In true eighties arcade style, Kung-Fu Master distils the elements of a chop-socky action film to its essentials. Hero Thomas and his girlfriend are attacked, she’s kidnapped, and Thomas fights his way through successive levels of bad guys to rescue her. The screen scrolls from side to side, and Thomas must use his kicks and punches to get from one side of the level to the other and climb the stairs to the next floor of the building.

Our Kung-Fu Master homage features punches, kicks, and a host of goons to use them on.

Making our brawler

To recreate this classic with Pygame Zero, we’ll need quite a few frames of animation, both for the hero character and the enemies he’ll battle. For a reasonable walk cycle, we’ll need at least six frames in each direction. Any fewer than six won’t look convincing, but more frames can achieve a smoother effect. For this example, I’ve used the 3D package Poser, since it has a handy walk designer which makes generating sequences of animation much easier.

Once we have the animation frames for our characters, including a punch, kick, and any others you want to add, we need a background for the characters to walk along. The image we’re using is 2000×400 pixels, and we start the game by displaying the central part so our hero can walk either way. By detecting arrow key presses, the hero can ‘walk’ one way or the other by moving the background left and right, while cycling through the walk animation frames. Then if we detect a Q key press, we change the action string to kick; if it’s A, it’s punch. Then in our update() function, we use that action to set the Actor’s image to the indicated action frame.

Our enemy Actors will constantly walk towards the centre of the screen, and we can cycle through their walking frames the same way we do with the main hero. To give kicks and punches an effect, we put in collision checks. If the hero strikes while an enemy collides with him, we register a hit. This could be made more precise to require more skill, but once a strike’s registered, we can switch the enemy to a different status that will cause them to fall downwards and off the screen.

This sample is a starting point to demonstrate the basics of the beat-’em-up genre. With the addition of flying daggers, several levels, and a variety of bad guys, you’ll be on your way to creating a Pygame Zero version of this classic game.

The generation game

Because we’re moving the background when our hero walks left and right, we need to make sure we move our enemies with the background, otherwise they’ll look as though they’re sliding in mid-air – this also applies to any other objects that aren’t part of the background. The number of enemies can be governed in several ways: in our code, we just have a random number deciding if a new enemy will appear during each update, but we could use a predefined pattern for the enemy generation to make it a bit less random, or we use a combination of patterns and random numbers.

Here’s Mark’s code snippet, which creates a side-scrolling beat-’em-up in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code, go here.

Get your copy of Wireframe issue 32

You can read more features like this one in Wireframe issue 32, available now at Tesco, WHSmith, all good independent UK newsagents, and the Raspberry Pi Store, Cambridge.

Or you can buy Wireframe directly from Raspberry Pi Press — delivery is available worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 32 for free in PDF format.

Look how lovely and glowy it is.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Code a Kung-Fu Master style beat-’em-up | Wireframe #32 appeared first on Raspberry Pi.

Make a Spy Hunter-style scrolling road | Wireframe #31

via Raspberry Pi

Raspberry Pi’s own Mac Bowley shows you how to make the beginnings of a top-down driving game inspired by 1983’s Spy Hunter.

Spy Hunter, an arcade game from 1983

Spy Hunter was one of the very first games with both driving and shooting.

Spy Hunter

The 1983 arcade classic Spy Hunter put players at the wheel of a fictitious Interceptor vehicle and challenged them to navigate a vertically scrolling road, destroying enemy vehicles.

Here, I’ll show you how you can recreate the game’s scrolling road to use in your own driving games. The road will be created using the Rect class from Pygame, with the road built from stacked rectangles that are each two pixels high.

Making the scrolling road in Python

First, I create two lists; one to hold the pieces of road currently being drawn on screen, and another to hold a queue of pieces that will be added as the road scrolls. To create the scrolling road effect, each of the current pieces of road will need to move down the screen, while a new piece is added to the end of the list at position y = 0.

Pygame can schedule functions, which can then be called at set intervals – meaning I can scroll my road at a set frame rate. The scroll_road function will achieve this. First, I loop over each road piece, and move it down by two pixels. I then remove the first item in the queue list and append it to the end of the road. The Pygame clock is then set to call the function at intervals set by a frame_rate variable: mine is set to 1/60, meaning 60 frames per second.

Our top-down rolling road in Python

Our code snippet provides a solid basis for your own top-down driving game. All you need now are weapons. And a few other cars.

My road can either turn left or right, a random choice made whenever the queue is populated. Whichever way the road turns, it has to start from the same spot as the last piece in my queue. I can grab the last item in a list using -1 as an index and then store the x position; building from here will make sure my road is continuous. I use a buffer of 50 pixels to keep the road from moving off the edge of my screen – each time a turn is made, I check that the road doesn’t go beyond this point.

I want the turn amount to be random, so I’m also setting a minimum turn of 200 pixels. If this amount takes my car closer than the buffer, I’ll instead set the turn amount so that it takes it up to the buffer but no further. I do this for both directions, as well as setting a modifier to apply to my turn amount (-1 to turn left and 1 to turn right), which will save me duplicating my code. I also want to randomly choose how many pieces will be involved in my turn. Each piece is a step in the scroll, so the more pieces, the longer my turn will take. This will make sure I have a good mix of sharp and elongated turns in my road, keeping the player engaged.

Our rolling road Python code

Here’s Mac’s code snippet, which creates a winding road worthy of Spy Hunter in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code, go here.

Speeding up the game

To make things more exciting, the game can also be speeded up by decreasing the frame_rate variable. You could even gradually increase this over time, making the game feel more frantic the further you get.
Another improvement would be to make the turns more curvy, but make sure you’re comfortable with algebra before you do this!

Get your copy of Wireframe issue 31

You can read more features like this one in Wireframe issue 31, available now at Tesco, WHSmith, all good independent UK newsagents, and the Raspberry Pi Store, Cambridge.

Or you can buy Wireframe directly from Raspberry Pi Press — delivery is available worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 31 for free in PDF format.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Make a Spy Hunter-style scrolling road | Wireframe #31 appeared first on Raspberry Pi.

Build your own first-person shooter in Unity

via Raspberry Pi

Raspberry Pi Press is back with a new publication: this time, it’s Wireframe’s time to shine, with Build Your Own First-Person Shooter in Unity.

BUILD YOUR OWN first-person shooter game in Unity || Wireframe magazine

Ever fancied creating your own first-person shooter game? Now you can with Wireframe’s brand new, 140-page bookazine, which positively heaves with tutorials and advice from expert video game developers!

Could you build a video game?

We’ve all had that moment of asking ourselves, “I wonder if I could do this?” when playing a video game. Whether as a child racing friends in Mario Kart, or in more recent years with vast open-world masterpieces, if you like games, you’ve probably thought about designing and building your own.

So, why don’t you?

With the latest publication from Wireframe and Raspberry Pi Press, you can learn how to use Unity, free software available to download online, to create your very own first-person shooter. You could build something reminiscent of DOOM, Wolfenstein, and all the other games you tried to convince your parents you were old enough to play when you really weren’t (who knew blurry, pixelated blood could be so terrifying?).

Build Your Own First-Person Shooter in Unity

Build Your Own First-Person Shooter in Unity leads you step-by-step through the process of making the game Zombie Panic – a frenetic battle for survival inside a castle heaving with the undead.

You’ll learn how to set up and use all the free software you’ll need, make enemies that follow and attack the player, create and texture 3D character models, and design levels with locked doors and keys.

You’ll also get tips and advice from experts, allowing you to progress your game making beyond the tutorials in the book.

Get your copy now!

Build Your Own First-Person Shooter in Unity is available now from the Raspberry Pi Press online store with free worldwide shipping, from the Raspberry Pi Store in Cambridge, and as a free download from the Wireframe website.

Wait, a free download?

Yup, you read correctly. Build Your Own First-Person Shooter in Unity can be downloaded for free as a PDF from the Wireframe website. We release free PDF versions of our books and magazines on the day they’re published; it means as many people as possible can get their hands on high-quality, up-to-date information about computing, programming and making.

However, when you buy our publications, you help us produce more great content, and you support the work of the Raspberry Pi Foundation to bring computing and digital making to people all over the world. We offer a variety of subscription options, including some terrific free gifts. And we make sure our publications are printed to feel good in your hands and look good on your bookshelf.

So, buy Build Your Own First-Person Shooter in Unity if you can – thank you, you’re amazing! And if not, grab the free PDF. Whichever you choose, we hope you make an awesome game. Don’t forget to share it with us on our social media channels.

The post Build your own first-person shooter in Unity appeared first on Raspberry Pi.

Code a Boulder Dash mining game | Wireframe #30

via Raspberry Pi

Learn how to code a simple Boulder Dash homage in Python and Pygame. Mark Vanstone shows you how. 

The original Boulder Dash was marked out by some devious level design, which threatened to squash the player at every turn.

Boulder Dash

Boulder Dash first appeared in 1984 for the Commodore 64, Apple II, and the Atari 400/800. It featured an energetic gem collector called Rockford who, thanks to some rather low-resolution graphics, looked a bit like an alien. His mission was to tunnel his way through a series of caves to find gems while avoiding falling rocks dislodged by his digging. Deadly creatures also inhabited the caves which, if destroyed by dropping rocks on them, turned into gems for Rockford to collect.

The ingenious level designs were what made Boulder Dash so addictive. Gems had to be collected within a time limit to unlock the exit, but some were positioned in places that would need planning to get to, often using the physics of falling boulders to block or clear areas. Of course, the puzzles got increasingly tough as the levels progressed.

Written by Peter Liepa and Chris Gray, Boulder Dash was published by First Star Software, which still puts out new versions of the game to this day. Due to its original success, Boulder Dash was ported to all kinds of platforms, and the years since have seen no fewer than 20 new iterations of Boulder Dash, and a fair few clones, too.

Our homage to Boulder Dash running in Pygame Zero. Dig through the caves to find gems – while avoiding death from above.

Making Boulder Dash in Python

We’re going to have a look at the boulder physics aspect of the game, and make a simple level where Rockford can dig out some gems and hopefully not get flattened under an avalanche of rocks. Writing our code in Pygame Zero, we’ll automatically create an 800 by 600-size window to work with. We can make our game screen by defining a two-dimensional list, which, in this case, we will fill with soil squares and randomly position the rocks and gems.

Each location in the list matrix will have a name: either wall for the outside boundary, soil for the diggable stuff, rock for a round, moveable boulder, gem for a collectable item, and finally, rockford to symbolise our hero. We can also define an Actor for Rockford, as this will make things like switching images and tracking other properties easier.

Here’s Mark’s code, which gets an homage to Boulder Dash running in Python. To get it working on your system, you’ll first need to install Pygame Zero. And to download the full code, go here.

Our draw() function is just a nested loop to iterate through the list matrix and blit to the screen whatever is indicated in each square. The Rockford Actor is then drawn over the top. We can also keep a count of how many gems have been collected and provide a congratulatory message if all of them are found. In the update() function, there are only two things we really need to worry about: the first being to check for keypresses from the player and move Rockford accordingly, and the second to check rocks to see if they need to move.

Rockford is quite easy to test for movement, as he can only move onto an empty square – a soil square or a gem square. It’s also possible for him to push a boulder if there’s an empty space on the other side. For the boulders, we need to first test if there’s an empty space below it, and if so, the boulder must move downwards. We also test to see if a boulder is on top of another boulder – if it is, the top boulder can roll off and down onto a space either to the left or the right of the one beneath.
There’s not much to add to this snippet of code to turn it into a playable game of Boulder Dash. See if you can add a timer, some monsters, and, of course, some puzzles for players to solve on each level.

Testing for movement

An important thing to notice about the process of scanning through the list matrix to test for boulder movement is that we need to read the list from the bottom upwards; otherwise, because the boulders move downwards, we may end up testing a boulder multiple times if we test from the beginning to the end of the list. Similarly, if we read the list matrix from the top down, we may end up moving a boulder down and then when reading the next row, coming across the same one again, and moving it a second time.

Get your copy of Wireframe issue 30

You can read more features like this one in Wireframe issue 30, available now at Tesco, WHSmith, all good independent UK newsagents, and the Raspberry Pi Store, Cambridge.

Or you can buy Wireframe directly from Raspberry Pi Press — delivery is available worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 30 for free in PDF format.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Code a Boulder Dash mining game | Wireframe #30 appeared first on Raspberry Pi.

Code a Phoenix-style mothership battle | Wireframe #26

via Raspberry Pi

It was one of gaming’s first boss battles. Mark Vanstone shows you how to recreate the mothership from the 1980 arcade game, Phoenix.

Phoenix’s fifth stage offered a unique challenge in 1980: one of gaming’s first-ever boss battles.

First released in 1980, Phoenix was something of an arcade pioneer. The game was the kind of post-Space Invaders fixed-screen shooter that was ubiquitous at the time: players moved their ship from side to side, shooting at a variety of alien birds of different sizes and attack patterns. The enemies moved swiftly, and the player’s only defence was a temporary shield which could be activated when the birds swooped and strafed the lone defender. But besides all that, Phoenix had a few new ideas of its own: not only did it offer five distinct stages, but it also featured one of the earliest examples of a boss battle – its heavily armoured alien mothership, which required accurate shots to its shields before its weak spot could be exposed.

To recreate Phoenix’s boss, all we need is Pygame Zero. We can get a portrait style window with the WIDTH and HEIGHT variables and throw in some parallax stars (an improvement on the original’s static backdrop) with some blitting in the draw() function. The parallax effect is created by having a static background of stars with a second (repeated) layer of stars moving down the screen.

The mothership itself is made up of several Actor objects which move together down the screen towards the player’s spacecraft, which can be moved right and left using the mouse. There’s the main body of the mothership, in the centre is the alien that we want to shoot, and then we have two sets of moving shields.

Like the original Phoenix, our mothership boss battle has multiple shields that need to be taken out to expose the alien at the core.

In this example, rather than have all the graphics dimensions in multiples of eight (as we always did in the old days), we will make all our shield blocks 20 by 20 pixels, because computers simply don’t need to work in multiples of eight any more. The first set of shields is the purple rotating bar around the middle of the ship. This is made up of 14 Actor blocks which shift one place to the right each time they move. Every other block has a couple of portal windows which makes the rotation obvious, and when a block moves off the right-hand side, it is placed on the far left of the bar.

The second set of shields are in three yellow rows (you may want to add more), the first with 14 blocks, the second with ten blocks, and the last with four. These shield blocks are fixed in place but share a behaviour with the purple bar shields, in that when they are hit by a bullet, they change to a damaged version. There are four levels of damage before they are destroyed and the bullets can pass through. When enough shields have been destroyed for a bullet to reach the alien, the mothership is destroyed (in this version, the alien flashes).

Bullets can be fired by clicking the mouse button. Again, the original game had alien birds flying around the mothership and dive-bombing the player, making it harder to get a good shot in, but this is something you could try adding to the code yourself.

To really bring home that eighties Phoenix arcade experience, you could also add in some atmospheric shooting effects and, to round the whole thing off, have an 8-bit rendition of Beethoven’s Für Elise playing in the background.

Here’s Mark’s code, which gets a simple mothership battle running in Python. To get it working on your system, you’ll first need to install Pygame Zero. And to download the full code, go here.

Get your copy of Wireframe issue 26

You can read more features like this one in Wireframe issue 26, available now at Tesco, WHSmith, all good independent UK newsagents, and the Raspberry Pi Store, Cambridge.

Or you can buy Wireframe directly from Raspberry Pi Press — delivery is available worldwide. And if you’d like a handy digital version of the magazine, you can also download issue 26 for free in PDF format.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusive offers and giveaways. Subscribe on the Wireframe website to save up to 49% compared to newsstand pricing!

The post Code a Phoenix-style mothership battle | Wireframe #26 appeared first on Raspberry Pi.