Sub-game Interaction

Creating SubClient Instances

As mentioned in the SubClient section, sub-games are child games launched and managed by the main game. To interact with a sub-game on the client side, you need to create a SubClient instance.

The subClient function of the AppClient allows you to do this. It takes two arguments:

  • subId: The unique identifier of the sub-game you want to connect to.

  • onEvent: A callback function that will be invoked whenever an event occurs within the sub-game.

Here's an example of creating a SubClient instance:

// Assuming appClient is an initialized AppClient instance

const subId = 1; // Replace with your sub-game ID

const subClient = await appClient.subClient({
  subId,
  onEvent: (context, state, event) => {
    // Handle sub-game events here
  },
});

Sending Events and Managing State

Once you have a SubClient instance, you can use its functions to interact with the sub-game in a similar way as you would with the AppClient for the main game. This includes:

  • Submitting custom events: Use the submitEvent function of the SubClient to send custom events representing player actions within the sub-game.

  • Handling events: Register callback functions using the onEvent function of the SubClient to react to incoming events and update the sub-game UI accordingly.

  • Accessing game context and state: Use the gameContext property of the SubClient to access the sub-game's state information and display it in the UI.

Here's an example of sending an event and managing state within a sub-game:

// Assuming subClient is an initialized SubClient instance

// Submit a custom event to the sub-game
subClient.submitEvent({
  type: 'subGameAction',
  playerId: 2n,
  action: 'movePiece',
});

// Handle incoming events from the sub-game
subClient.onEvent((context, state, event) => {
  if (event instanceof Custom) {
    // Handle custom sub-game events
  } else if (event instanceof GameStart) {
    // Update UI to indicate sub-game has started
  }
});

// Access the sub-game context to display state information
const subGameContext = subClient.gameContext;
const currentSubGameStage = subGameContext.stage;

// Update the sub-game UI based on the current stage

By utilizing the SubClient and its functionalities, developers can build client-side applications that seamlessly interact with both the main game and its sub-games, enabling complex and dynamic gameplay experiences within the Race Protocol framework.

Last updated