Game And State - felipemanga/FemtoIDE GitHub Wiki

Summary

While not obligatory, femto.Game and femto.State are important classes for your Java games. Using them correctly will make it easier to port your games to other platforms in the future, and will help you avoid common pitfalls in the present.

Game Theory

All computer games have a some form of game loop. At its core, it often looks something like this:

while( running ){
  updateGame();
}

(You can't actually use a loop like this in HTML5, but femto.Game will take care of the difference for you in the future)

What that updateGame function does, depends on the games state. Here are some examples of common states in a game:

  • Splash screen
  • main menu
  • options screen
  • credits
  • level select
  • the actual game

When a game starts up, it does so in a default state, such as the Splash screen. Eventually a change is triggered, either by a timeout or a button press, the game switches to the main menu. And so on.

The State Machine is responsible for managing which state is currently active.

femto.State

The femto.State class doesn't do anything on its own:

public class State {
    public void preinit(){}
    public void init(){}
    public void update(){}
    public void shutdown(){}
}

The idea is that you extend it and override those methods.

They are called by the state machine when changing from one state to another:

  • preinit is called on the new state, before shutdown is called in the old state. This is only useful when you need to get some information from the old state.
  • shutdown is called when leaving a state. This can be used to free up memory by setting variables to null, leaving more memory available for the next state.
  • init is called when entering a state. Here, you can create objects knowing that the old state has cleaned up after itself.
  • update is called every frame. This is the heartbeat, or "tick", of the game.

femto.Game

The FemtoLib comes with a state machine class, femto.StateMachine. On its own, it doesn't do much. Instead, what you want is femto.Game, which extends femto.StateMachine, and actually does something useful: 1 - It is a singleton, so any state can access it easily: Game.changeState( otherState ); 2 - It contains the game loop. 3 - It comes with a menu state that appears when you press the reset button on the Pokitto.

Point 2 is important to you, the developer, as it will help you get your games on other platforms (such as HTML5 and PC) in the future.

Point 3 is important to the player. If you don't use femto.Game, there is no way for players to go into the loader and switch to another game.

Examples

The Hello Java example uses femto.Game and femto.State to demonstrate a single-state game/demo. For an example with multiple states, look at the Pokitto Intervalometer.