Storing Game State - UQcsse3200/2023-studio-2 GitHub Wiki

The GameState service represents the current state of a game and facilitates state transitions in a thread-safe way. It also provides a mechanism for registering and notifying listeners when the state changes.

Usage

1. Import the GameState

Import the GameState class into your Java project:

import com.csse3200.game.services.GameState;

2. Initialising the GameState:

Initialise and access the GameState service:

GameState gameState = new GameState();

3. Updating State Data:

You can directly set the state data using the put method:

gameState.put("score", 100);
gameState.put("planet", "Mars");

Every put operation to the game state triggers a state change callback, notifying registered listeners.

4. Retrieving State Data:

To retrieve the current state data, use the get method.

Object score = gameState.get("score");

5. Registering State Change Listeners:

To be notified when the state changes, register listeners by implementing the StateChangeListener interface and overriding the onStateChange method:

GameState.StateChangeListener listener = newStateData -> {
    // Perform actions based on the new state data
    int newScore = (int) newStateData.get("score");
    String planet = (String) newStateData.get("planet");
    // ...
};

gameState.registerStateChangeListener(listener);

6. Unregistering State Change Listeners:

Unregister a listener if you no longer need to listen to state changes:

gameState.unregisterStateChangeListener(listener);

With these steps, you can use GameState to keep track of the current state of your game and react to state changes with the registered listeners.