Wednesday, June 24, 2009

AI - Planner Approach


There are may ways of coding the AI for a game, each game definitely needs it's custom made AI but that doesn't mean that there aren't certain patterns to apply for similar AI in different games.

The technique I'm about to expose is primarily focused for strategy games of a reduced scope, but works wonders in them. It's basically a Planner with 3 distinct levels to control the global AI of the game (NOT the specific units).

The beauty of the system is that it's simple, elegant and robust. Simple because each module is simple. Elegant because the interaction of the simple elements makes a complex behavior, and robust because adding or modifying the game design at any level has no impact whatsoever on the general AI architecture, only in the corresponding module.

Overview:

The technique consists of 3 levels.
First there is the data generators, that calculate all the data the planner needs. Then there is the actual planner, who calculates the probability of executing each action and calls them. Finally there are the individual actions, that produce different results based on the actual game situation.

The above diagram shows an example of the Planner strategy.

A PlayerAI class has references to external data (player and map), the blue methods are data generators, the red object is the planner, and the yellow objects are actions.

Data generators:
These are usually part of the general AI class, and game specific (you won't change throughout the game because they provide general info of the game the AI needs, regardless of the actual situation).
 

In the example:

They provide two datum. The % of the battle that is won (to know if the AI is wining and must press the advantage being aggressive, or is losing and must quickly rally to defend) which it calculates from the number of units, defenses and overall power of both contestants. The budget the AI can spend in that turn, cause in the beginning of the game it can spend freely to create cheap units, but later on it needs to save up to create more powerful ones.

Planners:

The planner is a object the AI has. A base Planner class exists to derive different planners from, and could look something like this:

It's the planner's job to decide what to do, and here is how it goes about it.

Creation:

For each kind of scenario we have a different planner, specified in the external game data files. When we load a PlayerAI data file, we create a specific Planner object specified in that file.

In the example:
We have a PlayerAI xml file with this structure:


So we would create for our playerAI a new Planner of type "somePlanner".
Then for each Action assigned to the Planner in the data file, we create a new Action object of type "T" and add it to the planner's action vector, with it's corresponding base percentage, which represents the probability of choosing that particular action.

In the example:
We would create a Order, CastSpell, CreateUnit, CreateBuilding and Wait actions and add them to m_vActions.

Execution:

Each time the AI updates, we update the Planner passing it the data provided by the data generators. Taking those into account, it calculates the new % of choosing each action, from their base %.

Now, knowing what the chances are of executing each action, it chooses those most probable ones and executes them.
 

In the example:
We would get the BattleStatus and Budget, and for each of the 5 actions, update their probability of being executed according to how much money we have and wherever we are winning the battle or not.

 

Actions:

All the actions are objects that take the same parameters, and provide some sort of output to the rest of the game system.
They are modular, so you can add new actions, remove actions (changing the xml file of that planner) or modify particular actions (changing the code of that particular action class) and the rest of the system never needs to know.
 

In the example:
The Order action tells units to attack, stop or retreat, depending on the BattleStatus. The Create Units action chooses one unit or another depending on the need for offensive or defensive units. ... Finally the Wait action puts the AI on idle, so it doesn't do anything.

Notes:

The Planners and actions are implemented by a base Planner (or Action) class and derived classes for each specific Planner (or action) and using those by polymorphism.

A Player AI class might look something like this:

Friday, June 12, 2009

Engine vs. Game

When immersed in amateur game programming, there's 2 ways to go. The game of the game-making, or getting skill points on engine programming.

There's plenty of strong opinions of what's better and what's not, but the truth is they both have their strong points and appeals for the beginner programmer, this must be so, or else natural selection would have claimed one of these two ways long ago.

As for what I think...

Before going in depth on either of them, I'll do a fast forward and give the definite answer to life, the universe, and everything:

Whatever you have most fun making.

That's one of the few pros of being an amateur, you can actually code just for fun, whatever goes your way. Putting that aside, lets have a look at some real arguments:

Engine:

Pros:
  • You learn, not more (quantity of knowledge is in direct correlation to, basically, quantity of work, wherever making engines or games), but more basic. You go down a deeper level and fight with elemental bugs. As with everything in life, the more you work on the basics, the more skill you'll achieve in the long run.
  • You get a head's up on engine design and architecture, which will make using any 3rd party engine much easier, cause after figuring out the logical way to design that entity class, you won't be surprised when you find a physx::Actor and see some of the physical methods you did for your engine.
  • As you probably won't be writing the whole engine from the most basic level (bliting pixels to screen using hardware functionality for example, is too basic level) you'll get the hang of a lot of auxiliar libraries. Maybe opengl for gfx, tinyXML for those weapon data files you wanted, or sdlMixer for making your speakers blast some sound.

Cons:
  • Its boring, up to a degree. Sure, you always have the hard-core programmer's joy of implementing a new feature here, tweaking a system there, but there's always a point when not seeing results starts eroding morale. It's not too bad per-se, but it can quickly kill a project, and that is something to be avoided.
  • It's harder, which to some translates to boring, which takes us to the above logic.
  • When all is said and done, you actually have nothing to show. No game here to play and show of to family and friends, nothing visible to put on your portfolio.

Game:

Pros:
  • You learn to make a game, which is a obscure science that no one can teach. Something like illumination, but with a lot more networking involved.
  • You have a shinny new gem to add to your portfolio, and to impress chicks at bars (well, some chicks, at some bars at least).
  • You get your hands dirty with a full featured engine, and learn from their design and their functionality.
  • It's easier, and faster, make that much much faster.
  • You have things visible from near the start, and there is nothing for keeping morale up like seeing little everyday improvements to your project.
  • It gives you security, as you finish one game after another, and that in turn makes you push a bit further, take bigger challenges.

Cons:
  • Half the work is done already. So that's one part you won't be needing to sweat, but it's also a part you're not gonna learn how it works.

Conclusion:
The above is my personal experience, so the conclusion will be my personal advice:

Make some games, get the feel of some engines, see what works and what doesn't. Those structures and systems you build time and again (entity manager, log system, menu state machine, any of those ring a bell?) save them up and re-utilize them from game to game, that way you'll be making them generic.

When you've done that, make an engine. Learn from the bottom up, get a paper tablecloth and sketch a full blown design of the engine, and implement it with care and dedication.

That over with, get back to making games, and if the engine works fine, remember to release it to the nice folks of the interwebs, so we can learn from you!

Wednesday, June 10, 2009

Game - Phagocitosis


Phagocitosis is a 1 week, simple, small puzzle game I created some months back.

It was developed in ActionScript with Adobe Flash CS4, using the KeyObject library as the only external help. A friend proposed the subject and I couldn't resist the challenge of coding a game and learning a new IDE and language at the same time, so here's how I went about it.


Design:
The Game Design was informal and written in miscellaneous pieces of paper, napkins, and the back of envelopes. It was mainly done by my buddy Undi. It took several months of sporadic work to get the general idea working.

Once the game design was over with, the Investigation and Technical Design phases began, in parallel. As it happens with new technologies, you can't design the technical aspect until you know how they work, and you can't know what you need to investigate until you know what you need.
The result of that phase was this Technical Design Document (TDD), (well, actually a draft, it was a quick development so it didn't need detail) specked with investigation notes, and this list of references:
Also, some interesting book titles:
  • Game Development With ActionScript
  • Essential ActionScript 3.0

Development:
The very first thing you come to realize when jumping into the Flash bandwagon is that there's ActionScript 2.0 and ActionScript 3.0 and that alone can shoot everything to hell.
I chose AS 3.0 on the grounds that, tough it might have a smaller support base, for learning purposes it's always a good idea to go for the next thing, as technologies outdate incredibly fast in this field.

After a few false starts, getting Adobe Flash working and setting up a SVN got me ready to start coding.

The game was built based on 3 things, the scenario, the player (a slimy Amoeba) and the enemy (a simple hole, if you fell in, you died).

The scenario was set up as a series of keyframes in the main timeline of Adobe Flash, with each keyframe having an associated Enter, Execute and Exit functions, creating a Finite State Machine to provide for all the screens of the scenario.
Scenes:
  • Menu
  • Scene Selection
  • Play
  • Pause
  • Game Over
  • Game Won
And you can guess what each one represents ;)

Each scene had it's own challenges, but the 2 biggest ones were:
Making buttons: 5 out of the 6 Scenes needed buttons, and those introduced me to the world of callbacks in AS, coupled with event handling and corresponding objects from the IDE to code entities.
The map: I wanted to have a easy way to create new levels and add them, and as I was using mappy to generate xml files of the levels, it stood to reason I had to have a in-game xml interpreter that also had access to the tilemaps and rendered the complete map. Now that was fun.

And everywhere, I had to take out my magical photoshop and produce crappy graphic after crappy graphic to fill my scene. I tried for a simple animation of the Amoeba and failed dramatically, after which I gave up and focused on static gfx.

The Amoeba and the Hole:
Each of these elements had to move around the map without charging trough walls. The pixel perfect collision detection was a real bugger, even tough the game only has 4 directions available.

The Amoeba was player controlled, so it needed a bit of input-handling magic, which had me fighting key input for more than a few hours.
The Hole on the other hand, was AI driven, and it uses a special pathfinding approximation algorithm based on it's relative position to the amoeba, instead of going for a full pathfinding with Dijkstra or A*. Not too surprisingly, this hack, apart from making the game run MUCH faster, made it more fun, as you could bait the hole to come out of certain areas instead of just waiting for it to chase you.

Game Play and Map-Making:
Final logic was added, specifically:
  • Collision between Hole and Amoeba results on player death
  • Collision between player and Objective results on loading next map
  • Map loading and changing
  • Game Over and Game Win
  • Select scene (start the game from a specific map)
Map after map was produced (special thanks to my brother there) each with different challenges, and tweaked to make them have a smooth difficulty curve (tough different players disagree on that one).

The End:
Final touches where made on the last wee hours of the morning in the last day of the development week, and a html file created for quick play without having to payload it to a server.

The game can be found at the SVN, along with all the code. Or if you prefer, a direct download.

Enjoy!



Cocos2D iPhone Research

logo  Cocos2D is one of the top choices when choosing an iPhone game development engine, THE top choice if you're looking for something free. Works great in 2D and has one of the best scene graphs I’ve seen out there. 

First up, a list of interesting links to guide the efforts of the aspiring Cocos2D programmer.
 
For starters, here is monoclestudios. This company decided to give a little bit back to cocos2D, as a thanks for using it for one of their games writing a walk trough that explains how to get a Cocos2D project working.

Once you've got that over with, you still need some preparation before heading on the path to adding cocos2D to your basic arsenal. The class hierarchy of the documentation must be read carefully to get a general idea of the engine works. Making your synapses comprehend the connections between the different classes will give you a good foothold.

With that bit of theory as reference, you can now enjoy the wonderful article written by Will Larson, showing the idea of how to work with the basic pillars of Cocos2D. After that one, you should have enough idea of the engine to draft a basic game architecture.

What our life needs right now, apart of a nice cup of coffee, is a step-by-step, code spiced, dummy game, to show how everything actually works, and to provide some working code for us to play with. Start reading those articles from the bottom, you won't be disappointed. Of special interest, I would point out the detection of user input, physics with chipmunk and a custom made particle effect in that series of tutorials.

That's about it! With that nice collection you can get well on your way with your iPhone game coding skills.

Code hard and have fun!

Tuesday, June 9, 2009

The WHY.

This blog is, to be frank, just an excuse to record the knowledge acquired as a game programmer. Essays, documentation, projects, libraries... it all needs to be recorded somewhere so people can use it, and this is going to be that place.

It will be updated regularly every weekend, and sporadically as need arises.

I hope the arcane texts will be useful to all those who have the skill to read them :)