Sunday, February 13, 2011

Flash Game Dev Tip #1 – Creating a cross-game communications structure

Flash Game Dev Tip #1 – Creating a cross-game communications structure:

Flash Game Dev Tips

Tip #1 – Flixel – Creating a cross-game communications structure

As moderator of the flixel forums there is one question I see time and time again. It starts something like this: “how can I make X talk to Y, especially when the State changes?”. The problem is a classic OOP one, and thankfully there is a classic OOP approach to solving it. Have a look at the following diagram:

Game state diagram

Here we have part of a mock-up Game State structure for an RPG game. As part of the state you can see the Player, an Enemy Manager, an Inventory (which both Player and Enemy can share) and a Map consisting of several important locations.

Of course this is just a rough-example, so don’t get bogged down in the semantics or structure of it. Instead think about how inter-dependant all of these objects are on each other.

  • For example perhaps the Temple won’t allow the Player to enter if he is carrying a weapon.
  • What if when fighting the Thief you win, but he steals a Potion from your Inventory before running away.
  • Perhaps the enemy wouldn’t even attack you if he realised what Sword you were carrying?
  • A Wizard casts a fireball at you. How much of the damage does your Armour repel?

In all but the most simple of games it’s vital that your game objects can communicate with each other. And communicate effectively.

When you create your Game State you could first make the Player object, and then pass a reference of that into say the Enemy Manager, so the baddies it creates can check out your vital stats prior to attack. But passing references around like this gets messy, and it’s all too easy to leave “open ends” that don’t get cleared up as needed. In a worse-case scenario they could leak memory and crash Flash Player. And in a “best case” they just confuse you during development.

One Ring to Rule Them All

My suggestion is to use a Registry. A Registry is “A well-known object that other objects can use to find common objects and services.” (Martin Fowler, P of EAA) – sounds ideal, right?

They are extremely easy to create too. In your Project create a file called Registry.as – Here is an example file based on the structure above: [...]

No comments:

Post a Comment