Tag Archives: retro games

Code Gauntlet’s four-player co-op mode | Wireframe #39

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-gauntlets-four-player-co-op-mode-wireframe-39/

Four players dungeon crawling at once? Mark Vanstone shows you how to recreate Gauntlet’s co-op mode in Python and Pygame Zero.

Players collected items while battling their way through dungeons. Shooting food was a definite faux pas.

Atari’s Gauntlet was an eye-catching game, not least because it allowed four people to explore its dungeons together. Each player could choose one of four characters, each with its own abilities – there was a warrior, a Valkyrie, a wizard, and an elf – and surviving each dungeon required slaughtering enemies and the constant gathering of food, potions, and keys that unlocked doors and exits.

Designed by Ed Logg, and loosely based on the tabletop RPG Dungeons & Dragons, as well as John Palevich’s 1983 dungeon crawler, Dandy, Gauntlet was a big success. It was ported to most of the popular home systems at the time, and Atari released a sequel arcade machine, Gauntlet II, in 1986.

Atari’s original arcade machine featured four joysticks, but our example will mix keyboard controls and gamepad inputs. Before we deal with the movement, we’ll need some characters and dungeon graphics. For this example, we can make our dungeon from a large bitmap image and use a collision map to prevent our characters from clipping through walls. We’ll also need graphics for the characters moving in eight different directions. Each direction has three frames of walking animation, which makes a total of 24 frames per character. We can use a Pygame Zero Actor object for each character and add a few extra properties to keep track of direction and the current animation frame. If we put the character Actors in a list, we can loop through the list to check for collisions, move the player, or draw them to the screen.

We now test input devices for movement controls using the built-in Pygame keyboard object to test if keys are pressed. For example, keyboard.left will return True if the left arrow key is being held down. We can use the arrow keys for one player and the WASD keys for the other keyboard player. If we register x and y movements separately, then if two keys are pressed – for example, up and left – we can read that as a diagonal movement. In this way, we can get all eight directions of movement from just four keys.

For joystick or gamepad movement, we need to import the joystick module from Pygame. This provides us with methods to count the number of joystick or gamepad devices that are attached to the computer, and then initialise them for input. When we check for input from these devices, we just need to get the x-axis value and the y- axis value and then make it into an integer. Joysticks and gamepads should return a number between -1 and 1 on each axis, so if we round that number, we will get the movement value we need.

We can work out the direction (and the image we need to use) of the character with a small lookup table of x and y values and translate that to a frame number cycling through those three frames of animation as the character walks. Then all we need to do before we move the character is check they aren’t going to collide with a wall or another character. And that’s it – we now have a four-player control system. As for adding enemy spawners, loot, and keys – well, that’s a subject for another time.

Here’s Mark’s code snippet. 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 39

You can read more features like this one in Wireframe issue 39, 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 39 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 Gauntlet’s four-player co-op mode | Wireframe #39 appeared first on Raspberry Pi.

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-robotron-2084s-twin-stick-action-wireframe-38/

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.

Code a homage to Lunar Lander | Wireframe #37

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-homage-to-lunar-lander-wireframe-37/

Shoot for the moon in our Python version of the Atari hit, Lunar Lander. Mark Vanstone has the code.

Atari’s cabinet featured a thrust control, two buttons for rotating, and an abort button in case it all went horribly wrong.

Lunar Lander

First released in 1979 by Atari, Lunar Lander was based on a concept created a decade earlier. The original 1969 game (actually called Lunar) was a text-based affair that involved controlling a landing module’s thrust to guide it safely down to the lunar surface; a later iteration, Moonlander, created a more visual iteration of the same idea on the DEC VT50 graphics terminal.

Given that it appeared at the height of the late-seventies arcade boom, though, it was Atari’s coin-op that became the most recognisable version of Lunar Lander, arriving just after the tenth anniversary of the Apollo 11 moon landing. Again, the aim of the game was to use rotation and thrust controls to guide your craft, and gently set it down on a suitably flat platform. The game required efficient control of the lander, and extra points were awarded for parking successfully on more challenging areas of the landscape.

The arcade cabinet was originally going to feature a normal joystick, but this was changed to a double stalked up-down lever providing variable levels of thrust. The player had to land the craft against the clock with a finite amount of fuel with the Altitude, Horizontal Speed, and Vertical Speed readouts at the top of the screen as a guide. Four levels of difficulty were built into the game, with adjustments to landing controls and landing areas.

Our homage to the classic Lunar Lander. Can you land without causing millions of dollars’ worth of damage?

Making the game

To write a game like Lunar Lander with Pygame Zero, we can replace the vector graphics with a nice pre-drawn static background and use that as a collision detection mechanism and altitude meter. If our background is just black where the Lander can fly and a different colour anywhere the landscape is, then we can test pixels using the Pygame function image.get_at() to see if the lander has landed. We can also test a line of pixels from the Lander down the Y-axis until we hit the landscape, which will give us the lander’s altitude.

The rotation controls of the lander are quite simple, as we can capture the left and right arrow keys and increase or decrease the rotation of the lander; however, when thrust is applied (by pressing the up arrow) things get a little more complicated. We need to remember which direction the thrust came from so that the craft will continue to move in that direction even if it is rotated, so we have a direction property attached to our lander object. A little gravity is applied to the position of the lander, and then we just need a little bit of trigonometry to work out the movement of the lander based on its speed and direction of travel.

To judge if the lander has been landed safely or rammed into the lunar surface, we look at the downward speed and angle of the craft as it reaches an altitude of 1. If the speed is sufficiently slow and the angle is near vertical, then we trigger the landed message, and the game ends. If the lander reaches zero altitude without these conditions met, then we register a crash. Other elements that can be added to this sample are things like a limited fuel gauge and variable difficulty levels. You might even try adding the sounds of the rocket booster noise featured on the original arcade game.

Engage

The direction of thrust could be done in several ways. In this case, we’ve kept it simple, with one directional value which gradually moves in a new direction when an alternative thrust is applied. You may want to try making an X- and Y-axis direction calculation for thrust so that values are a combination of the two dimensions. You could also add joystick control to provide variable thrust input.

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 36

You can read more features like this one in Wireframe issue 37, 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 37 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 homage to Lunar Lander | Wireframe #37 appeared first on Raspberry Pi.

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/make-a-side-pocket-esque-pool-game-wireframe-36/

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-hyper-sports-shooting-minigame-wireframe-35/

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-flappy-birds-flight-mechanic-wireframe-29/

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-homage-to-marble-madness-wireframe-34/

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.

Code a Zaxxon-style axonometric level | Wireframe #33

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-zaxxon-style-axonometric-level-wireframe-33/

Fly through the space fortress in this 3D retro forced scrolling arcade sample. Mark Vanstone has the details

A shot from Sega's arcade hit, Zaxxon

Zaxxon was the first arcade game to use an axonometric viewpoint, which made it look very different from its 2D rivals.

Zaxxon

When Zaxxon was first released by Sega in 1982, it was hailed as a breakthrough thanks to its pseudo-3D graphics. This axonometric projection ensured that Zaxxon looked unlike any other shooter around in arcades.

Graphics aside, Zaxxon offered a subtly different twist on other shooting games of the time, like Defender and Scramble; the player flew over either open space or a huge fortress, where they had to avoid obstacles of varying heights. Players could tell how high they were flying with the aid of an altimeter, and also the shadow beneath their ship (shadows were another of Zaxxon’s innovations). The aim of the game was to get to the end of each level without running out of fuel or getting shot down; if the player did this, they’d encounter an area boss called Zaxxon. Points were awarded for destroying gun turrets and fuel silos, and extra lives could be gained as the player progressed through the levels.

A shot of our Pygame version of Zaxxon

Our Zaxxon homage running in Pygame Zero: fly the spaceship through the fortress walls and obstacles with your cursor keys.

Making our level

For this code sample, we can borrow some of the techniques used in a previous Source Code article about Ant Attack (see Wireframe issue 15) since it also used an isometric display. Although the way the map display is built up is very similar, we’ll use a JSON file to store the map data. If you’ve not come across JSON before, it’s well worth learning about, as a number of web and mobile apps use it, and it can be read by Python very easily. All we need to do is load the JSON file, and Python automatically puts the data into a Python dictionary object for us to use.

In the sample, there’s a short run of map data 40 squares long with blocks for the floor, some low walls, higher walls, and a handful of fuel silos. To add more block types, just add data to the blocktypes area of the JSON file. The codes used in the map data are the index numbers of the blocktypes, so the first blocktypes is index 0, the next index 1, and so on. Our drawMap() function takes care of rendering the data into visual form and blits blocks from the top right to the bottom left of the screen. When the draw loop gets to where the ship is, it draws first the shadow and then the ship a little higher up the screen, depending on the altitude of the ship. The equation to translate the ship’s screen coordinates to a block position on the map is a bit simplistic, but in this case, it does the job well enough.

Cursor keys guide the movement of the spaceship, which is limited by the width of the map and a height of 85 pixels. There’s some extra code to display the ship if it isn’t on the map – for example, at the start, before it reaches the map area. To make the code snippet into a true Zaxxon clone, you’ll have to add some laser fire and explosions, a fuel gauge, and a scoring system, but this code sample should provide the basis you’ll need to get started.

Code for our Zaxxon homage

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 33

You can read more features like this one in Wireframe issue 33, 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 33 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 Zaxxon-style axonometric level | Wireframe #33 appeared first on Raspberry Pi.

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-kung-fu-master-style-beat-em-up-wireframe-32/

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

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/make-a-spy-hunter-style-scrolling-road-wireframe-31/

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.

Code a Boulder Dash mining game | Wireframe #30

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-boulder-dash-mining-game-wireframe-30/

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 the Classics on sale now

Post Syndicated from Eben Upton original https://www.raspberrypi.org/blog/code-the-classics-on-sale-now/

TL;DR: we made a fully automated luxury gay space communist type-in-listing book. Buy it now and get it in time for Christmas.

Code the Classics cover

Back in the dawn of time, in the late 1980s, I grew up on a diet of type-in computer game listings. From the BBC Micro User Guide, to The Micro User magazine, to the ubiquitous Usborne books: an hour or two of painstaking copying and a little imagination would provide you with an experience which wasn’t a million miles away from what you could buy on the shelves of your local computer store.

Can you believe they did “Machine Code for Beginners”?

The simple act of typing in a game helped to familiarise you with a programming language (usually a dialect of BASIC), and by making mistakes you could start to understand what other, more intentional changes might accomplish. Some of the earliest games I wrote started off as heavily modified versions of type-in listings; in fact, one of these made a sneaky reappearance on this blog last year.

Fast forward to the present day, and aside from regular appearances in our own MagPi and Wireframe magazines, type-in listings have faded from view. Commercial games, even casual ones, have become much more sophisticated, beyond what you might expect to be able to enter into a computer in a reasonable amount of time. At the same time, tools like Unity remove the need to develop every title from the ground up.

But there’s still a lot to be said for the immediacy of the type-in experience. Three years ago, we asked ourselves whether we could make a type-in game listing book for the modern era. The end result, of which we’re launching the first volume today, is Code the Classics. David Crookes and Liz Upton will take you behind the scenes of the creation of five classic arcade games, and then I’ll show you how to implement a simple Python game inspired by each one.

Cavern

Substitute Soccer

Developing retro arcade games has been a hobby of mine since those early BBC Micro days, and I spent many happy evenings developing these titles, ably assisted by Andrew Gillett and Sean Tracey. It was important to us that these games be as close as possible to the standard of modern commercial casual games. With this in mind, we invited Dan Malone, famous among many other things for his work with The Bitmap Brothers, to provide graphics, and long-time game audio pro Allister Brimble to provide music and sound effects. I’ve known Dan for nearly twenty years, and have admired Allister’s work since childhood; it was an enormous pleasure to work with them, and we took the opportunity to snag interviews with them both, which you’ll also find in the book. Here’s Dan to offer you a taster.

Meet the artist behind Code the Classics

Subscribe to our YouTube channel: http://rpf.io/ytsub Help us reach a wider audience by translating our video content: http://rpf.io/yttranslate Buy a Raspberry Pi from one of our Approved Resellers: http://rpf.io/ytproducts Find out more about the #RaspberryPi Foundation: Raspberry Pi http://rpf.io/ytrpi Code Club UK http://rpf.io/ytccuk Code Club International http://rpf.io/ytcci CoderDojo http://rpf.io/ytcd Check out our free online training courses: http://rpf.io/ytfl Find your local Raspberry Jam event: http://rpf.io/ytjam Work through our free online projects: http://rpf.io/ytprojects Do you have a question about your Raspberry Pi?

We’ve pushed the boat out on the production values for the book itself too: think of it as an object from a parallel universe where Usborne made luxury hardbound coffee-table type-in listing books rather than paperbacks.

So although, like all our books, you can download this one for free, you’ll really want a physical copy of Code the Classics to have, and to hold, and to leave on your bedside table to club intruders with.

And while the listings are rather long, and fully-commented versions are available on GitHub, perhaps you should think about spending a rainy afternoon actually typing one in.

The post Code the Classics on sale now appeared first on Raspberry Pi.

Create a turn-based combat system | Wireframe #28

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/create-a-turn-based-combat-system-wireframe-28/

Learn how to create the turn-based combat system found in games like Pokémon, Final Fantasy, and Undertale. Raspberry Pi’s Rik Cross shows you how.

With their emphasis on trading and collecting as well as turn-based combat, the Pokémon games helped bring RPG concepts to the masses.

In the late 1970s, high school student Richard Garriott made a little game called Akalabeth. Programmed in Applesoft BASIC, it helped set the template for the role-playing genre on computers. Even today, turn-based combat is still a common sight in games, with this autumn’s Pokémon Sword and Shield revolving around a battle system which sees opponents take turns to plan and execute attacks or defensive moves.

The turn-based combat system in this article is text-only, and works by allowing players to choose to defend against or attack their opponent in turn. The battle ends when only one player has some health remaining.

Each Player taking part in the battle is added to the static players list as it’s created. Players have a name, a health value (initially set to 100) and a Boolean defending value (initially set to False) to indicate whether a player is using their shield. Players also have an inputmethod attribute, which is the function used for getting player input for making various choices in the game. This function is passed to the object when created, and means that we can have human players that give their input through the keyboard, as well as computer players that make choices (in our case simply by making a random choice between the available options).

Richard Garriott’s Akalabeth laid the groundwork for Ultima, and was one of the earliest CRPGs.

A base Action class specifies an action owner and an opponent, as well as an execute() method which has no effect on the game. Subclasses of the base class override this execute() method to specify the effect the action has on the owner and/or the opponent of the action. As a basic example, two actions have been created: Defend, which sets the owner’s defending attribute to True, and Attack, which sets the owner’s defending attribute to False, and lowers the opponent’s health by a random amount depending on whether or not they are defending.

Players take turns to choose a single action to perform in the battle, starting with the human ‘Hero’ player. The choose_action() method is used to decide what to do next (in this case either attack or defend), as well as an opponent if the player has chosen to attack. A player can only be selected as an opponent if they have a health value greater than 0, and are therefore still in the game. This choose_action() method returns an Action, which is then executed using its execute() method. A few time.sleep() commands have also been thrown in here  to ramp up the suspense!

After each player has had their turn, a check is done to make sure that at least two players still have a health value greater than 0, and therefore that the battle can continue. If so, the static get_next_player() method finds the next player still in the game to take their turn in the battle, otherwise, the game ends and the winner is announced.

Our example battle can be easily extended in lots of interesting ways. The AI for choosing an action could also be made more sophisticated, by looking at opponents’ health or defending attributes before choosing an action. You could also give each action a ‘cost’, and give players a number of action ‘points’ per turn. Chosen actions would be added to a list, until all of the points have been used. These actions would then be executed one after the other, before moving on to the next player’s turn.

Here’s Rik’s code, which gets a simple turn-based combat system 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.

You can read more features like this one in Wireframe issue 28, 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 28 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 Create a turn-based combat system | Wireframe #28 appeared first on Raspberry Pi.

Code a Frogger-style road-crossing game | Wireframe #27

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-frogger-style-road-crossing-game-wireframe-27/

Guide a frog across busy roads and rivers. Mark Vanstone shows you how to code a simple remake of Konami’s arcade game, Frogger.

Konami’s original Frogger: so iconic, it even featured in a 1998 episode of Seinfeld.

Frogger

Why did the frog cross the road? Because Frogger would be a pretty boring game if it didn’t. Released in 1981 by Konami, the game appeared in assorted bars, sports halls, and arcades across the world, and became an instant hit. The concept was simple: players used the joystick to move a succession of frogs from the bottom of the screen to the top, avoiding a variety of hazards – cars, lorries, and later, the occasional crocodile. Each frog had to be safely manoeuvred to one of five alcoves within a time limit, while extra points were awarded for eating flies along the way.

Before Frogger, Konami mainly focused on churning out clones of other hit arcade games like Space Invaders and Breakout; Frogger was one of its earliest original ideas, and the simplicity of its concept saw it ported to just about every home system available at the time. (Ironically, Konami’s game would fall victim to repeated cloning by other developers.) Decades later, developers still take inspiration from it; Hipster Whale’s Crossy Road turned Frogger into an endless running game; earlier this year, Konami returned to the creative well with Frogger in Toy Town, released on Apple Arcade.

Code your own Konami Frogger

We can recreate much of Frogger’s gameplay in just a few lines of Pygame Zero code. The key elements are the frog’s movement, which use the arrow keys, vehicles that move across the screen, and floating objects – logs and turtles – moving in opposite directions. Our background graphic will provide the road, river, and grass for our frog to move over. The frog’s movement will be triggered from an on_key_down() function, and as the frog moves, we switch to a second frame with legs outstretched, reverting back to a sitting position after a short delay. We can use the inbuilt Actor properties to change the image and set the angle of rotation.

In our Frogger homage, we move the frog with the arrow keys to avoid the traffic, and jump onto the floating logs and turtles.

For all the other moving elements, we can also use Pygame Zero Actors; we just need to make an array for our cars with different graphics for the various rows, and an array for our floating objects in the same way.
In our update() function, we need to move each Actor according to which row it’s in, and when an Actor disappears off the screen, set the x coordinate so that it reappears on the opposite side.

Handling the logic of the frog moving across the road is quite easy; we just check for collision with each of the cars, and if the frog hits a car, then we have a squashed frog. The river crossing is a little more complicated. Each time the frog moves on the river, we need to make sure that it’s on a floating Actor. We therefore check to make sure that the frog is in collision with one of the floating elements, otherwise it’s game over.

There are lots of other elements you could add to the example shown here: the original arcade game provided several frogs to guide to their alcoves on the other side of the river, while crocodiles also popped up from time to time to add a bit more danger. Pygame Zero has all the tools you need to make a fully functional version of Konami’s hit.

Here’s Mark’s code, which gets a Frogger homage 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 27

You can read more features like this one in Wireframe issue 27, 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 27 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 Frogger-style road-crossing game | Wireframe #27 appeared first on Raspberry Pi.

Code a Phoenix-style mothership battle | Wireframe #26

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-a-phoenix-style-mothership-battle-wireframe-26/

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.

Make a Columns-style tile-matching game | Wireframe #25

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/make-a-columns-style-tile-matching-game-wireframe-25/

Raspberry Pi’s own Rik Cross shows you how to code your own Columns-style tile-matching puzzle game in Python and Pygame Zero.

Created by Hewlett-Packard engineer Jay Geertsen, Columns was Sega’s sparkly rival to Nintendo’s all-conquering Tetris.

Columns and tile-matching

Tile-matching games began with Tetris in 1984 and the less famous Chain Shot! the following year. The genre gradually evolved through games like Dr. Mario, Columns, Puyo Puyo, and Candy Crush Saga. Although their mechanics differ, the goals are the same: to organise a board of different-coloured tiles by moving them around until they match.

Here, I’ll show how you can create a simple tile-matching game using Python and Pygame. In it, any tile can be swapped with the tile to its right, with the aim being to make matches of three or more tiles of the same colour. Making a match causes the tiles to disappear from the board, with tiles dropping down to fill in the gaps.

At the start of a new game, a board of randomly generated tiles is created. This is made as an (initially empty) two-dimensional array, whose size is determined by the values of rows and columns. A specific tile on the board is referenced by its row and column number.

We want to start with a truly random board, but we also want to avoid having any matching tiles. Random tiles are added to each board position, therefore, but replaced if a tile is the same as the one above or to it’s left (if such a tile exists).

Our board consists of 12 rows and 8 columns of tiles. Pressing SPACE will swap the 2 selected tiles (outlined in white), and in this case, create a match of red tiles vertically.

In our game, two tiles are ‘selected’ at any one time, with the player pressing the arrow keys to change those tiles. A selected variable keeps track of the row and column of the left-most selected tile, with the other tile being one column to the right of the left-most tile. Pressing SPACE swaps the two selected tiles, checks for matches, clears any matched tiles, and fills any gaps with new tiles.

A basic ‘match-three’ algorithm would simply check whether any tiles on the board have a matching colour tile on either side, horizontally or vertically. I’ve opted for something a little more convoluted, though, as it allows us to check for matches on any length, as well as track multiple, separate matches. A currentmatch list keeps track of the (x,y) positions of a set of matching tiles. Whenever this list is empty, the next tile to check is added to the list, and this process is repeated until the next tile is a different colour.

If the currentmatch list contains three or more tiles at this point, then the list is added to the overall matches list (a list of lists of matches!) and the currentmatch list is reset. To clear matched tiles, the matched tile positions are set to None, which indicates the absence of a tile at that position. To fill the board, tiles in each column are moved down by one row whenever an empty board position is found, with a new tile being added to the top row of the board.

The code provided here is just a starting point, and there are lots of ways to develop the game, including adding a scoring system and animation to liven up your tiles.

Here’s Rik’s code, which gets a simple tile-match game 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 25

You can read more features like this one in Wireframe issue 25, 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 25 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 Columns-style tile-matching game | Wireframe #25 appeared first on Raspberry Pi.

Code your own Donkey Kong barrels | Wireframe issue 24

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-your-own-donkey-kong-barrels-wireframe-issue-24/

Replicate the physics of barrel rolling – straight out of the classic Donkey Kong. Mark Vanstone shows you how.

Released in 1981, Donkey Kong was one of the most important games in Nintendo’s history.

Nintendo’s Donkey Kong

Donkey Kong first appeared in arcades in 1981, and starred not only the titular angry ape, but also a bouncing, climbing character called Jumpman – who later went on to star in Nintendo’s little-known series of Super Mario games. Donkey Kong featured four screens per level, and the goal in each was to avoid obstacles and guide Mario (sorry, Jumpman) to the top of the screen to rescue the hapless Pauline. Partly because the game was so ferociously difficult from the beginning, Donkey Kong’s first screen is arguably the most recognisable today: Kong lobs an endless stream of barrels, which roll down a network of crooked girders and threaten to knock Jumpman flat.

Barrels in Pygame Zero

Donkey Kong may have been a relentlessly tough game, but we can recreate one of its most recognisable elements with relative ease. We can get a bit of code running with Pygame Zero – and a couple of functions borrowed from Pygame – to make barrels react to the platforms they’re on, roll down in the direction of a slope, and fall off the end onto the next platform. It’s a very simple physics simulation using an invisible bitmap to test where the platforms are and which way they’re sloping. We also have some ladders which the barrels randomly either roll past or sometimes use to descend to the next platform below.

Our Donkey Kong tribute up and running in Pygame Zero. The barrels roll down the platforms and sometimes the ladders.

Once we’ve created a barrel as an Actor, the code does three tests for its platform position on each update: one to the bottom-left of the barrel, one bottom-centre, and one bottom-right. It samples three pixels and calculates how much red is in those pixels. That tells us how much platform is under the barrel in each position. If the platform is tilted right, the number will be higher on the left, and the barrel must move to the right. If tilted left, the number will be higher on the right, and the barrel must move left. If there is no red under the centre point, the barrel is in the air and must fall downward.

There are just three frames of animation for the barrel rolling (you could add more for a smoother look): for rolling right, we increase the frame number stored with the barrel Actor; for rolling to the left, we decrease the frame number; and if the barrel’s going down a ladder, we use the front-facing images for the animation. The movement down a ladder is triggered by another test for the blue component of a pixel below the barrel. The code then chooses randomly whether to send the barrel down the ladder.

The whole routine will keep producing more barrels and moving them down the platforms until they reach the bottom. Again, this is a very simple physics system, but it demonstrates how those rolling barrels can be recreated in just a few lines of code. All we need now is a jumping player character (which could use the same invisible map to navigate up the screen) and a big ape to sit at the top throwing barrels, then you’ll have the makings of your own fully featured Donkey Kong tribute.

Here’s Mark’s code, which sets some Donkey Kong Barrels rolling about 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 24

You can read more features like this one in Wireframe issue 24, 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 24 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 your own Donkey Kong barrels | Wireframe issue 24 appeared first on Raspberry Pi.

Make a keyboard-bashing sprint game | Wireframe issue 23

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/make-a-keyboard-bashing-sprint-game-wireframe-issue-23/

Learn how to code a sprinting minigame straight out of Daley Thompson’s Decathlon with Raspberry Pi’s own Rik Cross.

Spurred on by the success of Konami’s Hyper Sports, Daley Thompson’s Decathlon featured a wealth of controller-wrecking minigames.

Daley Thompson’s Decathlon

Released in 1984, Daley Thompson’s Decathlon was a memorable entry in what’s sometimes called the ‘joystick killer’ genre: players competed in sporting events that largely consisted of frantically waggling the controller or battering the keyboard. I’ll show you how to create a sprinting game mechanic in Python and Pygame.

Python sprinting game

There are variables in the Sprinter() class to keep track of the runner’s speed and distance, as well as global constant ACCELERATION and DECELERATION values to determine the player’s changing rate of speed. These numbers are small, as they represent the number of metres per frame that the player accelerates and decelerates.

The player increases the sprinter’s speed by alternately pressing the left and right arrow keys. This input is handled by the sprinter’s isNextKeyPressed() method, which returns True if the correct key (and only the correct key) is being pressed. A lastKeyPressed variable is used to ensure that keys are pressed alternately. The player also decelerates if no key is being pressed, and this rate of deceleration should be sufficiently smaller than the acceleration to allow the player to pick up enough speed.

Press the left and right arrow keys alternately to increase the sprinter’s speed. Objects move across the screen from right to left to give the illusion of sprinter movement.

For the animation, I used a free sprite called ‘The Boy’ from gameart2d.com, and made use of a single idle image and 15 run cycle images. The sprinter starts in the idle state, but switches to the run cycle whenever its speed is greater than 0. This is achieved by using index() to find the name of the current sprinter image in the runFrames list, and setting the current image to the next image in the list (and wrapping back to the first image once the end of the list is reached). We also need the sprinter to move through images in the run cycle at a speed proportional to the sprinter’s speed. This is achieved by keeping track of the number of frames the current image has been displayed for (in a variable called timeOnCurrentFrame).

To give the illusion of movement, I’ve added objects that move past the player: there’s a finish line and three markers to regularly show the distance travelled. These objects are calculated using the sprinter’s x position on the screen along with the distance travelled. However, this means that each object is at most only 100 pixels away from the player and therefore seems to move slowly. This can be fixed by using a SCALE factor, which is the relationship between metres travelled by the sprinter and pixels on the screen. This means that objects are initially drawn way off to the right of the screen but then travel to the left and move past the sprinter more quickly.

Finally, startTime and finishTime variables are used to calculate the race time. Both values are initially set to the current time at the start of the race, with finishTime being updated as long as the distance travelled is less than 100. Using the time module, the race time can simply be calculated by finishTime - startTime.

Here’s Rik’s code, which gets a sprinting game running in Python (no pun intended). To get it working on your system, you’ll first need to install Pygame Zero. Download the code here.

Get your copy of Wireframe issue 23

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

Autonauts is coming to colonise your computers with cuteness. We find out more in Wireframe issue 23.

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 keyboard-bashing sprint game | Wireframe issue 23 appeared first on Raspberry Pi.

Create a Scramble-style scrolling landscape | Wireframe issue 22

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/create-a-scramble-style-scrolling-landscape-wireframe-issue-22/

Weave through a randomly generated landscape in Mark Vanstone’s homage to the classic arcade game Scramble.

Scramble was developed by Konami and released in arcades in 1981. Players avoid terrain and blast enemy craft.

Konami’s Scramble

In the early eighties, arcades and sports halls rang with the sound of a multitude of video games. Because home computers hadn’t yet made it into most households, the only option for the avid video gamer was to go down to their local entertainment establishment and feed the machines with ten pence pieces (which were bigger then). One of these pocket money–hungry machines was Konami’s Scramble — released in 1981, it was one of the earliest side-scrolling shooters with multiple levels.

The Scramble player’s jet aircraft flies across a randomly generated landscape (which sometimes narrows to a cave system), avoiding obstacles and enemy planes, bombing targets on the ground, and trying not to crash. As the game continues, the difficulty increases. The player aircraft can only fly forward, so once a target has been passed, there’s no turning back for a second go.

Code your own scrolling landscape

In this example code, I’ll show you a way to generate a Scramble-style scrolling landscape using Pygame Zero and a couple of additional Pygame functions. On early computers, moving a lot of data around the screen was very slow — until dedicated video hardware like the blitter chip arrived. Scrolling, however, could be achieved either by a quick shuffle of bytes to the left or right in the video memory, or in some cases, by changing the start address of the video memory, which was even quicker.

Avoid the roof and the floor with the arrow keys. Jet graphic courtesy of TheSource4Life at opengameart.org.

For our scrolling, we can use a Pygame surface the same size as the screen. To get the scrolling effect, we just call the scroll() function on the surface to shift everything left by one pixel and then draw a new pixel-wide slice of the terrain. The terrain could just be a single colour, but I’ve included a bit of maths-based RGB tinkering to make it more colourful. We can draw our terrain surface over a background image, as the SRCALPHA flag is set when we create the surface. This is also useful for detecting if the jet has hit the terrain. We can test the pixel from the surface in front of the jet: if it’s not transparent, kaboom!

The jet itself is a Pygame Zero Actor and can be moved up and down with the arrow keys. The left and right arrows increase and decrease the speed. We generate the landscape in the updateLand() and drawLand() functions, where updateLand() first decides whether the landscape is inclining or declining (and the same with the roof), making sure that the roof and floor don’t get too close, and then it scrolls everything left.

Each scroll action moves everything on the terrain surface to the left by one pixel.

The drawLand() function then draws pixels at the right-hand edge of the surface from y coordinates 0 to 600, drawing a thin sliver of roof, open space, and floor. The speed of the jet determines how many times the landscape is updated in each draw cycle, so at faster speeds, many lines of pixels are added to the right-hand side before the display updates.

The use of randint() can be changed to create a more or less jagged landscape, and the gap between roof and floor could also be adjusted for more difficulty. The original game also had enemy aircraft, which you could make with Actors, and fuel tanks on the ground, which could be created on the right-hand side as the terrain comes into view and then moved as the surface scrolls. Scramble sparked a wave of horizontal shooters, from both Konami and rival companies; this short piece of code could give you the basis for making a decent Scramble clone of your own:

Here’s Mark’s code, which gets a Scramble-style scrolling landscape 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 22

You can read more features like this one in Wireframe issue 22, available now at Tesco, WHSmith, and 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 22 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 Create a Scramble-style scrolling landscape | Wireframe issue 22 appeared first on Raspberry Pi.

Recreate Super Sprint’s top-down racing | Wireframe issue 21

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-super-sprints-top-down-racing-wireframe-issue-21/

Making player and computer-controlled cars race round a track isn’t as hard as it sounds. Mark Vanstone explains all.

The original Super Sprint arcade machine had three steering wheels and three accelerator pedals.

From Gran Trak 10 to Super Sprint

Decades before the advent of more realistic racing games such as Sega Rally or Gran Turismo, Atari produced a string of popular arcade racers, beginning with Gran Trak 10 in 1974 and gradually updated via the Sprint series, which appeared regularly through the seventies and eighties. By 1986, Atari’s Super Sprint allowed three players to compete at once, avoiding obstacles and collecting bonuses as they careened around the tracks.

The original arcade machine was controlled with steering wheels and accelerator pedals, and computer-controlled cars added to the racing challenge. Tracks were of varying complexity, with some featuring flyover sections and shortcuts, while oil slicks and tornadoes posed obstacles to avoid. If a competitor crashed really badly, a new car would be airlifted in by helicopter.

Code your own Super Sprint

So how can we make our own Super Sprint-style racing game with Pygame Zero? To keep this example code short and simple, I’ve created a simple track with a few bends. In the original game, the movement of the computer-controlled cars would have followed a set of coordinates round the track, but as computers have much more memory now, I have used a bitmap guide for the cars to follow. This method produces a much less predictable movement for the cars as they turn right and left based on the shade of the track on the guide.

Four Formula One cars race around the track. Collisions between other cars and the sides of the track are detected.

With Pygame Zero, we can write quite a short piece of code to deal with both the player car and the automated ones, but to read pixels from a position on a bitmap, we need to borrow a couple of objects directly from Pygame: we import the Pygame image and Color objects and then load our guide bitmaps. One is for the player to restrict movement to the track, and the other is for guiding the computer-controlled cars around the track.

Three bitmaps are used for the track. One’s visible, and the other two are guides for the cars.

The cars are Pygame Zero Actors, and are drawn after the main track image in the draw() function. Then all the good stuff happens in the update() function. The player’s car is controlled with the up and down arrows for speed, and the left and right arrows to change the direction of movement. We then check to see if any cars have collided with each other. If a crash has happened, we change the direction of the car and make it reverse a bit. We then test the colour of the pixel where the car is trying to move to. If the colour is black or red (the boundaries), the car turns away from the boundary.

The car steering is based on the shade of a pixel’s colour read from the guide bitmap. If it’s light, the car will turn right, if it’s dark, the car will turn left, and if it’s mid-grey, the car continues straight ahead. We could make the cars stick more closely to the centre by making them react quickly, or make them more random by adjusting the steering angle more slowly. A happy medium would be to get the cars mostly sticking to the track but being random enough to make them tricky to overtake.

Our code will need a lot of extra elements to mimic Atari’s original game, but this short snippet shows how easily you can get a top-down racing game working in Pygame Zero:

Here’s Mark’s code, which gets a Super Sprint-style racer 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 21

You can read more features like this one in Wireframe issue 21, 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 21 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 news stand pricing!

The post Recreate Super Sprint’s top-down racing | Wireframe issue 21 appeared first on Raspberry Pi.