Tag Archives: Wireframe magazine

How pillars and triangles can focus your game design

Post Syndicated from Ian Dransfield original https://www.raspberrypi.org/blog/how-pillars-and-triangles-can-focus-your-game-design/

In game design, freedom can lead to paralysis. But in the latest issue of Wireframe magazine, Stuart Maine explains how game pillars and the iron triangle will help you focus on what’s important.

The flexibility of the medium of video games lets us experience concepts like the non-Euclidean geometry behind Superliminal’s ‘whatever you see is reality’
The flexibility of the medium of video games lets us experience concepts like the non-Euclidean geometry behind Superliminal’s ‘whatever you see is reality’

This article will cover two game development tools that are designed to help decide what’s important in the game you’re making. The iron triangle revolves around the practical realities of making a game, while game pillars cover the creative side, but both relate to the importance of focus. Let’s begin with pillars.

Game pillars

Every game media has its strengths, such as wargaming’s communities, the shared experiences of board games, or the collaboration of RPGs. One of the advantages of video games is their sheer flexibility – we can race across alien worlds, explore Egyptian tombs, or keep fit while going on magical quests. But that infinite flexibility can be a real problem for game creators, because if the game you’re making can include literally anything, then how do you know what to focus on?

A pillar saying your game is a platformer doesn’t really help, it’s what you do or say with that basic framework that matters
A pillar saying your game is a platformer doesn’t really help, it’s what you do or say with that basic framework that matters

Let’s assume you have an idea for a game based on a particular world or character, or a certain type of gameplay. Alternatively, you might have used player types (see Wireframe issue 39) to decide on a particular audience and the features they like, or if you’re working with someone else’s IP, then that brand’s owners might have a type of gameplay in mind. Game pillars help move beyond those starting points and guide you through development.

The basics

A game’s pillars are a list of around three ‘core statements’ created early in that game’s development. You could come up with your pillars before you’ve started development to help narrow down the possible game you might make, or you might do this after prototyping has given you an idea you want to pursue. You can even retroactively create pillars to help rescue a game that’s been in development for a while and has lost its way.

  • Each statement should be short – no more than a sentence – and each should be phrased as a rule you will follow throughout development.
  • Use active language. We will, we like, this game is, our audience wants, and so on. Don’t use negative language if you can rephrase the same statement as a positive.
  • Importantly, make your pillars focus on how your players will feel over the things they will do. This is probably the most important concept here, so let’s explore it further.
During development, Rime began to deviate from its original goals and the team had to take the decision to refocus on their pillars
During development, Rime began to deviate from its original goals and the team had to take the decision to refocus on their pillars

Dig deeper into the ‘why’

It’s easy to write ‘our game will feature 2D puzzles and platforming’, and technically that is a pillar because you can refer back to it later. But it doesn’t really say anything about what that platforming is for. By that, I mean why are you making a game about platforming? To dig deeper into the ‘why’ behind your pillar, you could rewrite that sentence to one of these:

  • Explore evocative alien worlds, telling a story through atmosphere and details
  • It’s satisfying to master deep systems and figure out hidden rules
  • Our players will achieve a state of flow through challenging, precision gameplay

Those are my example guesses at a pillar each for the platform games Flashback, Spelunky, and Celeste. All are 2D platformers, but they’re ‘about’ very different things.

What to do with your pillars

Note that none of the above examples specifically talk about the gameplay being platforming, because pillars should focus on the feelings and emotions you want your game to evoke, rather than how you’re going to do it. That’s because pillars aren’t a feature list to check off, more a tool to help remember the things that are important when you’re submerged in the day-to-day realities of game development. Pillars are the why of your game, and the actual development process is coming up with the what to match those initial goals.

Another benefit of pillars is they can be used to communicate the game’s vision to the public, helping to balance reality and hype
Another benefit of pillars is they can be used to communicate the game’s vision to the public, helping to balance reality and hype

Print your chosen pillars as large as you can and put them up somewhere you’ll see them every day. That way they’ll become ingrained in your thoughts and you’ll easily be able to refer to them when someone suggests a new feature or change to the game. Will that change help bring your game closer to your pillars (great), not really affect them (neutral), or work against them (bad)?

I’ve seen studios use pillars on struggling games to discard any areas which don’t match them. You particularly see this if a game is taking too long to release (because most professional studios have to get a game out to some sort of deadline – more on this below), with people looking back to their pillars to help work out what to cut. If feature A is cool, but feature B aligns with the pillars, it’ll take a strong argument to keep A.

Establishing pillars

There are a couple of approaches for coming up with a game’s pillars, each with advantages, but also potential problems to look out for. Both of these approaches assume you already know to some degree what the game will be. Your pillars will help guide the eventual game’s details, but they’re a tool for staying on track as you forge ahead, not for coming up with ideas in the first place. If you haven’t agreed on a concept for your game yet, then run game jams, conduct audience and market research, or paper prototype ideas first.

When you’re working with someone else’s brand, involve that IP’s holder in pillar discussions so that they’re onboard with your chosen direction
When you’re working with someone else’s brand, involve that IP’s holder in pillar discussions so that they’re onboard with your chosen direction

Second, both approaches assume any business, audience, IP, or technology factors are already agreed and set in stone. For example, you might already know that this will be a multiplayer game, that it must be released within this time frame, or that it must be built on the technology created for your previous game. We’ll talk more about this with the iron triangle, but basically, any real-world issues that are beyond your control must be acknowledged or you risk coming up with pillars that set you up for difficulties later.

Duke Nukem Forever is an example of a major game that suffered for its lack of creative direction
Duke Nukem Forever is an example of a major game that suffered for its lack of creative direction

Two approaches

The two approaches are to have the entire team brainstorm potential pillars, or have vision holders dictate them:

ONE: If the entire team is involved, then you run brainstorming sessions where everyone’s potential pillar ideas are stuck up on a wall. Then the group chooses the best pillars or combines a couple of ideas into pillars (remember the point about keeping them short – mashing many ideas into a long pillar is cheating). 

The advantage of this approach is that everyone understands and buys into the chosen pillars because they had a say in creating them. The downside is that this process can take time, with potentially conflicting ideas needing to be whittled down until an agreement is reached.

TWO: The other approach is for ‘creative vision holders’ to come up with the game’s pillars and then present them to the rest of the team. Obviously, this is much less collaborative and more about saying, ‘I have a vision for this game which I think could be incredible, will you help me make it?’ The advantage of this is that everyone can rally behind a singular vision that someone is passionate about bringing to the world. As a result, the game’s pillars are likely to be extremely focused and all pointing in the same direction. The downside is that it requires everyone else to get on board with the game’s pillars even though they didn’t help come up with them.

Either way, once the pillars have been created, everyone on the team has to work with them in mind – there’s an implied contract that these rules must be enforced to ensure the game keeps moving in the right direction. Even though it can be unpopular to say no to someone’s idea, that’s what pillars are there to help with (and of course, pillars don’t say ‘that idea is bad’, simply that it doesn’t fit this particular game. Write the idea down and maybe build your next game around it).

Examples

Here are some actual pillars from games I’ve worked on:

  • Live through the apocalypse by any means necessary.
    This pillar from a military-themed game establishes that any action is acceptable in order to survive, implying a gritty, survival-of-the-fittest tone. 
  • Does it make me feel loved?
    A pillar from a game that was designed to appeal to an audience that liked romances and was looking for escapism. This guided our characters, environments, and art style.
  • Make me feel powerful, and make me say, ‘That was awesome!’
    It’s always worth considering a pillar covering who the player is in this game. If you’re making a game about being a giant robot, then ensure players feel big and powerful.
  • Small actions = epic reactions.
    From a puzzle game themed around combat. Because the player is making very small actions (tap, drag) we wanted to ensure the game responded with weighty reactions.
  • Express your own style in a safe way.
    If you’re working on a game for kids, it’s worth thinking about the challenges and worries in their lives, and whether your game can help them safely explore those areas.
  • Trust the player – it’s their game, let them play how they like.
    We used this for a procedurally created game, reminding the team not to create puzzles but to focus on systems that players could use and abuse any way they wanted.

The value of pillars

I realise that game pillars are quite an abstract topic, but in my experience across many games and studios, they have proven their worth. At the start of a project, they help avoid the ‘blank page’ problem of being able to make anything you can imagine, and later they help you say ‘this, but not that’ and avoid wandering in the development wilderness. So however you choose to structure or word your game pillars, I wholeheartedly recommend spending a little time thinking about the why before you launch into the what.

Owlboy: a game that favoured quality over time. It took about nine years to make, but looked spectacular
Owlboy: a game that favoured quality over time. It took about nine years to make, but looked spectacular

Speaking of which, let’s take a look at the iron triangle and how it will impact your game, because no matter what you do in the games industry, the triangle will impact you. As a result, it’s important to have an idea of how it works and what it means to your projects. A quick disclaimer: I’m going to simplify a complex area for space reasons, so if it interests you, check out online resources on this and other project management topics.

Art versus business

Have you ever played a game and clearly seen that it was unfinished? Missing features, obvious bugs, and a lack of polish show that you’re playing a game that needed more development time. The iron triangle is the reason games are released in an unfinished state, but it isn’t some malevolent force – it’s simply where reality butts up against creativity in game development.

Although no one sets out to make a bad game, movie licences often feel the pressure of the iron triangle due to their fixed release date
Although no one sets out to make a bad game, movie licences often feel the pressure of the iron triangle due to their fixed release date

Coined by Dr. Martin Barnes, the triangle applies to premium games as much as free ones, and to indie games as equally as blockbusters. It relates to…

Three areas of game development

  • Quality: How ‘good’ is your game? Good could mean it has many features, levels, NPCs, and weapons, or that what you have is highly polished and balanced. It also dictates how many bugs you let through into the finished game (no one ever fixes all their bugs, you just choose which are most important).
  • Time: Implementing all of the above takes time, so this point of the triangle relates to how long your game will take to be released. Most game developers have to release their games to some sort of deadline; see ‘Time = money’ for more on this.
  • Money: The longer a game’s in development, the more money it costs, with most coming from the wages or living expenses of the team working on it. Money is the most complicated of the three factors because there’s a limit to how much you can throw at a game. A feature that’s going to take a lone developer ten months can’t be done in one simply by paying to put ten developers on it – people get in each other’s way and you have to pay even more because that many people need a lot of management.

Choose your priorities

Now we know the three points of the iron triangle – where things get interesting is that those points are all interrelated, and the rule is you can only control two of the three points. You can select which two points you want to control, but you have no say on what happens to the third. That’s why it’s called an iron triangle – the outcome of the third point is decided by what you do with the two you’ve chosen to control.

Shigeru Miyamoto spoke about delaying The Ocarina of Time until it was of the highest quality, making ‘cost’ the element out of his control
Shigeru Miyamoto spoke about delaying The Ocarina of Time until it was of the highest quality, making ‘cost’ the element out of his control

These are the outcomes you can expect based on the two points of the triangle you choose to control:

  • Controlling time and money is where you see licensed tie-in games. Because they need to release alongside (say) a movie, they must come out on a certain date, and they can’t cost more than a certain amount otherwise it isn’t worth making the game in the first place. The point of the triangle not controlled here is quality, meaning the game will be as big and polished as it happens to be when the time and money run out.
  • The second choice is to control time and quality, meaning the game must come out on a certain date and be at least ‘this’ good (e.g. large, polished, and bug-free). This option means you relinquish control over the game’s cost – it will simply cost as much as it needs to, to ensure it hits your quality bar and is released on time.
  • Finally, you can control money and quality, meaning the game will be big and polished, but the team is kept small to limit development costs. This means you have no control over how long the game will take to release because a small team making a polished product can only work so fast.

Business realities

You might be wondering why any of this matters – after all, you could be making a game in your spare time or working at a studio where other people make these decisions. But if you understand which of the points of the triangle your project is trying to control, then you can work more effectively, making choices that work towards those needs rather than against them.

As a side note, if you’re working at a studio and whoever’s in charge insists they can control all three points of the iron triangle, consider that a Big Red Warning. That sort of denial of the fundamentals of project management means overtime – and a game that’s likely to go off the rails.

The iron triangle isn’t about hateful business realities quashing your creative dreams, it’s about choosing and understanding your priorities so that you control your game, not the other way around.

Recap

To recap: choosing your game’s pillars helps you focus on what’s important, and choosing which two points of the iron triangle you want to control helps you focus on the reality of making a game. Both of these are important, because not deciding on a game’s pillars can lead to the end result being a mess of conflicting ideas pulling in multiple directions, and ignoring the iron triangle leads to games spiralling into overtime, delays, and impossible demands. Yes, making games should be fun, but a little focus early in a project’s life can pay off big time later on.

Get your copy of Wireframe issue 52

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

Wireframe issue 52's cover

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

The post How pillars and triangles can focus your game design appeared first on Raspberry Pi.

Recreate Gradius’ rock-spewing volcanoes | Wireframe #52

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/recreate-gradius-volcanoes-wireframe-52/

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

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

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

Flying rocks

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

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

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

Get the ship moving

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

Collision detection

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

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

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

Get your copy of Wireframe issue 52

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

Wireframe issue 52's cover

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

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

Gifts that last all year round

Post Syndicated from Ashley Whittaker original https://www.raspberrypi.org/blog/gifts-that-last-all-year-round/

What if you could give the joy of opening a Raspberry Pi–themed gift every single month for a whole year? But what if the thought of wrapping 12 individual things fills you with Scrooge-level dread?

Snap up a magazine subscription for one of your nearest and/or dearest and we’ll take care of the packaging and delivery while you sit back and reap all the credit!

You could end up with a few extra gifts depending on what you sign up for so, read on and take your pick.

The MagPi magazine

Magpi magazines fanned out with free gift to the side of them

The official Raspberry Pi magazine comes with a free Raspberry Pi Zero W kit worth £20 when you sign up for a 12-month subscription. You can use our tiniest computer in tonnes of projects, meaning Raspberry Pi fans can never have enough. That’s a top gift-giving bonus for you right there.

Every issue of The MagPi is packed with computing and electronics tutorials, how-to guides, and the latest news and reviews. They also hit their 100th issue this month so, if someone on your list has been thinking about getting a subscription, now is a great time.

Check out subscription deals on the official Raspberry Pi Press store.

HackSpace magazine

Hackspace magazines fanned out with adafruit gift on top

HackSpace magazine is the one to choose for fixers and tinkerers of all abilities. If you’re looking for a gift for someone who is always taking things apart and hacking everyday objects, HackSpace magazine will provide a year of inspiration for them.

12-month subscriptions come with a free Adafruit Circuit Playground Express, which has been specially developed to teach programming novices from scratch and is worth £25.

Check out subscription deals on the official Raspberry Pi Press store.

Custom PC

Some Custom PC magazines fanned out with the free giveaway mouse on top of them

Custom PC is the magazine for people who are passionate about PC technology and hardware. And they’ve just launched a pretty cool new giveaway with every 12-month subscription: a free Chillblast Aero RGB Gaming mouse worth £40. Look, it lights up, it’s cool.

Check out subscription offers on the official Raspberry Pi Press store.

Wireframe magazine

Wireframe magazine lifts the lid on video games. In every issue, you’ll find out how games are made, who makes them, and how you can code them to play for yourself using detailed guides.

The latest deal gets you three issues for just £10, plus your choice of one of our official books as a gift. By the way, that ‘three for £10 plus a free book’ is available across ALL our magazines. Did I not tell you that before? My bad. It’s good though, right?

Check out more subscriptions deals on the official Raspberry Pi Press store.

Three books for the price of one

A selection of Raspberry Pi books on a table surrounded by Christmas decorations

And as an extra Christmas gift to you all, we’ve decided to keep our Black Friday deal rolling until Christmas Eve, so if you buy just one teeny tiny book from the Raspberry Pi Press store, you get two more completely FREE!

Better still, all of the books in the deal only cost £7 or £10 to start with, so makes for a good chunky batch of presents at a brilliantly affordable price.

The post Gifts that last all year round appeared first on Raspberry Pi.

Make your own virtual reality 3D Shooter

Post Syndicated from Mark Vanstone original https://www.raspberrypi.org/blog/make-your-own-virtual-reality-3d-shooter/

In the latest issue of Wireframe magazine, Mark Vanstone shows you how to turn a 3D shooter into a VR game for a variety of viewers, from Google Cardboard to gaming headsets.

Our shooter, now in VR format. Blast aliens from the sky as they fly over the mountains.

Browser development has really matured of late, with a number
of exciting new features coming to the fore. Where WebGL was well supported, the new WebXR (previously WebVR) is now becoming standard
in modern browsers. JavaScript ES5 has now been superseded by ES6, and with these new technologies, making browser-based apps – and specifically 3D games – is now a serious proposition. The other part of VR technology, the hardware, has also evolved – as mobile tech has become more powerful, so have the opportunities for cost-effective VR experiences.

With a mobile phone you can create a stereoscopic display for use with a simple Cardboard viewer.

If you have an old mobile phone, perhaps an Make your own virtual reality 3D Shooter B iPhone 6 or a Samsung S7, you can get a Google Cardboard headset for £6 and turn it into a rudimentary VR viewer. In this article, we’ll show you how to set up a 3D shooter to run not only on that hardware, but also on other viewers such as the Gear VR or Daydream, and even gaming headsets such as the Oculus, HTC, or Valve. All of these have web browsers built in which can support WebXR or a 3D display, and although there are some differences between how they work, the process of displaying a 3D scene is mostly the same on all of them, so we can use the Three.js JavaScript library.

Three different VR headsets on a white background
There’s a wide range of VR viewers and headsets on the market, from Google Cardboard to pricey gaming headsets like the Oculus, HTC, HP, Microsoft, and Valve ranges.

To begin, we’ll start with the Three.js 3D shooter we made in Wireframe #32 – if you missed it, you can download a copy. We’ll use the same models and much of the same code. The first change, though, is to update the code to run as an ES6 module. The non-module version of Three.js is being phased out at the end of 2020, so it’s probably best to get with the times and use the new stuff. As with our earlier shooter, you’ll need to run this code from a secure web server, which, for mobile phones and gaming headsets, will mean uploading it to somewhere suitable, but if you want to see it running, you can play it at technovisual.co.uk/vr.

Basic VR viewers

Now we need to consider the hardware we’re going to use to run our game. Let’s start at our baseline, Google Cardboard, and work up from there. Available from many outlets online (including Google’s store), it’s a cut-out kit, which you fold up to create a viewer.


From a browser window inside a gaming headset environment, you can launch a Three.js VR experience

There are two lenses to look through, two magnets in a recess on the side, and velcro tabs to hold a mobile phone. The magnets on the side serve as a selection mechanism which we’ll explore later.

Next, we have Gear VR-style viewers. There are many different types, priced from around £12 to £40, and these are essentially a better-built plastic version of the Cardboard but with a button on top to act as a selector. Phones of varying sizes can be used, and as long as the device isn’t more than about four years old, it should be up-to-date enough to run the 3D software.

For example, the six-year-old Samsung S5 is capable of displaying VR, but it’s a bit too slow to make the experience pleasant, whereas a five-year-old iPhone 6 is quite capable of displaying simple VR scenes smoothly. (With
iPhones, you may need to switch on Experimental Features in the Safari settings, however.)

Proper pro kit

Gaming headsets are a bit different, since they have a built-in screen in the headset, and – in the case of the Oculus Go and Quest – an Android computer in there as well. Tethered headsets use the power of a connected computer to generate the display, and all of them use a slightly different
Three.js system from the cheaper viewers to generate the 3D display.

As time goes on, it’s likely that more mobile phones will be compatible with
the VR software used by the untethered gaming headsets. Gaming headsets also have sensors that track your movement as well as the tilt of the headset, providing six degrees of freedom.

Get the rest of the tutorial in Wireframe #44

This is just a taste of the comprehensive guide included in the latest issue of Wireframe magazine. If you’re not a subscriber, you can download a PDF copy for free from the Wireframe magazine website. Start at page 50 and work your way through to create your own VR shooter game.

And if you want to take advantage of Wireframe magazine’s latest subscription deal, you can get it for just £10 at the official Raspberry Pi Press online store.

The post Make your own virtual reality 3D Shooter appeared first on Raspberry Pi.

AI-Man: a handy guide to video game artificial intelligence

Post Syndicated from Ryan Lambie original https://www.raspberrypi.org/blog/ai-man-a-handy-guide-to-video-game-artificial-intelligence/

Discover how non-player characters make decisions by tinkering with this Unity-based Pac-Man homage. Paul Roberts wrote this for the latest issue of Wireframe magazine.

From the first video game to the present, artificial intelligence has been a vital part of the medium. While most early games had enemies that simply walked left and right, like the Goombas in Super Mario Bros., there were also games like Pac-Man, where each ghost appeared to move intelligently. But from a programming perspective, how do we handle all the different possible states we want our characters to display?

Here’s AI-Man, our homage to a certain Namco maze game. You can switch between AI types to see how they affect the ghosts’ behaviours.

For example, how do we control whether a ghost is chasing Pac-Man, or running away, or even returning to their home? To explore these behaviours, we’ll be tinkering with AI-Man – a Pac-Man-style game developed in Unity. It will show you how the approaches discussed in this article are implemented, and there’s code available for you to modify and add to. You can freely download the AI-Man project here. One solution to managing the different states a character can be in, which has been used for decades, is a finite state machine, or FSM for short. It’s an approach that describes the high-level actions of an agent, and takes its name simply from the fact that there are a finite number of states from which to transition between, with each state only ever doing one thing.

Altered states

To explain what’s meant by high level, let’s take a closer look at the ghosts in Pac-Man. The highlevel state of a ghost is to ‘Chase’ Pac-Man, but the low level is how the ghost actually does this. In Pac-Man, each ghost has its own behaviour in which it hunts the player down, but they’re all in the same high-level state of ‘Chase’. Looking at Figure 1, you can see how the overall behaviour of a ghost can be depicted extremely easily, but there’s a lot of hidden complexity. At what point do we transition between states? What are the conditions on moving between states across the connecting lines? Once we have this information, the diagram can be turned into code with relative ease. You could use simple switch statements to achieve this, or we could achieve the same using an object-oriented approach.

Figure 1: A finite state machine

Using switch statements can quickly become cumbersome the more states we add, so I’ve used the object-oriented approach in the accompanying project, and an example code snippet can be seen in Code Listing 1. Each state handles whether it needs to transition into another state, and lets the state machine know. If a transition’s required, the Exit() function is called on the current state, before calling the Enter() function on the new state. This is done to ensure any setup or cleanup is done, after which the Update() function is called on whatever the current state is. The Update()function is where the low-level code for completing the state is processed. For a project as simple as Pac-Man, this only involves setting a different position for the ghost to move to.

Hidden complexity

Extending this approach, it’s reasonable for a state to call multiple states from within. This is called a hierarchical finite state machine, or HFSM for short. An example is an agent in Call of Duty: Strike Team being instructed to seek a stealthy position, so the high-level state is ‘Find Cover’, but within that, the agent needs to exit the dumpster he’s currently hiding in, find a safe location, calculate a safe path to that location, then repeatedly move between points on that path until he reaches the target position.

FSMs can appear somewhat predictable as the agent will always transition into the same state. This can be accommodated for by having multiple options that achieve the same goal. For example, when the ghosts in our Unity project are in the ‘Chase’ state, they can either move to the player, get in front of the player, or move to a position behind the player. There’s also an option to move to a random position. The FSM implemented has each ghost do one of these, whereas the behaviour tree allows all ghosts to switch between the options every ten seconds. A limitation of the FSM approach is that you can only ever be in a single state at a particular time. Imagine a tank battle game where multiple enemies can be engaged. Simply being in the ‘Retreat’ state doesn’t look smart if you’re about to run into the sights of another enemy. The worst-case scenario would be our tank transitions between ‘Attack’ and ‘Retreat’ states on each frame – an issue known as state thrashing – and gets stuck, and seemingly confused about what to do in this situation. What we need is away to be in multiple states at the same time: ideally retreating from tank A, whilst attacking tank B. This is where fuzzy finite state machines, or FFSM for short, come in useful.

This approach allows you to be in a particular state to a certain degree. For example, my tank could be 80% committed to the Retreat state (avoid tank A), and 20% committed to the Attack state (attack tank B). This allows us to both Retreat and Attack at the same time. To achieve this, on each update, your agent needs to check each possible state to determine its degree of commitment, and then call each of the active states’ updates. This differs from a standard FSM, where you can only ever be in a single state. FFSMs can be in none, one, two, or however many states you like at one time. This can prove tricky to balance, but it does offer an alternative to the standard approach.

No memory

Another potential issue with an FSM is that the agent has no memory of what they were previously doing. Granted, this may not be important: in the example given, the ghosts in Pac-Man don’t care about what they were doing, they only care about what they are doing, but in other games, memory can be extremely important. Imagine instructing a character to gather wood in a game like Age of Empires, and then the character gets into a fight. It would be extremely frustrating if the characters just stood around with nothing to do after the fight had concluded, and for the player to have to go back through all these characters and reinstruct them after the fight is over. It would be much better for the characters to return to their previous duties.

“FFSMs can be in one, none,

two, or however many states

you like.”

We can incorporate the idea of memory quite easily by using the stack data structure. The stack will hold AI states, with only the top-most element receiving the update. This in effect means that when a state is completed, it’s removed from the stack and the previous state is then processed. Figure 2 depicts how this was achieved in our Unity project. To differentiate the states from the FSM approach, I’ve called them tasks for the stackbased implementation. Looking at Figure 2, it shows how (from the bottom), the ghost was chasing the player, then the player collected a power pill, which resulted in the AI adding an Evade_Task – this now gets the update call, not the Chase_Task. While evading the player, the ghost was then eaten.

At this point, the ghost needed to return home, so the appropriate task was added. Once home, the ghost needed to exit this area, so again, the relevant task was added. At the point the ghost exited home, the ExitHome_Task was removed, which drops processing back to MoveToHome_Task. This was no longer required, so it was also removed. Back in the Evade_Task, if the power pill was still active, the ghost would return to avoiding the player, but if it had worn off, this task, in turn, got removed, putting the ghost back in its default task of Chase_Task, which will get the update calls until something else in the world changes.

Figure 2: Stack-based finite state machine.

Behaviour trees

In 2002, Halo 2 programmer Damian Isla expanded on the idea of HFSM in a way that made it more scalable and modular for the game’s AI. This became known as the behaviour tree approach. It’s now a staple in AI game development. The behaviour tree is made up of nodes, which can be one of three types – composite, decorator, or leaf nodes. Each has a different function within the tree and affects the flow through the tree. Figure 3 shows how this approach is set up for our Unity project. The states we’ve explored so far are called leaf nodes. Leaf nodes end a particular branch of the tree and don’t have child nodes – these are where the AI behaviours are located. For example, Leaf_ExitHome, Leaf_Evade, and Leaf_ MoveAheadOfPlayer all tell the ghost where to move to. Composite nodes can have multiple child nodes and are used to determine the order in which the children are called. This could be in the order in which they’re described by the tree, or by selection, where the children nodes will compete, with the parent node selecting which child node gets the go-ahead. Selector_Chase allows the ghost to select a single path down the tree by choosing a random option, whereas Sequence_ GoHome has to complete all the child paths to complete its behaviour.

Code Listing 2 shows how simple it is to choose a random behaviour to use – just be sure to store the index for the next update. Code Listing 3 demonstrates how to go through all child nodes, and to return SUCCESS only when all have completed, otherwise the status RUNNING is returned. FAILURE only gets returned when a child node itself returns a FAILURE status.

Complex behaviours

Although not used in our example project, behaviour trees can also have nodes called decorators. A decorator node can only have a single child, and can modify the result returned. For example, a decorator may iterate the child node for a set period, perhaps indefinitely, or even flip the result returned from being a success to a failure. From what first appears to be a collection of simple concepts, complex behaviours can then develop.

Figure 3: Behaviour tree

Video game AI is all about the illusion of intelligence. As long as the characters are believable in their context, the player should maintain their immersion in the game world and enjoy the experience we’ve made. Hopefully, the approaches introduced here highlight how even simple approaches can be used to develop complex characters. This is just the tip of the iceberg: AI development is a complex subject, but it’s also fun and rewarding to explore.

Wireframe #43, with the gorgeous Sea of Stars on the cover.

The latest issue of Wireframe Magazine is out now. available in print from the Raspberry Pi Press onlinestore, your local newsagents, and the Raspberry Pi Store, Cambridge.

You can also download the PDF directly from the Wireframe Magazine website.

The post AI-Man: a handy guide to video game artificial intelligence appeared first on Raspberry Pi.