All posts by Ryan Lambie

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.

Code your own 2D shooting gallery in Python | Wireframe issue 20

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-your-own-2d-shooting-gallery-in-python-wireframe-issue-20/

Raspberry Pi’s own Rik Cross shows you how to hit enemies with your mouse pointer as they move around the screen.

Duck Hunt made effective use of the NES Zapper, and made a star of its sniggering dog, who’d pop up to heckle you between stages.

Clicky Clicky Bang Bang

Shooting galleries have always been a part of gaming, from the Seeburg Ray-O-Lite in the 1930s to the light gun video games of the past 40 years. Nintendo’s Duck Hunt — played with the NES Zapper — was a popular console shooting game in the early eighties, while titles such as Time Crisis and The House of the Dead kept the genre alive in the 1990s and 2000s.

Here, I’ll show you how to use a mouse to fire bullets at moving targets. Code written to instead make use of a light gun and a CRT TV (as with Duck Hunt) would look very different. In these games, pressing the light gun’s trigger would cause the entire screen to go black and an enemy sprite to become bright white. A light sensor at the end of the gun would then check whether the gun is pointed at the white sprite, and if so, would register a hit. If more than one enemy was on the screen when the trigger was pressed, each enemy would flash white for one frame in turn, so that the gun would know which enemy had been hit.

Our simple shooting gallery in Python. You could try adding randomly spawning ducks, a scoreboard, and more.

Pygame Zero

I’ve used two Pygame Zero event hooks for dealing with mouse input. Firstly, the on_mouse_move() function updates the position of the crosshair sprite whenever the mouse is moved. The on_mouse_down() function reacts to mouse button presses, with the left button being pressed to fire a bullet (if numberofbullets > 0) and the right button to reload (setting numberofbullets to MAXBULLETS).

Each time a bullet is fired, a check is made to see whether any enemy sprites are colliding with the crosshair — a collision means that an enemy has been hit. Luckily, Pygame Zero has a colliderect() function to tell us whether the rectangular boundary around two sprites intersects.

If this helper function wasn’t available, we’d instead need to use sprites’ x and y coordinates, along with width and height data (w and h below) to check whether the two sprites intersect both horizontally and vertically. This is achieved by coding the following algorithm:

  • Is the left-hand edge of sprite 1 further left than the right-hand edge of sprite 2 (x1 < x2+w2)?
  • Is the right-hand edge of sprite 1 further right than the left-hand edge of sprite 2 (x1+w1 > x2)?
  • Is the top edge of sprite 1 higher up than the bottom edge of sprite 2 (y1 < y2+h2)?
  • Is the bottom edge of sprite 1 lower down than the top edge of sprite 2 (y1+h1 > y2)?

If the answer to the four questions above is True, then the two sprites intersect (see Figure 1). To give visual feedback, hit enemies briefly remain on the screen (in this case, 50 frames). This is achieved by setting a hit variable to True, and then decrementing a timer once this variable has been set. The enemy’s deleted when the timer reaches 0.

Figure 1: A visual representation of a collision algorithm, which checks whether two sprites intersect.

As well as showing an enemy for a short time after being hit, successful shots are also shown. A problem that needs to be overcome is how to modify an enemy sprite to show bullet holes. A hits list for each enemy stores bullet sprites, which are then drawn over enemy sprites.

Storing hits against an enemy allows us to easily stop drawing these hits once the enemy is removed. In the example code, an enemy stops moving once it has been hit.

If you don’t want this behaviour, then you’ll also need to update the position of the bullets in an enemy’s hits list to match the enemy movement pattern.

When decrementing the number of bullets, the max() function is used to ensure that the bullet count never falls below 0. The max() function returns the highest of the numbers passed to it, and as the maximum of 0 and any negative number is 0, the number of bullets always stays within range.

There are a couple of ways in which the example code could be improved. Currently, a hit is registered when the crosshair intersects with an enemy — even if they are barely touching. This means that often part of the bullet is drawn outside of the enemy sprite boundary. This could be solved by creating a clipping mask around an enemy before drawing a bullet. More visual feedback could also be given by drawing missed shots, stored in a separate list.

Here’s Rik’s code, which lets you hit enemies with your mouse pointer. To get it running 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 20

You can read more features like this one in Wireframe issue 20, 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 20 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 2D shooting gallery in Python | Wireframe issue 20 appeared first on Raspberry Pi.

Create your own arcade-style continue screen | Wireframe #19

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/create-your-own-arcade-style-continue-screen-wireframe-19/

Raspberry Pi’s Rik Cross shows you how to create game states, and rules for moving between them.

Ninja Gaiden’s dramatic continue screen. Who would be cruel enough to walk away?

The continue screen, while much less common now, was a staple feature of arcade games, providing an opportunity (for a small fee) to reanimate the game’s hero and to pick up where they left off.

Continue Screens

Games such as Tecmo’s Ninja Gaiden coin-op (known in some regions as Shadow Warriors) added jeopardy to their continue screen, in an effort to convince us to part with our money.

Often, a continue screen is one of many screens that a player may find themselves on; other possibilities being a title screen or an instruction screen. I’ll show you how you can add multiple screens to a game in a structured way, avoiding a tangle of if…else statements and variables.

A simple way of addressing this problem is to create separate update and draw functions for each of these screens, and then switch between these functions as required. Functions are ‘first-class citizens’ of the Python language, which means that they can be stored and manipulated just like any other object, such as numbers, text, and class instances. They can be stored in variables and other data types such as lists and dictionaries, and passed as parameters to (or returned from) other functions.

the continue screen of SNK’s Fantasy

SNK’s Fantasy, released in 1981, was the first arcade game to feature a continue screen.

We can take advantage of the first-class nature of Python functions by storing the functions for the current screen in variables, and then calling them in the main update() and draw() functions. In the following example, notice the difference between storing a function in a variable (by using the function name without parentheses) and calling the function (by including parentheses).

[Ed. comment: We have to use an image here because WordPress doesn’t seem to allow code indentation. We know that’s annoying because you can’t copy and paste the code, so if you know a better solution, please leave us a comment.]

The example code above calls currentupdatefunction() and currentdrawfunction(), which each store a reference to separate update() and draw() functions for the continue screen. These continue screen functions could then also include logic for changing which function is called, by updating the function reference stored in currentupdatefunction and currentdrawfunction.

This way of structuring code can be taken a step further by making use of state machines. In a state machine, a system can be in one of a (finite) number of predefined states, and rules determine the conditions under which a system can transition from one state into another.

Rules define conditions that need to be satisfied in order to move between states.

A state machine (in this case a very simplified version) can be implemented by first creating a core State() class. Each game state has its own update() and draw() methods, and a rules dictionary containing state:rule pairs – references to other state objects linked to functions for testing game conditions. As an example, the continuescreen state has two rules:

  • Transition to the gamescreen state if the SPACE key is pressed;
  • Transition to the titlescreen state if the frame timer reaches 10.

This is pulled together with a StateMachine() class, which keeps track of the current state. The state machine calls the update() and draw() methods for the current state, and checks the rules for transitioning between states. Each rule in the current state’s rules list is executed, with the state machine updating the reference to its current state if the rule function returns True. I’ve also added a frame counter that is incremented by the state machine’s update() function each time it is run. While not a necessary part of the state machine, it does allow the continue screen to count down from 10, and could have a number of other uses, such as for animating sprites.

Something else to point out is the use of lambda functions when adding rules to states. Lambda functions are small, single-expression anonymous functions that return the result of evaluating its expression when called. Lambda functions have been used in this example simply to make the code a little more concise, as there’s no benefit to naming the functions passed to addrule().

State machines have lots of other potential uses, including the modelling of player states. It’s also possible to extend the state machine in this example by adding onenter() and onexit() functions that can be called when transitioning between states.

Here’s Rik’s code, which gets a simple continue screen up and running in Python. To get it working on your system, you’ll need to install Pygame Zero. And to download the full code, visit our Github repository here.

Get your copy of Wireframe issue 19

You can read more features like this one in Wireframe issue 19, 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 19 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 your own arcade-style continue screen | Wireframe #19 appeared first on Raspberry Pi.

Recreate 3D Monster Maze’s 8-bit labyrinth | Wireframe issue 18

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-3d-monster-mazes-8-bit-labyrinth-wireframe-issue-18/

You too can recreate the techniques behind a pioneering 3D maze game in Python. Mark Vanstone explains how.

3D Monster Maze, released in 1982 by J.K. Greye software, written by Malcolm Evans.

3D Monster Maze

While 3D games have become more and more realistic, some may forget that 3D games on home computers started in the mists of time on machines like the Sinclair ZX81. One such pioneering game took pride of place in my collection of tapes, took many minutes to load, and required the 16K RAM pack expansion. That game was 3D Monster Maze — perhaps the most popular game released for the ZX81.

The game was released in 1982 by J.K. Greye Software, and written by Malcolm Evans. Although the graphics were incredibly low resolution by today’s standards, it became an instant hit. The idea of the game was to navigate around a randomly generated maze in search of the exit.

The problem was that a Tyrannosaurus rex also inhabited the maze, and would chase you down and have you for dinner if you didn’t escape quickly enough. The maze itself was made of straight corridors on a 16×18 grid, which the player would move around from one block to the next. The shape of the blocks were displayed by using the low-resolution pixels included in the ZX81’s character set, with 2×2 pixels per character on the screen.

The original ZX81 game drew its maze from chunky 2×2 pixel blocks.

Draw imaginary lines

There’s an interesting trick to recreating the original game’s 3D corridor display which, although quite limited, works well for a simplistic rendering of a maze. To do this, we need to draw imaginary lines diagonally from corner to corner in a square viewport: these are our vanishing point perspective guides. Then each corridor block in our view is half the width and half the height of the block nearer to us.

If we draw this out with lines showing the block positions, we get a view that looks like we’re looking down a long corridor with branches leading off left and right. In our Pygame Zero version of the maze, we’re going to use this wireframe as the basis for drawing our block elements. We’ll create graphics for blocks that are near the player, one block away, two, three, and four blocks away. We’ll need to view the blocks from the left-hand side, the right-hand side, and the centre.

The maze display is made by drawing diagonal lines to a central vanishing point.

Once we’ve created our block graphics, we’ll need to make some data to represent the layout of the maze. In this example, the maze is built from a 10×10 list of zeros and ones. We’ll set a starting position for the player and the direction they’re facing (0–3), then we’re all set to render a view of the maze from our player’s perspective.

The display is created from furthest away to nearest, so we look four blocks away from the player (in the direction they’re looking) and draw a block if there’s one indicated by the maze data to the left; we do the same on the right, and finally in the middle. Then we move towards the player by a block and repeat the process (with larger graphics) until we get to the block the player is on.

Each visible block is drawn from the back forward to make the player’s view of the corridors.

That’s all there is to it. To move backwards and forwards, just change the position in the grid the player’s standing on and redraw the display. To turn, change the direction the player’s looking and redraw. This technique’s obviously a little limited, and will only work with corridors viewed at 90-degree angles, but it launched a whole genre of games on home computers. It really was a big deal for many twelve-year-olds — as I was at the time — and laid the path for the vibrant, fast-moving 3D games we enjoy today.

Here’s Mark’s code, which recreates 3D Monster Maze’s network of corridors in Python. To get it running on your system, you’ll need to install Pygame Zero. And to download the full code, visit our Github repository here.

Get your copy of Wireframe issue 18

You can read more features like this one in Wireframe issue 18, 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 18 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 Recreate 3D Monster Maze’s 8-bit labyrinth | Wireframe issue 18 appeared first on Raspberry Pi.

Code your own path-following Lemmings in Python | Wireframe issue 17

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/code-your-own-path-following-lemmings-in-python-wireframe-issue-17/

Learn how to create your own obedient lemmings that follow any path put in front of them. Raspberry Pi’s own Rik Cross explains how.

The original Lemmings, first released for the Amiga, quickly spread like a virus to just about every computer and console of the day.

Lemmings

Lemmings is a puzzle-platformer, created at DMA Design, and first became available for the Amiga in 1991. The aim is to guide a number of small lemming sprites to safety, navigating traps and difficult terrain along the way. Left to their own devices, the lemmings will simply follow the path in front of them, but additional ‘special powers’ given to lemmings allow them to (among other things) dig, climb, build, and block in order to create a path to freedom (or to the next level, anyway).

Code your own lemmings

I’ll show you a simple way (using Python and Pygame) in which lemmings can be made to follow the terrain in front of them. The first step is to store the level’s terrain information, which I’ve achieved by using a two-dimensional list to store the colour of each pixel in the background ‘level’ image. In my example, I’ve used the ‘Lemcraft’ tileset by Matt Hackett (of Lost Decade Games) – taken from opengameart.org – and used the Tiled software to stitch the tiles together into a level.

The algorithm we then use can be summarised as follows: check the pixels immediately below a lemming. If the colour of those pixels isn’t the same as the background colour, then the lemming is falling. In this case, move the lemming down by one pixel on the y-axis. If the lemming isn’t falling, then it’s walking. In this case, we need to see whether there is a non-ground, background-coloured pixel in front of the lemming for it to move onto.

Sprites cling to the ground below them, navigating uneven terrain, and reversing direction when they hit an impassable obstacle.

If a pixel is found in front of the lemming (determined by its direction) that is low enough to get to (i.e. lower than its climbheight), then the lemming moves forward on the x-axis by one pixel, and upwards on the y-axis to the new ground level. However, if no suitable ground is found to move onto, then the lemming reverses its direction.

The algorithm is stored as a lemming’s update() method, which is executed for each lemming, each frame of the game. The sample level.png file can be edited, or swapped for another image altogether. If using a different image, just remember to update the level’s BACKGROUND_COLOUR in your code, stored as a (red, green, blue, alpha) tuple. You may also need to increase your lemming climbheight if you want them to be able to navigate a climb of more than four pixels.

There are other things you can do to make a full Lemmings clone. You could try replacing the yellow-rectangle lemmings in my example with pixel-art sprites with their own walk cycle animation (see my article in issue #14), or you could give your lemmings some of the special powers they’ll need to get to safety, achieved by creating flags that determine how lemmings interact with the terrain around them.

Here’s Rik’s code, which gets those path-following lemmings moving about in Python. To get it running 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 17

You can read more features like this one in Wireframe issue 17, 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 17 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 path-following Lemmings in Python | Wireframe issue 17 appeared first on Raspberry Pi.

Recreate the sprite-following Options from Gradius using Python | Wireframe issue 16

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-the-sprite-following-options-from-gradius-using-python-wireframe-issue-16/

Learn how to create game objects that follow the path of the main player sprite. Raspberry Pi’s own Rik Cross explains all.

Options first appeared in 1985’s Gradius, but became a mainstay of numerous sequels and spin-offs, including the Salamander and Parodius series of games.

Gradius

First released by Konami in 1985, Gradius pushed the boundaries of the shoot-’em-up genre with its varied level design, dramatic boss fights, and innovative power-up system.

One of the most memorable of its power-ups was the Option — a small, drone-like blob that followed the player’s ship and effectively doubled its firepower.

By collecting more power-ups, it was possible to gather a cluster of death-dealing Options, which obediently moved wherever the player moved.

Recreate sprite-following in Python

There are a few different ways of recreating Gradius’ sprite-following, but in this article, I’ll show you a simple implementation that uses the player’s ‘position history’ to place other following items on the screen. As always, I’ll be using Python and Pygame to recreate this effect, and I’ll be making use of a spaceship image created by ‘pitrizzo’ from opengameart.org.

The first thing to do is to create a spaceship and a list of ‘power-up’ objects. Storing the power-ups in a list allows us to perform a simple calculation on a power-up to determine its position, as you’ll see later. As we’ll be iterating through the power-ups stored in a list, there’s no need to create a separate variable for each. Instead, we can use list comprehension to create the power-ups:

powerups = [Actor(‘powerup’) for p in range(3)]

The player’s position history will be a list of previous positions, stored as a list of (x,y) tuples. Each time the player’s position changes, the new position is added to the front of the list (as the new first element). We only need to know the spaceship’s recent position history, so the list is also truncated to only contain the 100 most recent positions. Although not necessary, the following code can be added to allow you to see a selection (in this case every fifth) of these previous positions:

for p in previouspositions[::5]:

screen.draw.filled_circle(p, 2, (255,0,0))

Plotting the spaceship’s position history.

Each frame of the game, this position list is used to place each of the power-ups. In our Gradius-like example, we need each of these objects to follow the player’s spaceship in a line, as if moving together in a single-file queue. To achieve this effect, a power-up’s position is determined by its position in the power-ups list, with the first power-up in the list taking up a position nearest to the player. In Python, using enumerate when iterating through a list allows us to get the power-up’s position in the list, which can then be used to determine which position in the player’s position history to use.

newposition = previouspositions[(i+1)*20]

So, the first power-up in the list (element 0 in the list) is placed at the coordinates of the twentieth ((0+1)*20) position in the spaceship’s history, the second power-up at the fourtieth position, and so on. Using this simple calculation, elements are equally spaced along the spaceship’s previous path. The only thing to be careful of here is that you have enough items in the position history for the number of items you want to follow the player!

Power-ups following a player sprite, using the player’s position history.

This leaves one more question to answer; where do we place these power-ups initially, when the spaceship has no position history? There are a few different ways of solving this problem, but the simplest is just to generate a fictitious position history at the beginning of the game. As I want power-ups to be lined up behind the spaceship initially, I again used list comprehension

to generate a list of 100 positions with ever-decreasing x-coordinates.

previouspositions = [(spaceship.x - i*spaceship.speed,spaceship.y) for i in range(100)]

With an initial spaceship position of (400,400) and a spaceship.speed of 4, this means the list will initially contain the following coordinates:

previouspositions = [(400,400),(396,400),(392,400),(388,400),...]

Storing our player’s previous position history has allowed us to create path-following power-ups with very little code. The idea of storing an object’s history can have very powerful applications. For example, a paint program could store previous commands that have been executed, and include an ‘undo’ button that can work backwards through the commands.

Here’s Rik’s code, which recreates those sprite-following Options in Python. To get it running 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 16

You can read more features like this one in Wireframe issue 16, 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 16 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 Recreate the sprite-following Options from Gradius using Python | Wireframe issue 16 appeared first on Raspberry Pi.

Coding an isometric game map | Wireframe issue 15

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/coding-an-isometric-game-map-wireframe-issue-15/

Isometric graphics give 2D games the illusion of depth. Mark Vanstone explains how to make an isometric game map of your own.

Published by Quicksilva in 1983, Ant Attack was one of the earliest games to use isometric graphics. And you threw grenades at giant ants. It was brilliant.

Isometric projection

Most early arcade games were 2D, but in 1982, a new dimension emerged: isometric projection. The first isometric game to hit arcades was Sega’s pseudo-3D shooter, Zaxxon. The eye-catching format soon caught on, and other isometric titles followed: Q*bert came out the same year, and in 1983 the first isometric game for home computers was published: Ant Attack, written by Sandy White.

Ant Attack

Ant Attack was first released on the ZX Spectrum, and the aim of the game was for the player to find and rescue a hostage in a city infested with giant ants. The isometric map has since been used by countless titles, including Ultimate Play The Game’s classics Knight Lore and Alien 8, and my own educational history series ArcVenture.

Let’s look at how an isometric display is created, and code a simple example of how this can be done in Pygame Zero — so let’s start with the basics. The isometric view displays objects as if you’re looking down at 45 degrees onto them, so the top of a cube looks like a diamond shape. The scene is made by drawing cubes on a diagonal grid so that the cubes overlap and create solid-looking structures. Additional layers can be used above them to create the illusion of height.

Blocks are drawn from the back forward, one line at a time and then one layer on top of another until the whole map is drawn.

The cubes are actually two-dimensional bitmaps, which we start printing at the top of the display and move along a diagonal line, drawing cubes as we go. The map is defined by a three-dimensional list (or array). The list is the width of the map by the height of the map, and has as many layers as we want to represent in the upward direction. In our example, we’ll represent the floor as the value 0 and a block as value 1. We’ll make a border around the map and create some arches and pyramids, but you could use any method you like — such as a map editor — to create the map data.

To make things a bit easier on the processor, we only need to draw cubes that are visible in the window, so we can do a check of the coordinates before we draw each cube. Once we’ve looped over the x, y, and z axes of the data list, we should have a 3D map displayed. The whole map doesn’t fit in the window, and in a full game, the map is likely to be many times the size of the screen. To see more of the map, we can add some keyboard controls.

Here’s Mark’s isometric map, coded in Python. To get it running on your system, you’ll first need to install Pygame Zero. And to download the full code, visit our Github repository here.

If we detect keyboard presses in the update() function, all we need to do to move the map is change the coordinates we start drawing the map from. If we start drawing further to the left, the right-hand side of the map emerges, and if we draw the map higher, the lower part of the map can be seen.

We now have a basic map made of cubes that we can move around the window. If we want to make this into a game, we can expand the way the data represents the display. We could add differently shaped blocks represented by different numbers in the data, and we could include a player block which gets drawn in the draw() function and can be moved around the map. We could also have some enemies moving around — and before we know it, we’ll have a game a bit like Ant Attack.

Tiled

When writing games with large isometric maps, an editor will come in handy. You can write your own, but there are several out there that you can use. One very good one is called Tiled and can be downloaded free from mapeditor.org. Tiled allows you to define your own tilesets and export the data in various formats, including JSON, which can be easily read into Python.

Get your copy of Wireframe issue 15

You can read more features like this one in Wireframe issue 15, 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 15 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 Coding an isometric game map | Wireframe issue 15 appeared first on Raspberry Pi.

Make a Donkey Kong–style walk cycle | Wireframe issue 14

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/make-a-donkey-kong-style-walk-cycle-wireframe-issue-14/

Effective animation gave Donkey Kong barrels of personality. Raspberry Pi’s own Rik Cross explains how to create a similar walk cycle.

Donkey Kong wasn’t the first game to feature an animated character who could walk and jump, but on its release in 1981, it certainly had more personality than the games that came before it. You only have to compare Donkey Kong to another Nintendo arcade game that came out just two years earlier — the half-forgotten top-down shooter Sheriff — to see how quickly both technology and pixel art moved on in that brief period. Although simple by modern standards, Donkey Kong’s hero Jumpman (later known as Mario) packed movement and personality into just a few frames of animation.

In this article, I’ll show you how to use Python and Pygame to create a character with a simple walk cycle animation like Jumpman’s in Donkey Kong. The code can, however, be adapted for any game object that requires animation, and even for multiple game object animations, as I’ll explain later.

Jumpman’s (aka Mario’s) walk cycle comprised just three frames of animation.

Firstly, we’ll need some images to animate. As this article is focused on the animation code and not the theory behind creating walk cycle images, I grabbed some suitable images created by Kenney Vleugels and available at opengameart.org.

Let’s start by animating the player with a simple walk cycle. The two images to be used in the animation are stored in an images list, and an animationindex variable keeps track of the index of the current image in the list to display. So, for a very simple animation with just two different frames, the images list will contain two different images:

images = [‘walkleft1’,‘walkleft2’

To achieve a looping animation, the animationindex is repeatedly incremented, and is reset to 0 once the end of the images list is reached. Displaying the current image can then be achieved by using the animationindex to reference and draw the appropriate image in the animation cycle:

self.image = self.images[self.state][self.animationindex]

A list of images along with an index is used to loop through an animation cycle.

The problem with the code described so far is that the animationindex is incremented once per frame, and so the walk cycle will happen way too quickly, and won’t look natural. To solve this problem, we need to tell the player to update its animation every few frames, rather than every frame. To achieve this, we need another couple of variables; I’ll use animationdelay to store the number of frames to skip between displayed images, and animationtimer to store the number of frames since the last image change.

Therefore, the code needed to animate the player becomes:

self.animationtimer += 1
if self.animationtimer >= self.animationdelay:
self.animationtimer = 0
self.animationindex += 1
if self.animationindex > len(self.images) - 1:
self.animationindex = 0
self.image = self.images[self.animationindex]

So we have a player that appears to be walking, but now the problem is that the player walks constantly, and always in the same direction! The rest of this article will show you how to solve these two related problems.

There are a few different ways to approach this problem, but the method I’ll use is to make use of game object states, and then have different animations for each state. This method is a little more complicated, but it’s very adaptable.

The first thing to do is to decide on what the player’s ‘states’ might be — stand, walkleft, and walkright will do as a start. Just as we did with our previous single animation, we can now define a list of images for each of the possible player’s states. Again, there are lots of ways of structuring this data, but I’ve opted for a Python dictionary linking states and image lists:

self.images = { ‘stand’ : [‘stand1’],
‘walkleft’ : [‘walkleft1’,‘walkleft2’],
‘walkright’ : [‘walkright1’,‘walkright2’]
}

The player’s state can then be stored, and the correct image obtained by using the value of state along with the animationindex:

self.image = self.images[self.state][self.animationindex]

The correct player state can then be set by getting the keyboard input, setting the player to walkleft if the left arrow key is pressed or walkright if the right arrow key is pressed. If neither key is pressed, the player can be set to a stand state; the image list for which contains a single image of the player facing the camera.

Animation cycles can be linked to player ‘states’.

For simplicity, a maximum of two images are used for each animation cycle; adding more images would create a smoother or more realistic animation.

Using the code above, it would also be possible to easily add additional states for, say, jumping or fighting enemies. You could even take things further by defining an Animation() object for each player state. This way, you could specify the speed and other properties (such as whether or not to loop) for each animation separately, giving you greater flexibility.

Here’s Rik’s animated walk cycle, coded in Python. To get it running 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 14

You can read more features like this one in Wireframe issue 14, 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 14 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 Donkey Kong–style walk cycle | Wireframe issue 14 appeared first on Raspberry Pi.

Create an arcade-style zooming starfield effect | Wireframe issue 13

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/create-an-arcade-style-zooming-starfield-effect-wireframe-issue-13/

Unparalleled depth in a 2D game: PyGame Zero extraordinaire Daniel Pope shows you how to recreate a zooming starfield effect straight out of the eighties arcade classic Gyruss.

The crowded, noisy realm of eighties amusement arcades presented something of a challenge for developers of the time: how can you make your game stand out from all the other ones surrounding it? Gyruss, released by Konami in 1983, came up with one solution. Although it was yet another alien blaster — one of a slew of similar shooters that arrived in the wake of Space Invaders, released in 1978 — it differed in one important respect: its zooming starfield created the illusion that the player’s craft was hurtling through space, and that aliens were emerging from the abyss to attack it.

This made Gyruss an entry in the ‘tube shooter’ genre — one that was first defined by Atari’s classic Tempest in 1981. But where Tempest used a vector display to create a 3D environment where enemies clambered up a series of tunnels, Gyruss used more common hardware and conventional sprites to render its aliens on the screen. Gyruss was designed by Yoshiki Okamoto (who would later go on to produce the hit Street Fighter II, among other games, at Capcom), and was born from his affection for Galaga, a 2D shoot-’em-up created by Namco.

Under the surface, Gyruss is still a 2D game like Galaga, but the cunning use of sprite animation and that zooming star effect created a sense of dynamism that its rivals lacked. The tubular design also meant that the player could move in a circle around the edge of the play area, rather than moving left and right at the bottom of the screen, as in Galaga and other fixed-screen shooters like it. Gyruss was one of the most popular arcade games of its period, probably in part because of its attention-grabbing design.

Here’s Daniel Pope’s example code, which creates a Gyruss-style zooming starfield effect in Python. To get it running on your system, you’ll first need to install Pygame Zero — find installation instructions here, and download the Python code here.

The code sample above, written by Daniel Pope, shows you how a zooming star field can work in PyGame Zero — and how, thanks to modern hardware, we can heighten the sense of movement in a way that Konami’s engineers couldn’t have hoped to achieve about 30 years ago. The code generates a cluster of stars on the screen, and creates the illusion of depth and movement by redrawing them in a new position in a randomly chosen direction each frame.

At the same time, the stars gradually increase their brightness over time, as if they’re getting closer. As a modern twist, Pope has also added an extra warp factor: holding down the Space bar increases the stars’ velocity, making that zoom into space even more exhilarating.

Get your copy of Wireframe issue 13

You can read the rest of the feature in Wireframe issue 13, 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 13 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 an arcade-style zooming starfield effect | Wireframe issue 13 appeared first on Raspberry Pi.

Recreate iconic 1980s game explosions | Wireframe issue 12

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-bombermans-iconic-explosions-wireframe-issue-12/

Rik Cross, Senior Learning Manager here at the Raspberry Pi Foundation, shows you how to recreate the deadly explosions in the classic game, Bomberman.

An early incarnation of Bomberman on the NES; the series is still going strong today under Konami’s wing.

Creating Bomberman

Bomberman was first released in the early 1980s as a tech demo for a BASIC compiler, but soon became a popular series that’s still going today. Bomberman sees players use bombs to destroy enemies and uncover doors behind destructible tiles. In this article, I’ll show you how to recreate the bombs that explode in four directions, destroying parts of the level as well as any players in their path!

The game level is a tilemap stored as a two-dimensional array. Each tile in the map is a Tile object, which contains the tile type, and corresponding image. For simplicity, a tile can be set to one of five types; GROUND, WALL, BRICK, BOMB, or EXPLOSION. In this example code, BRICK and GROUND can be exploded with bombs, but WALL cannot, but of course, this behaviour can be changed.

Each Tile object also has a timer, which is decremented each frame of the game. When a tile’s timer reaches 0, an action is carried out, which is dependent on the tile type. BOMB tiles (and surrounding tiles) turn into EXPLOSION tiles after a short delay, and EXPLOSION tiles eventually turn back into GROUND. At the start of the game, the tilemap for the level is generated, in this case consisting of mostly GROUND, with some WALL and a couple of BRICK tiles. The player starts off in the top-left tile, and moves by using the arrow keys. Pressing the SPACE key will place a bomb in the player’s current tile, which is achieved by setting the Tile at the player’s position to BOMB. The tile’s timer is also set to a small number, and once this timer is decremented to 0, the bomb tile and the tiles around it are set to EXPLOSION.

Here’s Rik’s example code, which recreates Bomberman’s explosions in Python. To get it running on your system, you’ll first need to install Pygame Zero — you can find full instructions here. And you can download the code here.

The bomb explodes outwards in four directions, with a range determined by the RANGE, which in our code is 3. As the bomb explodes out to the right, for example, the tile to the right of the bomb is checked. If such a tile exists (i.e. the position isn’t out of the level bounds) and can be exploded, then the tile’s type is set to EXPLOSION and the next tile to the right is checked. If the explosion moves out of the level bounds, or hits a WALL tile, then the explosion will stop radiating in that direction. This process is then repeated for the other directions.

There’s a nice trick for exploding the bomb without repeating the code four times, and it relies on the sine and cosine values for the four direction angles. The angles are 0° (up), 90° (right), 180° (down) and 270° (left). When exploding to the right (at an angle of 90°), sin(90) is 1 and cos(90) is 0, which corresponds to the offset direction on the x- and y-axis respectively. These values can be multiplied by the tile offset, to explode the bomb in all four directions.

Get your copy of Wireframe issue 12

You can read the rest of the feature in Wireframe issue 12, 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 12 for free in PDF format.

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

The post Recreate iconic 1980s game explosions | Wireframe issue 12 appeared first on Raspberry Pi.

Coding Breakout’s brick-breaking action | Wireframe #11

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/coding-breakouts-brick-breaking-action-wireframe-11/

Atari’s Breakout was one of the earliest video game blockbusters. Here’s how to recreate it in Python.

The original Breakout, designed by Nolan Bushnell and Steve Bristow, and famously built by a young Steve Wozniak.

Atari Breakout

The games industry owes a lot to the humble bat and ball. Designed by Allan Alcorn in 1972, Pong was a simplified version of table tennis, where the player moved a bat and scored points by ricocheting a ball past their opponent. About four years later, Atari’s Nolan Bushnell and Steve Bristow figured out a way of making Pong into a single-player game. The result was 1976’s Breakout, which rotated Pong’s action 90 degrees and replaced the second player with a wall of bricks.

Points were scored by deflecting the ball off the bat and destroying the bricks; as in Pong, the player would lose the game if the ball left the play area. Breakout was a hit for Atari, and remains one of those game ideas that has never quite faded from view; in the 1980s, Taito’s Arkanoid updated the action with collectible power-ups, multiple stages with different layouts of bricks, and enemies that disrupted the trajectory of the player’s ball.

Breakout had an impact on other genres too: game designer Tomohiro Nishikado came up with the idea for Space Invaders by switching Breakout’s bat with a base that shot bullets, while Breakout’s bricks became aliens that moved and fired back at the player.

Courtesy of Daniel Pope, here’s a simple Breakout game written in Python. To get it running on your system, you’ll first need to install Pygame Zero. And download the code for Breakout here.

Bricks and balls in Python

The code above, written by Daniel Pope, shows you just how easy it is to get a basic version of Breakout up and running in Python, using the Pygame Zero library. Like Atari’s original, this version draws a wall of blocks on the screen, sets a ball bouncing around, and gives the player a paddle, which can be controlled by moving the mouse left and right. The ball physics are simple to grasp too. The ball has a velocity, vel – which is a vector, or a pair of numbers: vx for the x direction and vy for the y direction.

The program loop checks the position of the ball and whether it’s collided with a brick or the edge of the play area. If the ball hits the left side of the play area, the ball’s x velocity vx is set to positive, thus sending it bouncing to the right. If the ball hits the right side, vx is set to a negative number, so the ball moves left. Likewise, when the ball hits the top or bottom of a brick, we set the sign of the y velocity vy, and so on for the collisions with the bat and the top of the play area and the sides of bricks. Collisions set the sign of vx and vy but never change the magnitude. This is called a perfectly elastic collision.

To this basic framework, you could add all kinds of additional features: a 2012 talk by developers Martin Jonasson and Petri Purho, which you can watch on YouTube here, shows how the Breakout concept can be given new life with the addition of a few modern design ideas.

You can read this feature and more besides in Wireframe issue 11, available now in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy Wireframe directly from us – worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusives, and for subscriptions, visit the Wireframe website to save 49% compared to newsstand pricing!

The post Coding Breakout’s brick-breaking action | Wireframe #11 appeared first on Raspberry Pi.

Coding Pang’s sprite spawning mechanic | Wireframe #10

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/pang-sprite-spawning-wireframe-10/

Rik Cross, Senior Learning Manager here at Raspberry Pi, shows you how to recreate the spawning of objects found in the balloon-bursting arcade gem Pang.

Pang: bringing balloon-hating to the masses since 1989.

Capcom’s Pang

Programmed by Mitchell and distributed by Capcom, Pang was first released as an arcade game in 1989, but was later ported to a whole host of home computers, including the ZX Spectrum, Amiga, and Commodore 64. The aim in Pang is to destroy balloons as they bounce around the screen, either alone or working together with another player, in increasingly elaborate levels. Destroying a balloon can sometimes also spawn a power-up, freezing all balloons for a short time or giving the player a better weapon with which to destroy balloons.

Initially, the player is faced with the task of destroying a small number of large balloons. However, destroying a large balloon spawns two smaller balloons, which in turn spawns two smaller balloons, and so on. Each level is only complete once all balloons have been broken up and completely destroyed. To add challenge to the game, different-sized balloons have different attributes – smaller balloons move faster and don’t bounce as high, making them more difficult to destroy.

Rik’s spawning balloons, up and running in Pygame Zero. Hit space to divide them into smaller balloons.

Spawning balloons

There are a few different ways to achieve this game mechanic, but the approach I’ll take in my example is to use various features of object orientation (as usual, my example code has been written in Python, using the Pygame Zero library). It’s also worth mentioning that for brevity, the example code only deals with simple spawning and destroying of objects, and doesn’t handle balloon movement or collision detection.

The base Enemy class is simply a subclass of Pygame Zero’s Actor class, including a static enemies list to keep track of all enemies that exist within a level. The Enemy subclass also includes a destroy() method, which removes an enemy from the enemies list and deletes the object.

There are then three further subclasses of the Enemy class, called LargeEnemy, MediumEnemy, and SmallEnemy. Each of these subclasses are instantiated with a specific image, and also include a destroy() method. This method simply calls the same destroy() method of its parent Enemy class, but additionally creates two more objects nearby — with large enemies spawning two medium enemies, and medium enemies spawning two small enemies.

Wireframe 10 Pang

Here’s Rik’s example code, which recreates Pang’s spawning balloons in Python. To get it running on your system, you’ll first need to install Pygame Zero – you can find full instructions here. And you can download the code here.

In the example code, initially two LargeEnemy objects are created, with the first object in the enemies list having its destroy() method called each time the Space key is pressed. If you run this code, you’ll see that the first large enemy is destroyed and two medium-sized enemies are created. This chain reaction of destroying and creating enemies continues until all SmallEnemy objects are destroyed (small enemies don’t create any other enemies when destroyed).

As I mentioned earlier, this isn’t the only way of achieving this behaviour, and there are advantages and disadvantages to this approach. Using subclasses for each size of enemy allows for a lot of customisation, but could get unwieldy if much more than three enemy sizes are required. One alternative is to simply have a single Enemy class, with a size attribute. The enemy’s image, the entities it creates when destroyed, and even the movement speed and bounce height could all depend on the value of the enemy size.

You can read the rest of the feature in Wireframe issue 10, available now in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy Wireframe directly from us – worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusives, and for subscriptions, visit the Wireframe website to save 49% compared to newsstand pricing!

The post Coding Pang’s sprite spawning mechanic | Wireframe #10 appeared first on Raspberry Pi.

Coding Space Invaders’ disintegrating shields | Wireframe #9

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/coding-space-invaders-disintegrating-shields-wireframe-9/

They add strategy to a genre-defining shooter. Andrew Gillett lifts the lid on Space Invaders’ disintegrating shields.

Wireframe 9 Space Invaders

Released in 1978, Space Invaders introduced ideas so fundamental to video games that it’s hard to imagine a time before them. And it did this using custom-made hardware which by today’s standards is unimaginably slow.

Space Invaders ran on an Intel 8080 CPU operating at 2MHz. With such meagre processing power, merely moving sprites around the screen was a struggle. In modern 2D games, at the start of each frame the entire screen is reset, then all objects are displayed.

For Space Invaders’ hardware, this process would have been too slow. Instead, each time a sprite needs to move, the game first erases the sprite from the screen, then redraws it in the new position. The game also updates only one alien per frame — which leads to the effect of the aliens moving faster when there are fewer of them. These techniques cut down the number of pixels which need to be updated each frame, from nearly 60,000 to around a hundred.

Wireframe 9 Space Invaders

One of Space Invaders’ most notable features is its four shields. These provide shelter from enemy fire, but deteriorate after repeated hits. The player can take advantage of the shields’ destructible nature — by repeatedly firing at the same place on a shield’s underside, a narrow gap can be created which can then be used to take out enemies. (Of course, the player can also be shot through the same gap.)

The system of updating only the minimum necessary number of pixels works well as long as there’s no need for objects to overlap. In the case of the shields, though, what happens when objects do overlap is fundamental to how they work. Whenever a shot hits something, it’s replaced by an explosion sprite. A few frames later, the explosion sprite is deleted from the screen. If the explosion sprite overlapped with a shield, that part of the shield is also deleted.

Wireframe 9 Space Invaders

Here’s a code snippet that shows Andrew’s Space Invaders-style disintegrating shields working in Python. To get it running on your system, you’ll need to install Pygame Zero — you can find full instructions here. And download the above code here.

The code to the right displays four shields, and then bombards them with a series of shots which explode on impact. I’m using sprites which have been scaled up by ten, to make it easier to see what’s going on.

We first create two empty lists — one to hold details of any shots on screen, as well as explosions. These will be displayed on the screen every frame. Each entry in the shots list will be a dictionary data structure containing three values: a position, the sprite to be displayed, and whether the shot is in ‘exploding’ mode — in which case it’s displayed in the same position for a few frames before being deleted.

The second list, to_delete, is for sprites which need to be deleted from the screen. For simplicity, I’m using separate copies of the shot and explosion sprites where the white pixels have been changed to black (the other pixels in these sprites are set as transparent).

The function create_random_shot is called every half-second. The combination of dividing the maximum value by ten, choosing a random whole number between zero and the maximum value, and then multiplying the resulting random number by ten, ensures that the chosen X coordinate is a multiple of ten.


Wireframe 9 Space Invaders
Wireframe 9 Space Invaders

Andrew’s Space Invaders shields up and running in Pygame Zero.

In the draw function, we first check to see if it’s the first frame, as we only want to display the shields on that frame. The screen.blit method is used to display sprites, and Pygame Zero’s images object is used to specify which sprite should be displayed. We then display all sprites in the to_delete list, after which we reset it to being an empty list. Finally we display all sprites in the shots list.

Wireframe 9 Space Invaders

In the update function, we go through all sprites in the shots list, in reverse order. Going through the list backwards avoids problems that can occur when deleting items from a list inside a for loop. For each shot, we first check to see if it’s in ‘exploding’ mode. If so, its timer is reduced each frame — when it hits zero we add the shot to the to_delete list, then delete it from shots.

If the item is a normal shot rather than an explosion, we add its current position to to_delete, then update the shot’s position to move the sprite down the screen. We next check to see if the sprite has either gone off the bottom of the screen or collided with something. Pygame’s get_at method gives us the colour of a pixel at a given position. If a collision occurs, we switch the shot into ‘exploding’ mode — the explosion sprite will be displayed for five frames.

You can read the rest of the feature in Wireframe issue 9, available now in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy Wireframe directly from us – worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusives, and for subscriptions, visit the Wireframe website to save 49% compared to newsstand pricing!

The post Coding Space Invaders’ disintegrating shields | Wireframe #9 appeared first on Raspberry Pi.

How musical game worlds are made | Wireframe #8

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/how-musical-game-worlds-are-made-wireframe-8/

88 Heroes composer Mike Clark explains how music and sound intertwine to create atmospheric game worlds in this excerpt from Wireframe issue 8, available now.

Music for video games is often underappreciated. When I first started writing music in my bedroom, it took me a while to realise how much I was influenced by the worlds that came from my tiny CRT TV. A couple of years ago, I was lucky enough to be approached by Bitmap Bureau, an indie startup who hired me to compose the music for their first game, 88 Heroes.

88 Heroes is a platformer styled like a Saturday morning cartoon. Interestingly, cartoon soundtracks have a lot in common with those for stage productions: short musical cues accompany the actions on screen, so if someone violently falls downstairs, you hear a piano rolling down the keys. This is called ‘mickey mousing’ in cartoons, but we hear similar things in film soundtracks.

Take Raiders of the Lost Ark, scored by John Williams: for every heroic rope swing, leap of faith, or close encounter with danger, the main theme can be heard powering through the dissonances and changing rhythms. It fills the audience with hope and becomes synonymous with the lead character – we want to see him succeed. Let’s not forget the title theme. Every time you see the Star Wars logo, does that grand title theme play in your head? It’s the same with video games. The challenge here, of course, is that players often leave the title screen after three seconds.

Three seconds is all you need though. Take Super Mario World’s soundtrack, composed by Koji Kondo. Many of its levels have the same leading melody, which changes subtly in tonality and rhythm to create the appropriate mood. The most repeating part of the melody is four bars long, but we hear it in so many forms that we only need the first two bars to know where it’s from. In classical music, this is called ‘variations on a theme’. In video games, we call it a ‘sonic identity’.

Action platformer 88 Heroes, featuring music by Mike Clark.

How a picture should ‘sound’

Sonic identity informed my approach to the 88 Heroes soundtrack. The title screen tells us that an unknown group is going to save the day. I first thought about unlikely heroes who end up on an adventure, and Back to the Future, scored by Alan Silvestri, sprang to mind. The second inspiration came from traditional superheroes, like Superman. I composed a melody which travels between the first and fifth notes in the scale (in this case C and G), with little flourishes of the notes in-between. It’s a triumphant, heroic melody.

This concept helps to connect these worlds beyond their visuals. It took a long time for games to evolve into the cohesive open-world sandboxes or MMOs we see today; the technology that masked loading screens to create a seamless experience was unheard of in the 1990s, so a melody that you hear in different ‘costumes’ gives these games a sense of cohesion.

Intelligent instruments

What if you have levels (or worlds) so big that some areas need to be loaded? That’s where non-linear composition comes in. Banjo-Kazooie, released for the N64 in 1998, was among the first 3D games to feature dynamic music. It used a technique called MIDI channel fading. MIDI stands for Musical Instrument Digital Interface; think of it as a universal language for music that is played back in real time by the hardware. As you walk into caves, fly in the sky, or move near certain characters, instruments fade in and out using the different MIDI channels to mimic the atmosphere, give the player an audio cue, and build and release tension.

Learning how to write music that changes as you play might seem impossible at first, but it becomes second nature once you understand the relationship between every instrument in your composition. Many digital audio workstations, like Logic and FL Studio, let you import MIDI data for a song (so you have all the notes in front of you) and set the instruments yourself. Try slowly fading out or muting certain tracks altogether, and listen to how the mood changes. What could this change represent in a video game? It’s like when you’re riding Yoshi in many of the Mario games; the fast bongos come in to represent the quick-footed dinosaur as he dashes at high speeds.

Undertale’s soundtrack blends analogue synth instruments with a plethora of real instruments to help create emotion.

Music is used to evoke emotions that wouldn’t be possible with visuals alone. Beep: A Documentary History of Game Sound shows a six-second video of a boat accompanied by two soundtracks; one is a light and happy guitar piece, the other a grating, scary, orchestral dissonance. Through these two extremes, the music creates the mood by itself. I remember playing Metroid Prime and finding the Chozo Ghost enemies rather scary, not because of their appearance, but because of the unnerving music that accompanies them. Music and sound design are one and the same. Think about what feelings you can create by taking music away entirely — it’s a great way to create tension before a boss battle or pivotal plot point, and it really works. In Undertale, scored by Toby Fox, there are times when the music stops so abruptly during NPC dialogue that you feel shivers down your spine.

So, what if you’re trying to come up with some game music, and you have writer’s block? Well, the next time you play a new game, turn the sound off. As you’re playing, focus on how the story, art, or characters make you feel, and focus on the emotions the game is trying to convey. Then, think of a time when a song made you feel happy, sad, joyful, anxious, or even frightened. Maybe you can use the music to create the mood you want for that game, as opposed to what the game makes you feel. By finding these emotions and understanding how they can change, you’ll be able to write a score that helps strengthen the immersion, escapism, and player investment in your game.

You can read the rest of the feature in Wireframe issue 8, available now in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy Wireframe directly from us – worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

Markets, moggies, and making in Wireframe issue 8

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusives, and for subcriptions, visit the Wireframe website to save 49% compared to newsstand pricing!

The post How musical game worlds are made | Wireframe #8 appeared first on Raspberry Pi.

Inside the Dreamcast homebrew scene | Wireframe issue 7

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/wireframe-7-inside-dreamcast-homebrew-scene/

Despite its apparent death 17 years ago, the Sega Dreamcast still has a hardcore group of developers behind it. We uncover their stories in this excerpt from Wireframe issue 7, available now.

In 1998, the release of the Dreamcast gave Sega an opportunity to turn around its fortunes in the home console market. The firm’s earlier system, the Saturn, though host to some beloved titles, was running a distant third in sales behind the Nintendo 64 and PlayStation. The Dreamcast, by contrast, saw a successful launch and quickly became the go-to system for arcade-quality ports of fighting games, among other groundbreaking titles like Seaman and Crazy Taxi.

Unfortunately for fans, it wasn’t to last. The Dreamcast struggled to compete against the PlayStation 2, which launched in 2000, and at the end of March 2001, in the face of the imminent launch of the Nintendo GameCube and Microsoft’s new Xbox, Dreamcast left the stage, and Sega abandoned the console market altogether.

None of this stopped a vibrant homebrew development scene springing up around the console in Sega’s place, and even years later, the Dreamcast remains a thriving venue for indie developers. Roel van Mastbergen codes for Senile Team, the developers of Intrepid Izzy, a puzzle platformer coming soon to the PC, PS4, and Dreamcast.

Of the port to Sega’s ageing console, van Mastbergen tells us, “I started this project with only the PC in mind. I’m more used to developing for older hardware, though, so I tend to write code with low CPU and RAM requirements by force of habit. At some point I decided to see if I could get it running on the Dreamcast, and I was happy to find that it ran almost perfectly on the first try.”

It runs at a lower resolution than on PC, but Intrepid Izzy still maintains a smooth 60fps on Dreamcast.

One of the pluses of the Dreamcast, van Mastbergen points out, is how easy it is to develop for. “There are free tools and sufficient documentation available, and you can run your own code on a standard Dreamcast without any hardware modifications or hacks.”

Games burned to CD will play in most models of unmodified Dreamcast, usually with no extra software required. While this doesn’t result in a huge market — the customer base for new Dreamcast games is difficult to measure but certainly small — it makes development for original hardware far more viable than on other systems, which often need expensive and difficult-to-install modchips.

Many of the games now being developed for the system are available as digital downloads, but the state of Dreamcast emulation lags behind that of its competitors, with no equivalent to the popular Dolphin and PCSX2 emulators for GameCube and PS2. All this makes boxed games on discs more viable than on other systems — and, in many cases, physical games can also become prized collectors’ items.

Intrepid Izzy is developed with a custom code library that works across multiple systems; it’s simple to downscale PC assets and export a Dreamcast binary.

Kickstarting dreams

By now, you might be asking yourself what the point of developing for these old systems is — especially when creating games for PC is a much easier and potentially more profitable route to take. When it comes to crowdfunding, though, catering to a niche but dedicated audience can pay dividends.

Belgian developer Alice Team, creators of Alice Dreams Tournament, asked for €8000 in funding to complete its Dreamcast exclusive, which began development in 2006. It eventually raised €28,000 — more than treble its goal.

Intrepid Izzy didn’t quite reach such dizzying heights, only just meeting its €35,000 target, but van Mastbergen is clear it wouldn’t have been funded at all without the dedicated Dreamcast base. “The project has been under-funded since the beginning, which is slightly problematic,” van Mastbergen tells us. “Even so, it is true that the Dreamcast community is responsible for the lion’s share of the funding, which is a testament to how well-loved this system still is.”

You can read the rest of the feature in Wireframe issue 7, available in Tesco, WHSmith, and all good independent UK newsagents.

Or you can buy Wireframe directly from us – worldwide delivery is available. And if you’d like to own a handy digital version of the magazine, you can also download a free PDF.

Face your fears in the indie horror, Someday You’ll Return.

Make sure to follow Wireframe on Twitter and Facebook for updates and exclusives, and for subscriptions, visit the Wireframe website to save 49% compared to newsstand pricing!

The post Inside the Dreamcast homebrew scene | Wireframe issue 7 appeared first on Raspberry Pi.