Tag Archives: wireframe

The Raspberry Pi Press store is looking mighty fine

via Raspberry Pi

Eagle-eyed Raspberry Pi Press fans might have noticed some changes over the past few months to the look and feel of our website. Today we’re pleased to unveil a new look for the Raspberry Pi Press website and its online store.

Did you know?

Raspberry Pi Press is the publishing imprint of Raspberry Pi (Trading) Ltd, which is part of the Raspberry Pi Foundation, a UK-based charity that does loads of cool stuff with computers and computer education.

Did you also know?

Raspberry Pi Press publishes five monthly magazines: The MagPi, HackSpace Magazine, Wireframe, Custom PC, and Digital SLR Photography. It also produces a plethora of project books and gorgeous hardback beauties, such as retro gamers’ delight Code the Classics, as well as Hello World, the computing and digital making magazine for educators! Phew!

And did you also, also know?

The Raspberry Pi Press online store ships around the globe, with copies of our publications making their way to nearly every single continent on planet earth. Antarctica, we’re looking at you, kid.

It’s upgrade time!

With all this exciting work going on, it seemed only fair that Raspberry Pi Press should get itself a brand new look. We hope you’ll enjoy skimming the sparkling shelves of our online newsagents and bookshop.

Ain’t nothin’ wrong with a little tsundoku

You can pick up all the latest issues of your favourite magazines or treat yourself to a book or three, and you can also subscribe to all our publications with ease. We’ve even added a few new payment options to boot.

New delivery options

We’ve made a few changes to our shipping options, with additional choices for some regions to make sure that you can easily track your purchases and receive timely and reliable deliveries, even if you’re a long way from the Raspberry Pi Press printshop.

Customers in the UK, the EU, North America, Australia, and New Zealand won’t see any changes to delivery options. We continue to work to make sure we’re offering the best price and service we can for everyone, no matter where you are.

Have a look and see what you think!

So hop on over to the new and improved Raspberry Pi Press website to see the changes for yourself. And if you have any feedback, feel free to drop Oli and the team an email at rpipresshelp@raspberrypi.com.

The post The Raspberry Pi Press store is looking mighty fine appeared first on Raspberry Pi.

Code Robotron: 2084’s twin-stick action | Wireframe #38

via Raspberry Pi

News flash! Before we get into our Robotron: 2084 code, we have some important news to share about Wireframe: as of issue 39, the magazine will be going monthly.

The new 116-page issue will be packed with more in-depth features, more previews and reviews, and more of the guides to game development that make the magazine what it is. The change means we’ll be able to bring you new subscription offers, and generally make the magazine more sustainable in a challenging global climate.

As for existing subscribers, we’ll be emailing you all to let you know how your subscription is changing, and we’ll have some special free issues on offer as a thank you for your support.

The first monthly issue will be out on 4 June, and subsequent editions will be published on the first Thursday of every month after that. You’ll be able to order a copy online, or you’ll find it in selected supermarkets and newsagents if you’re out shopping for essentials.

We now return you to our usual programming…

Move in one direction and fire in another with this Python and Pygame re-creation of an arcade classic. Raspberry Pi’s own Mac Bowley has the code.

Robotron: 2084 is often listed on ‘best game of all time’ lists, and has been remade and re-released for numerous systems over the years.

Robotron: 2084

Released back in 1982, Robotron: 2084 popularised the concept of the twin-stick shooter. It gave players two joysticks which allowed them to move in one direction while also shooting at enemies in another. Here, I’ll show you how to recreate those controls using Python and Pygame. We don’t have access to any sticks, only a keyboard, so we’ll be using the arrow keys for movement and WASD to control the direction of fire.

The movement controls use a global variable, a few if statements, and two built-in Pygame functions: on_key_down and on_key_up. The on_key_down function is called when a key on the keyboard is pressed, so when the player presses the right arrow key, for example, I set the x direction of the player to be a positive 1. Instead of setting the movement to 1, instead, I’ll add 1 to the direction. The on_key_down function is called when a button’s released. A key being released means the player doesn’t want to travel in that direction anymore and so we should do the opposite of what we did earlier – we take away the 1 or -1 we applied in the on_key_up function.

We repeat this process for each arrow key. Moving the player in the update() function is the last part of my movement; I apply a move speed and then use a playArea rect to clamp the player’s position.

The arena background and tank sprites were created in Piskel. Separate sprites for the tank allow the turret to rotate separately from the tracks.

Turn and fire

Now for the aiming and rotating. When my player aims, I want them to set the direction the bullets will fire, which functions like the movement. The difference this time is that when a player hits an aiming key, I set the direction directly rather than adjusting the values. If my player aims up, and then releases that key, the shooting will stop. Our next challenge is changing this direction into a rotation for the turret.

Actors in Pygame can be rotated in degrees, so I have to find a way of turning a pair of x and y directions into a rotation. To do this, I use the math module’s atan2 function to find the arc tangent of two points. The function returns a result in radians, so it needs to be converted. (You’ll also notice I had to adjust mine by 90 degrees. If you want to avoid having to do this, create a sprite that faces right by default.)

To fire bullets, I’m using a flag called ‘shooting’ which, when set to True, causes my turret to turn and fire. My bullets are dictionaries; I could have used a class, but the only thing I need to keep track of is an actor and the bullet’s direction.

Here’s Mac’s code snippet, which creates a simple twin-stick shooting mechanic in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, go here.

You can look at the update function and see how I’ve implemented a fire rate for the turret as well. You can edit the update function to take a single parameter, dt, which stores the time since the last frame. By adding these up, you can trigger a bullet at precise intervals and then reset the timer.

This code is just a start – you could add enemies and maybe other player weapons to make a complete shooting experience.

Get your copy of Wireframe issue 38

You can read more features like this one in Wireframe issue 38, 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 38 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 Robotron: 2084’s twin-stick action | Wireframe #38 appeared first on Raspberry Pi.

Make a Side Pocket-esque pool game | Wireframe #36

via Raspberry Pi

Recreate the arcade pool action of Data East’s Side Pocket. Raspberry Pi’s own Mac Bowley has the code.

In the original Side Pocket, the dotted line helped the player line up shots, while additional functions on the UI showed where and how hard you were striking the cue ball.

Created by Data East in 1986, Side Pocket was an arcade pool game that challenged players to sink all the balls on the table and achieve a minimum score to progress. As the levels went on, players faced more balls in increasingly difficult locations on the table.

Here, I’ll focus on three key aspects from Side Pocket: aiming a shot, moving the balls, and handling collisions for balls and pockets. This project is great for anyone who wants to dip their toe into 2D game physics. I’m going to use the Pygame’s built-in collision system as much as possible, to keep the code readable and short wherever I can.

Making a pool game

Before thinking about aiming and moving balls, I need a table to play on. I created both a border and a play area sprite using piskelapp.com; originally, this was one sprite, and I used a rect to represent the play area (see Figure 1). Changing to two sprites and making the play area an actor made all the collisions easier to handle and made everything much easier to place.

Figure 1: Our table with separate border. You could add some detail to your own table, or even adapt a photograph to make it look even more realistic.

For the balls, I made simple 32×32 sprites in varying colours. I need to be able to keep track of some information about each ball on the table, such as its position, a sprite, movement, and whether it’s been pocketed or not – once a ball’s pocketed, it’s removed from play. Each ball will have similar functionality as well – moving and colliding with each other. The best way to do this is with a class: a blueprint for each ball that I will make copies of when I need a new ball on the table.

class Ball:
def __init__(self, image, pos):
self.actor = Actor(image, center=pos, anchor=(“center”, “center”))
self.movement = [0, 0]
self.pocketed = False

def move(self):
self.actor.x += self.movement[0]
self.actor.y += self.movement[1]
if self.pocketed == False:
if self.actor.y < playArea.top + 16 or self.actor.y > playArea.bottom-16:
self.movement[1] = -self.movement[1]
self.actor.y = clamp(self.actor.y, playArea.top+16, playArea.bottom-16)
if self.actor.x < playArea.left+16 or self.actor.x > playArea.right-16:
self.movement[0] = -self.movement[0]
self.actor.x = clamp(self.actor.x, playArea.left+16, playArea.right-16)
else:
self.actor.x += self.movement[0]
self.actor.y += self.movement[1]
self.resistance()

def resistance(self):
# Slow the ball down
self.movement[0] *= 0.95
self.movement[1] *= 0.95

if abs(self.movement[0]) + abs(self.movement[1]) < 0.4:
self.movement = [0, 0]

The best part about using a class is that I only need to make one piece of code to move a ball, and I can reuse it for every ball on the table. I’m using an array to keep track of the ball’s movement – how much it will move each frame. I also need to make sure it bounces off the sides of the play area if it hits them. I’ll use an array to hold all the balls on the table.

To start with, I need a cue ball:

balls = []
cue_ball = Ball(“cue_ball.png”, (WIDTH//2, HEIGHT//2))
balls.append(cue_ball)

Aiming the shot

In Side Pocket, players control a dotted line that shows where the cue ball will go when they take a shot. Using the joystick or arrow buttons rotated the shot and moved the line, so players could aim to get the balls in the pockets (see Figure 2). To achieve this, we have to dive into our first bit of maths, converting a rotation in degrees to a pair of x and y movements. I decided my rotation would be at 0 degrees when pointing straight up; the player can then press the right and left arrow to increase or decrease this value.

Figure 2: The dotted line shows the trajectory of the ball. Pressing the left or right arrows rotates the aim.

Pygame Zero has some built-in attributes for checking the keyboard, which I’m taking full advantage of.

shot_rotation = 270.0 # Start pointing up table
turn_speed = 1
line = [] # To hold the points on my line
line_gap = 1/12
max_line_length = 400
def update():
global shot_rotation

## Rotate your aim
if keyboard[keys.LEFT]:
shot_rotation -= 1 * turn_speed
if keyboard[keys.RIGHT]:
shot_rotation += 1 * turn_speed

# Make the rotation wrap around
if shot_rotation > 360:
shot_rotation -= 360
if shot_rotation < 0:
shot_rotation += 360

At 0 degrees, my cue ball’s movement should be 0 in the x direction and -1 in y. When the rotation is 90 degrees, my x movement would be 1 and y would be zero; anything in between should be a fraction between the two numbers. I could use a lot of ‘if-elses’ to set this, but an easier way is to use sin and cos on my angle – I sin the rotation to get my x value and cos the rotation to get the y movement.

# The in-built functions need radian
rot_radians = shot_rotation * (math.pi/180)

x = math.sin(rot_rads)
y = -math.cos(rot_rads)
if not shot:
current_x = cue_ball.actor.x
current_y = cue_ball.actor.y
length = 0
line = []
while length < max_line_length:
hit = False
if current_y < playArea.top or current_y > playArea.bottom:
y = -y
hit = True
if current_x < playArea.left or current_x > playArea.right:
x = -x
hit = True
if hit == True:
line.append((current_x-(x*line_gap), current_y-(y*line_gap)))
length += math.sqrt(((x*line_gap)**2)+((y*line_gap)**2) )
current_x += x*line_gap
current_y += y*line_gap
line.append((current_x-(x*line_gap), current_y-(y*line_gap)))

I can then use those x and y co-ordinates to create a series of points for my aiming line.

Shooting the ball

To keep things simple, I’m only going to have a single shot speed – you could improve this design by allowing players to load up a more powerful shot over time, but I won’t do that here.

shot = False
ball_speed = 30


## Inside update
## Shoot the ball with the space bar
if keyboard[keys.SPACE] and not shot:
shot = True
cue_ball.momentum = [x*ball_speed, y*ball_speed]

When the shot variable is True, I’m going to move all the balls on my table – at the beginning, this is just the cue ball – but this code will also move the other balls as well when I add them.

# Shoot the ball and move all the balls on the table
else:
shot = False
balls_pocketed = []
collisions = []
for b in range(len(balls)):
# Move each ball
balls[b].move()
if abs(balls[b].momentum[0]) + abs(balls[b].momentum[1]) > 0:
shot = True

Each time I move the balls, I check whether they still have some movement left. I made a resistance function inside the ball class that will slow them down.

Collisions

Now for the final problem: getting the balls to collide with each other and the pockets. I need to add more balls and some pocket actors to my game in order to test the collisions.

balls.append(Ball(“ball_1.png”, (WIDTH//2 - 75, HEIGHT//2)))
balls.append(Ball(“ball_2.png”, (WIDTH//2 - 150, HEIGHT//2)))

pockets = []
pockets.append(Actor(“pocket.png”, topleft=(playArea.left, playArea.top), anchor=(“left”, “top”)))
# I create one of these actors for each pocket, they are not drawn

Each ball needs to be able to collide with the others, and when that happens, the direction and speed of the balls will change. Each ball will be responsible for changing the direction of the ball it has collided with, and I add a new function to my ball class:

def collide(self, ball):
collision_normal = [ball.actor.x - self.actor.x, ball.actor.y - self.actor.y]
ball_speed = math.sqrt(collision_normal[0]**2 + collision_normal[1]**2)
self_speed = math.sqrt(self.momentum[0]**2 + self.momentum[1]**2)
if self.momentum[0] == 0 and self.momentum[1] == 0:
ball.momentum[0] = -ball.momentum[0]
ball.momentum[1] = -ball.momentum[1]
elif ball_speed > 0:
collision_normal[0] *= 1/ball_speed
collision_normal[1] *= 1/ball_speed
ball.momentum[0] = collision_normal[0] * self_speed
ball.momentum[1] = collision_normal[1] * self_speed

When a collision happens, the other ball should move in the opposite direction to the collision. This is what allows you to line-up slices and knock balls diagonally into the pockets. Unlike the collisions with the edges, I can’t just reverse the x and y movement. I need to change its direction, and then give it a part of the current ball’s speed. Above, I’m using a normal to find the direction of the collision. You can think of this as the direction to the other ball as they collide.

Our finished pool game. See if you can expand it with extra balls and maybe a scoring system.

Handling collisions

I need to add to my update loop to detect and store the collisions to be handled after each set of movement.

# Check for collisions
for other in balls:
if other != b and b.actor.colliderect(other.actor):
collisions.append((b, other))
# Did it sink in the hole?
in_pocket = b.actor.collidelistall(pockets)
if len(in_pocket) > 0 and b.pocketed == False:
if b != cue_ball:
b.movement[0] = (pockets[in_pocket[0]].x - b.actor.x) / 20
b.movement[1] = (pockets[in_pocket[0]].y - b.actor.y) / 20
b.pocket = pockets[in_pocket[0]]
balls_pocketed.append(b)
else:
b.x = WIDTH//2
b.y = HEIGHT//2

First, I use the colliderect() function to check if any of the balls collide this frame – if they do, I add them to a list. This is so I handle all the movement first and then the collisions. Otherwise, I’m changing the momentum of balls that haven’t moved yet. I detect whether a pocket was hit as well; if so, I change the momentum so that the ball heads towards the pocket and doesn’t bounce off the walls anymore.

When all my balls have been moved, I can handle the collisions with both the other balls and the pockets:

for col in collisions:
col[0].collide(col[1])
if shot == False:
for b in balls_pocketed:
balls.remove(b)

And there you have it: the beginnings of an arcade pool game in the Side Pocket tradition. You can get the full code and assets right here.

Get your copy of Wireframe issue 36

You can read more features like this one in Wireframe issue 36, 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 36 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 Side Pocket-esque pool game | Wireframe #36 appeared first on Raspberry Pi.

Code Hyper Sports’ shooting minigame | Wireframe #35

via Raspberry Pi

Gun down the clay pigeons in our re-creation of a classic minigame from Konami’s Hyper Sports. Take it away, Mark Vanstone

Hyper Sports

Hyper Sports’ Japanese release was tied in with the 1984 Summer Olympics.

Hyper Sports

Konami’s sequel to its 1983 arcade hit, Track & Field, Hyper Sports offered seven games – or events – in which up to four players could participate. Skeet shooting was perhaps the most memorable game in the collection, and required just two buttons: fire left and fire right.

The display showed two target sights, and each moved up and down to come into line with the next clay disc’s trajectory. When the disc was inside the red target square, the player pressed the fire button, and if their timing was correct, the clay disc exploded. Points were awarded for being on target, and every now and then, a parrot flew across the screen, which could be gunned down for a bonus.

Making our game

To make a skeet shooting game with Pygame Zero, we need a few graphical elements. First, a static background of hills and grass, with two clay disc throwers each side of the screen, and a semicircle where our shooter stands – this can be displayed first, every time our draw() function is called.

We can then draw our shooter (created as an Actor) in the centre near the bottom of the screen. The shooter has three images: one central while no keys are pressed, and two for the directions left and right when the player presses the left or right keys. We also need to have two square target sights to the left and right above the shooter, which we can create as Actors.

When the clay targets appear, the player uses the left and right buttons to shoot either the left or right target respectively.

To make the clay targets, we create an array to hold disc Actor objects. In our update() function we can trigger the creation of a new disc based on a random number, and once created, start an animation to move it across the screen in front of the shooter. We can add a shadow to the discs by tracking a path diagonally across the screen so that the shadow appears at the correct Y coordinate regardless of the disc’s height – this is a simple way of giving our game the illusion of depth. While we’re in the update() function, looping around our disc object list, we can calculate the distance of the disc to the nearest target sight frame, and from that, work out which is the closest.

When we’ve calculated which disc is closest to the right-hand sight, we want to move the sight towards the disc so that their paths intersect. All we need to do is take the difference of the Y coordinates, divide by two, and apply that offset to the target sight. We also do the same for the left-hand sight. If the correct key (left or right arrows) is pressed at the moment a disc crosses the path of the sight frame, we register a hit and cycle the disc through a sequence of exploding frames. We can keep a score and display this with an overlay graphic so that the player knows how well they’ve done.

And that’s it! You may want to add multiple players and perhaps a parrot bonus, but we’ll leave that up to you.

Here’s Mark’s code snippet, which creates a simple shooting game in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code and assets, go here.

Get your copy of Wireframe issue 35

You can read more features like this one in Wireframe issue 35, available now at Tesco, WHSmith, and all good independent UK newsagents.

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 35 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 Hyper Sports’ shooting minigame | Wireframe #35 appeared first on Raspberry Pi.

Recreate Flappy Bird’s flight mechanic | Wireframe #29

via Raspberry Pi

From last year’s issue 29 of Wireframe magazine: learn how to create your own version of the simple yet addictive side-scroller Flappy Bird. Raspberry Pi’s Rik Cross shows you how.

Flappy Bird: ridiculously big in 2014, at least for a while.

Flappy Bird was released by programmer Dong Nguyen in 2013, and made use of a straightforward game mechanic to create an addictive hit. Tapping the screen provided ‘lift’ to the main character, which is used strategically to navigate through a series of moving pipes. A point is scored for each pipe successfully passed. The idea proved so addictive that Nguyen eventually regretted his creation and removed it from the Google and Apple app stores. In this article, I’ll show you how to recreate this simple yet time-consuming game, using Python and Pygame Zero.

The player’s motion is very similar to that employed in a standard platformer: falling down towards the bottom of the screen under gravity. See the article, Super Mario-style jumping physics in Wireframe #7 for more on creating this type of movement. Pressing a button (in our case, the SPACE bar) gives the player some upward thrust by setting its velocity to a negative value (i.e. upwards) larger than the value of gravity acting downwards. I’ve adapted and used two different images for the sprite (made by Imaginary Perception and available on opengameart.org), so that it looks like it’s flapping its wings to generate lift and move upwards.

Pressing the SPACE bar gives the bird ‘lift’ against gravity, allowing it to navigate through moving pipes.

Sets of pipes are set equally spaced apart horizontally, and move towards the player slowly each frame of the game. These pipes are stored as two lists of rectangles, top_pipes and bottom_pipes, so that the player can attempt to fly through gaps between the top and bottom pipes. Once a pipe in the top_pipes list reaches the left side of the screen past the player’s position, a score is incremented and the top and corresponding bottom pipes are removed from their respective lists. A new set of pipes is created at the right edge of the screen, creating a continuous challenge for the player. The y-position of the gap between each newly created pair of pipes is decided randomly (between minimum and maximum limits), which is used to calculate the position and height of the new pipes.

The game stops and a ‘Game over’ message appears if the player collides with either a pipe or the ground. The collision detection in the game uses the player.colliderect() method, which checks whether two rectangles overlap. As the player sprite isn’t exactly rectangular, it means that the collision detection isn’t pixel-perfect, and improvements could be made by using a different approach. Changing the values for GRAVITY, PIPE_GAP, PIPE_SPEED, and player.flap_velocity through a process of trial and error will result in a game that has just the right amount of frustration! You could even change these values as the player’s score increases, to add another layer of challenge.

Here’s Rik’s code, which gets an homage to Flappy Bird 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.

If you’d like to read older issues of Wireframe magazine, you can find the complete back catalogue as free PDF downloads.

The latest issue of Wireframe is available in print to buy online from the Raspberry Pi Press store, with older physical issues heavily discounted too. You can also find Wireframe at local newsagents, but we should all be staying home as much as possible right now, so why not get your copy online and save yourself the trip?

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

The post Recreate Flappy Bird’s flight mechanic | Wireframe #29 appeared first on Raspberry Pi.

Code a homage to Marble Madness | Wireframe #34

via Raspberry Pi

Code the map and movement basics of the innovative marble-rolling arcade game. Mark Vanstone shows you how.

The original Marble Madness

Each of Marble Madness’ six levels got progressively harder to navigate and had to be completed within a time limit.

Marble Madness

Hitting arcades in 1984, Atari’s Marble Madness presented a rather different control mechanism than other games of the time. The original arcade cabinet provided players with a trackball controller rather than a conventional joystick, and the aim was to guide a marble through a three-dimensional course in the fastest possible time. This meant that a player could change the angle and speed of the marble as it rolled and avoid various obstacles and baddies.

During development, designer Mark Cerny had to shelve numerous ideas for Marble Madness, since the hardware just wasn’t able to achieve the level of detail and interaction he wanted. The groundbreaking 3D display was one idea that made it through to the finished game: its pre-rendered, ray-traced isometric levels.

Marble Madness was the first game to use Atari’s System 1 upgradeable hardware platform, and also boasted the first use of an FM sound chip produced by Yamaha to create its distinctive stereo music. The game was popular in arcades to start with, but interest appeared to drop off after a few months – something Cerny attributed to the fact that the game didn’t take long to play. Marble Madness’s popularity endured in the home market, though, with ports made for most computers and consoles of the time – although inevitably, most of these didn’t support the original’s trackball controls.

Our Python version of Marble Madness

In our sample level, you can control the movement of the marble using the left and right arrow keys.

Making our game

For our version of Marble Madness, we’re going to use a combination of a rendered background and a heightmap in Pygame Zero, and write some simple physics code to simulate the marble rolling over the terrain’s flats and slopes. We can produce the background graphic using a 3D modelling program such as Blender. The camera needs to be set to Orthographic to get the forced perspective look we’re after. The angle of the camera is also important, in that we need an X rotation of 54.7 degrees and a Y rotation of 45 degrees to get the lines of the terrain correct. The heightmap can be derived from an overhead view of the terrain, but you’ll probably want to draw the heights of the blocks in a drawing package such as GIMP to give you precise colour values on the map.

The ball rolling physics are calculated from the grey-shaded heightmap graphic. We’ve left a debug mode in the code; by changing the debug variable to True, you can see how the marble moves over the terrain from the overhead viewpoint of the heightmap. The player can move the marble left and right with the arrow keys – on a level surface it will gradually slow down if no keys are pressed. If the marble is on a gradient on the heightmap, it will increase speed in the direction of the gradient. If the marble hits a section of black on the heightmap, it falls out of play, and we stop the game.

That takes care of the movement of the marble in two dimensions, but now we have to translate this to the rendered background’s terrain. The way we do this is to translate the Y coordinate of the marble as if the landscape was all at the same level – we multiply it by 0.6 – and then move it down the screen according to the heightmap data, which in this case moves the marble down 1.25 pixels for each shade of colour. We can use an overlay for items the marble always rolls behind, such as the finish flag. And with that, we have the basics of a Marble Madness level.

The code you'll need to make Marble Madness

Here’s Mark’s code snippet, which creates a Marble Madness level in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code, go here.

Module Madness

We use the image module from Pygame to sample the colour of the pixel directly under the marble on the heightmap. We also take samples from the left diagonal and the right diagonal to see if there is a change of height. We are only checking for left and right movement, but this sample could be expanded to deal with the two other directions and moving up the gradients, too. Other obstacles and enemies can be added using the same heightmap translations used for the marble, and other overlay objects can be added to the overlay graphic.

Get your copy of Wireframe issue 34

You can read more features like this one in Wireframe issue 34, 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 34 for free in PDF format.

Wireframe #34

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 homage to Marble Madness | Wireframe #34 appeared first on Raspberry Pi.