Tag Archives: Python

Code a Spectrum-style Crazy Golf game | Wireframe #54

via Raspberry Pi

Putt the ball around irrational obstacles in our retro take on golf. Mark Vanstone has the code

First released by Mr. Micro in 1983 – then under the banner of Sinclair Research – Krazy Golf was, confusingly, also called Crazy Golf. The loading screen featured the Krazy spelling, but on the cover, it was plain old Crazy Golf.

Designed for the ZX Spectrum, the game provided nine holes and a variety of obstacles to putt the ball around. Crazy Golf was released at a time when dozens of other games were hitting the Spectrum market, and although it was released under the Sinclair name and reviewed in magazines such as Crash, it didn’t make much impact. The game itself employed a fairly rudimentary control system, whereby the player selects the angle of the shot at the top left of the screen, sets the range via a bar along the top, and then presses the RETURN key to take the shot.

The game was called Crazy Golf on the cover, but weirdly, the loading screen spelled the name as Krazy Golf. The early games industry was strange.


If you’ve been following our Source Code articles each month, you will have seen the pinball game where a ball bounces off various surfaces. In that example, we used a few shortcuts to approximate the bounce angles. Here, we’re only going to have horizontal and vertical walls, so we can use some fairly straightforward maths to calculate more precisely the new angle as the ball bounces off a surface. In the original game, the ball was limited to only 16 angles, and the ball moved at the same speed regardless of the strength of the shot. We’re going to improve on this a bit so that there’s more flexibility around the shot angle; we’ll also get the ball to start moving fast and then reduce its speed until it stops.

Horizontal or vertical obstruction?

To make this work, we need to have a way of defining whether an obstruction is horizontal or vertical, as the calculation is different for each. We’ll have a background graphic showing the course and obstacles, but we’ll also need another map to check our collisions. We need to make a collision map that just has the obstacles on it, so we need a white background; mark all the horizontal surfaces red and all the vertical surfaces blue.

As we move the ball around the screen (in much the same way as our pinball game) we check to see if it has collided with a surface by sampling the colours of the pixels from the collision map. If the pixel’s blue, we know that the ball has hit a vertical wall; if it’s red, the wall’s horizontal. We then calculate the new angle for the ball. If we mark the hole as black, then we can also test for collision with that – if the ball’s in the hole, the game ends.

The pointer’s angle is rotated using degrees, but we’ll use radians for our ball direction as it will simplify our movement and bounce calculations.

Get the code

We have our ball bouncing mechanism, so now we need our user interaction system. We’ll use the left and right arrow keys to rotate our pointer, which designates the direction of the next shot. We also need a range-setting gizmo, which will be shown as a bar at the top of the screen. We can make that grow and shrink with the up and down arrows.

Then when we press the RETURN key, we transfer the pointer angle and the range to the ball and watch it go. We ought to count each shot so that we can display a tally to the player once they’ve putted the ball into the hole. From this point, it’s a simple task to create another eight holes – and then you’ll have a full crazy golf game!

Here’s Mark’s code for a simple golf game. To get it running on your system, you’ll need to install Pygame Zero. And for the full code, head to our Github.

Get your copy of Wireframe issue 55

You can read more features like this one in Wireframe issue 54, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 54 for free in PDF format.

The post Code a Spectrum-style Crazy Golf game | Wireframe #54 appeared first on Raspberry Pi.

Code your own pinball game | Wireframe #53

via Raspberry Pi

Get flappers flapping and balls bouncing off bumpers. Mark Vanstone has the code in the new issue of Wireframe magazine, available now.

There are so many pinball video games that it’s become a genre in its own right. For the few of you who haven’t encountered pinball for some reason, it originated as an analogue arcade machine where a metal ball would be fired onto a sloping play area and bounce between obstacles. The player operates a pair of flippers by pressing buttons on each side of the machine, which will in turn ping the ball back up the play area to hit obstacles and earn points. The game ends when the ball falls through the exit at the bottom of the play area.

NES Pinball
One of the earliest pinball video games – it’s the imaginatively-named Pinball on the NES.


Recreating pinball machines for video games

Video game developers soon started trying to recreate pinball, first with fairly rudimentary graphics and physics, but with increasingly greater realism over time – if you look at Nintendo’s Pinball from 1984, then, say, Devil’s Crush on the Sega Mega Drive in 1990, and then 1992’s Pinball Dreams on PC, you can see how radically the genre evolved in just a few years. In this month’s Source Code, we’re going to put together a very simple rendition of pinball in Pygame Zero. We’re not going to use any complicated maths or physics systems, just a little algebra and trigonometry.


Let’s start with our background. We need an image which has barriers around the outside for the ball to bounce off, and a gap at the bottom for the ball to fall through. We also want some obstacles in the play area and an entrance at the side for the ball to enter when it’s first fired. In this case, we’re going to use our background as a collision map, too, so we need to design it so that all the areas that the ball can move in are black.

Pinball in Python
Here it is: your own pinball game in less than 100 lines of code.


Next, we need some flippers. These are defined as Actors with a pivot anchor position set near the larger end, and are positioned near the bottom of the play area. We detect left and right key presses and rotate the angle of the flippers by 20 degrees within a range of -30 to +30 degrees. If no key is pressed, then the flipper drops back down. With these elements in place, we have our play area and an ability for the player to defend the exit.


All we need now is a ball to go bouncing around the obstacles we’ve made. Defining the ball as an Actor, we can add a direction and a speed parameter to it. With these values set, the ball can be moved using a bit of trigonometry. Our new x-coordinate will move by the sin of the ball direction multiplied by the speed, and the new y-coordinate will move by the cos of the ball direction multiplied by speed. We need to detect collisions with objects and obstacles, so we sample four pixels around the ball to see if it’s hit anything solid. If it has, we need to make the ball bounce.

Get the code

Here’s Mark’s pinball code. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

If you wanted more realistic physics, you’d calculate the reflection angle from the surface which has been hit, but in this case, we’re going to use a shortcut which will produce a rough approximation. We work out what direction the ball is travelling in and then rotate either left or right by a quarter of a turn until the ball no longer collides with a wall. We could finesse this calculation further to create a more accurate effect, but we’ll keep it simple for this sample. Finally, we need to add some gravity. As the play area is tilted downwards, we need to increase the ball speed as it travels down and decrease it as it travels up.

All of this should give you the bare bones of a pinball game. There’s lots more you could add to increase the realism, but we’ll leave you to discover the joys of normal vectors and dot products…

Get your copy of Wireframe issue 53

You can read more features like this one in Wireframe issue 53, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 53 for free in PDF format.

The post Code your own pinball game | Wireframe #53 appeared first on Raspberry Pi.

Recreate Gradius’ rock-spewing volcanoes | Wireframe #52

via Raspberry Pi

Code an homage to Konami’s classic shoot-’em-up, Gradius. Mark Vanstone has the code in the new edition of Wireframe magazine, available now.

Released by Konami in 1985, Gradius – also known as Nemesis outside Japan – brought a new breed of power-up system to arcades. One of the keys to its success was the way the player could customise their Vic Viper fighter craft by gathering capsules, which could then be ‘spent’ on weapons, speed-ups, and shields from a bar at the bottom of the screen.

Gradius screenshot
The Gradius volcanoes spew rocks at the player just before the end-of-level boss ship arrives.

Flying rocks

A seminal side-scrolling shooter, Gradius was particularly striking thanks to the variety of its levels: a wide range of hazards were thrown at the player, including waves of aliens, natural phenomena, and boss ships with engine cores that had to be destroyed in order to progress. One of the first stage’s biggest obstacles was a pair of volcanoes that spewed deadly rocks into the air: the rocks could be shot for extra points or just avoided to get through to the next section. In this month’s Source Code, we’re going to have a look at how to recreate the volcano-style flying rock obstacle from the game.

Our sample uses Pygame Zero and the randint function from the random module to provide the variations of trajectory that we need our rocks to have. We’ll need an actor created for our spaceship and a list to hold our rock Actors. We can also make a bullet Actor so we can make the ship fire lasers and shoot the rocks. We build up the scene in layers in our draw() function with a star-speckled background, then our rocks, followed by the foreground of volcanoes, and finally the spaceship and bullets.

Dodge and shoot the rocks in our homage to the classic Gradius.

Get the ship moving

In the update() function, we need to handle moving the ship around with the cursor keys. We can use a limit() function to make sure it doesn’t go off the screen, and the SPACE bar to trigger the bullet to be fired. After that, we need to update our rocks. At the start of the game our list of rocks will be empty, so we’ll get a random number generated, and if the number is 1, we make a new rock and add it to the list. If we have more than 100 rocks in our list, some of them will have moved off the screen, so we may as well reuse them instead of making more new rocks. During each update cycle, we’ll need to run through our list of rocks and update their position. When we make a rock, we give it a speed and direction, then when it’s updated, we move the rock upwards by its speed and then reduce the speed by 0.2. This will make it fly into the air, slow down, and then fall to the ground. 

Collision detection

From this code, we can make rocks appear just behind both of the volcanoes, and they’ll fly in a random direction upwards at a random speed. We can increase or decrease the number of rocks flying about by changing the random numbers that spawn them. We should be able to fly in and out of the rocks, but we could add some collision detection to check whether the rocks hit the ship – we may also want to destroy the ship if it’s hit by a rock. In our sample, we have an alternative, ‘shielded’ state to indicate that a collision has occurred. We can also check for collisions with the bullets: if a collision’s detected, we can make the rock and the bullet disappear by moving them off-screen, at which point they’re ready to be reused.

That’s about it for this month’s sample, but there are many more elements from the original game that you could add yourself: extra weapons, more enemies, or even an area boss.

Here’s Mark’s volcanic code. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 52

You can read more features like this one in Wireframe issue 52, available directly from Raspberry Pi Press — we deliver worldwide.

Wireframe issue 52's cover

And if you’d like a handy digital version of the magazine, you can also download issue 52 for free in PDF format.

The post Recreate Gradius’ rock-spewing volcanoes | Wireframe #52 appeared first on Raspberry Pi.

Recreate Exerion’s pseudo-3D landscape | Wireframe #51

via Raspberry Pi

Swoop over mountains in our homage to Jaleco’s shooter. Mark Vanstone has the code in the latest issue of Wireframe magazine, out now.

Taking the shooting action of Galaxian from a few years earlier, Japanese developer Jaleco released Exerion in 1983. What helped Exerion stand out from other shoot-’em-ups of the period, though, was its pseudo-3D background, which used both a scrolling landscape and moving background elements to create the illusion of depth. This was quite an achievement considering the hardware of the day, and it’s still an eye-catching effect even now.


Exerion’s pseudo-3D effect helped the game stand out from the crowd of other shooters packed into arcades at the time.

Three main elements

To recreate Exerion’s scrolling in Pygame Zero, we need to break the effect down into three main elements. The first is the scrolling stripes that form the landscape’s base layer. These are followed by the elements that roll over the landscape as it scrolls down the screen. Then thirdly, there’s the player’s movement, which affects both the other two elements. Let’s start with the scrolling landscape, which is made of alternating coloured stripes. To give the sense of perspective, they start very thin on the horizon and, as they move down the screen, they grow in thickness. We can create this with a list that contains the heights of each stripe, increasing as we go through the list. Then in our draw() function, we run through the list, drawing the stripes downwards from the horizon using the heights in our list. Then we increase the height of each stripe. When the first stripe reaches a certain height, we take the last one off the end of the list and add it to the beginning, resetting its height to the smallest. 

Our homage to Exerion. You can’t tell from a static image, but the illusion of depth is amazing. Honest. 

Landscape details

The next items to code are the landscape details. These are buildings and hills that we want to move with the stripes so that it looks as though the player’s flying over them as they scroll by. We need to do this in two sections as some will be drawn behind the stripes as they’re over the horizon, while others will be in front of the stripes. We’ll give each landscape item an index which ties it to a stripe, but we’ll give items that are beyond the horizon negative indexes, and those in front, positive.

All the landscape items will start with a negative index to indicate that they all start beyond the horizon. So in the draw() function, we have an initial loop to draw all the items behind the horizon, and then while we’re drawing the stripes, we also draw the items which have the same index as the stripes, so they appear in front. Once we have these two parts, we’ll have a continuous carousel of stripes and landscape items.

Player aircraft

Now we need the player aircraft. We can move it around using the arrow keys, but we want to have the background graphics moving to give the impression of a 3D landscape: if the player moves upwards, we move the horizon down, and do the opposite if the player moves downwards. We then apply a parallax effect to the landscape items. The way we do this is by moving the items at the back a small amount in the opposite direction from the player’s movement, and as we work down through the items, they move more and more. This enhances the impression of depth. 

Once we’ve added a tilt to the aircraft as it turns, we have the makings of an Exerion clone. All that needs to be added are the aliens to shoot at – if you want to add these, then you could take the Galaxian routine from last month’s Source Code. 

Here’s Mark’s code for an Exerion-style, pseudo-3D background. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 51

You can read more features like this one in Wireframe issue 51, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 51 for free in PDF format.

The post Recreate Exerion’s pseudo-3D landscape | Wireframe #51 appeared first on Raspberry Pi.

Recreate Galaxian’s iconic attack patterns | Wireframe #50

via Raspberry Pi

Blast dive-bombing aliens in our salute to Namco’s classic. Mark Vanstone has the code

Aliens swoop down towards the player, bombing as they go. Back in 1979, this was a big step forward from Taito’s Space Invaders.

Hot on the heels of the original Space Invaders, Galaxian emerged as a rival space shooter in 1979. Released by Namco, Galaxian brought new colour and unpredictable motion to the alien enemy, who would swoop down on the defending player. Galaxian was so popular in arcades that Namco released a sequel, Galaga, two years later – that game complicated the attack patterns even more. It’s difficult to say how many ports and clones have been made of Galaxian, as there are several versions of similar games for almost every home platform.

The player’s role in Galaxian is similar to Space Invaders, in that they pilot a ship and need to destroy a fleet of aliens. With Galaxian, however, the aliens have a habit of breaking formation and swooping down towards the player’s ship, and dive-bombing it. The aim is to destroy all the enemy ships and move on to the next wave. The subsequent waves of enemies get more difficult as the player progresses. For this sample, we’re going to look at that swooping mechanic, and make the bare nuts and bolts of a Galaxian game with Pygame Zero.

Our Galaxian homage up and running in Pygame Zero.
Our homage to the classic Galaxian, with angry aliens that love to break formation.

First, Galaxian has a portrait display, so we can set the play area’s width and height to be 600 and 800 respectively. Next, we can create a scrolling backdrop of stars using a bitmap that we blit to the screen and move downwards every update. We need a second blit of the stars to fill in the space that the first one leaves as it scrolls down, and we could also have another static background image behind them, which will provide a sense of depth.

Next, we set up the player ship as an Actor, and we’ll capture the left and right arrow keys in the update() function to move the ship left and right on the screen. We can also fire off a bullet with the SPACE bar, which will travel up the screen until it hits an alien or goes off the top of the screen. As in the original Galaxian, you can only shoot one bullet at a time, so we only need one Actor for this.

The aliens are arranged in rows and move left and right across the screen together. We’ll stick to just one type of alien for this sample, but draw two rows of them. You could add extra types and any number of rows. When we create the alien Actors, we can also add a status flag, and we need to determine which side of the row they’re on as when they break formation, the two sides fly in opposite directions. In this case, there’ll be four aliens on the left of each row and four on the right. Once they’re set up in a list, we can iterate through the list on each update and move them backwards and forwards. While we’re moving our aliens, we can also check to see if they’ve collided with a bullet or the player ship. If the collision is with a bullet, the alien cycles through a few frames of an explosion using the status flag, and then, when their status reaches five, they’re no longer drawn. If the collision is with the player, then the player dies and the game’s over. We can also check a random number to see if the alien will start a bombing run; if so, we set the status to one, which will start calls to the flyAlien() function. This function checks which side the alien’s on and starts changing the alien’s angle, depending on the side. It also alters the x and y coordinates, depending on the angle. We’ve written this section in longhand for clarity, but this could be collapsed down a bit with the use of some multiplier variables for the x coordinates and the angles.

There we have it: the basics of Galaxian. Can you flesh it out into a full game?

Here’s Mark’s code for a Galaxian-style shooter with attacking groups of aliens. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, head here.

Get your copy of Wireframe issue 50

You can read more features like this one in Wireframe issue 50, available directly from Raspberry Pi Press — we deliver worldwide.

And if you’d like a handy digital version of the magazine, you can also download issue 50 for free in PDF format.

The post Recreate Galaxian’s iconic attack patterns | Wireframe #50 appeared first on Raspberry Pi.

Swing into action with an homage to Pitfall! | Wireframe #48

via Raspberry Pi

Grab onto ropes and swing across chasms in our Python rendition of an Atari 2600 classic. Mark Vanstone has the code

Whether it was because of the design brilliance of the game itself or because Raiders of the Lost Ark had just hit the box office, Pitfall Harry became a popular character on the Atari 2600 in 1982.

His hazardous attempts to collect treasure struck a chord with eighties gamers, and saw Pitfall!, released by Activision, sell over four million copies. A sequel, Pitfall II: The Lost Caverns quickly followed the next year, and the game was ported to several other systems, even making its way to smartphones and tablets in the 21st century.

Pitfall

Designed by David Crane, Pitfall! was released for the Atari 2600 and published by Activision in 1982

The game itself is a quest to find 32 items of treasure within a 20-minute time limit. There are a variety of hazards for Pitfall Harry to navigate around and over, including rolling logs, animals, and holes in the ground. Some of these holes can be jumped over, but some are too wide and have a convenient rope swinging from a tree to aid our explorer in getting to the other side of the screen. Harry must jump towards the rope as it moves towards him and then hang on as it swings him over the pit, releasing his grip at the other end to land safely back on firm ground.

For this code sample, we’ll concentrate on the rope swinging (and catching) mechanic. Using Pygame Zero, we can get our basic display set up quickly. In this case, we can split the background into three layers: the background, including the back of the pathway and the tree trunks, the treetops, and the front of the pathway. With these layers we can have a rope swinging with its pivot point behind the leaves of the trees, and, if Harry gets a jump wrong, it will look like he falls down the hole in the ground. The order in which we draw these to the screen is background, rope, tree-tops, Harry, and finally the front of the pathway.

Now, let’s get our rope swinging. We can create an Actor and anchor it to the centre and top of its bounding box. If we rotate it by changing the angle property of the Actor, then it will rotate at the top of the Actor rather than the mid-point. We can make the rope swing between -45 degrees and 45 degrees by increments of 1, but if we do this, we get a rather robotic sort of movement. To fix this, we add an ‘easing’ value which we can calculate using a square root to make the rope slow down as it reaches the extremes of the swing.

Our homage to the classic Pitfall! Atari game. Can you add some rolling logs and other hazards?

Our Harry character will need to be able to run backwards and forwards, so we’ll need a few frames of animation. There are several ways of coding this, but for now, we can take the x coordinate and work out which frame to display as the x value changes. If we have four frames of running animation, then we would use the %4 operator and value on the x coordinate to give us animation frames of 0, 1, 2, and 3. We use these frames for running to the right, and if he’s running to the left, we just mirror the images. We can check to see if Harry is on the ground or over the pit, and if he needs to be falling downward, we add to his y coordinate. If he’s jumping (by pressing the SPACE bar), we reduce his y coordinate.

We now need to check if Harry has reached the rope, so after a collision, we check to see if he’s connected with it, and if he has, we mark him as attached and then move him with the end of the rope until the player presses the SPACE bar and he can jump off at the other side. If he’s swung far enough, he should land safely and not fall down the pit. If he falls, then the player can have another go by pressing the SPACE bar to reset Harry back to the start.

That should get Pitfall Harry over one particular obstacle, but the original game had several other challenges to tackle – we’ll leave you to add those for yourselves.

Pitfall Python code

Here’s Mark’s code for a Pitfall!-style platformer. To get it working on your system, you’ll need to  install Pygame Zero.  And to download the full code and assets, head here.

Get your copy of Wireframe issue 48

You can read more features like this one in Wireframe issue 48, available directly from Raspberry Pi Press — we deliver worldwide.
Wireframe issue 48
And if you’d like a handy digital version of the magazine, you can also download issue 48 for free in PDF format.
A banner with the words "Be a Pi Day donor today"

The post Swing into action with an homage to Pitfall! | Wireframe #48 appeared first on Raspberry Pi.