Dealing with Actions, Commands, and Model Data in UTiny

Overview

There is very little difference in the methods used to send and receive actions and commands in the P2 and P3 models. The difference is that, when using P2, commands can only be sent by the hosts, while in P3, commands can be sent by both hosts and clients. This allows clients to also set global model data.

Actions and Commands

Actions and commands stay the same as when using the P2 model, except they can now be sent from the clients, and actions are sent to the client devices too. Direct client-to-client messages are not yet supported, although they are simulated by the client sending a message to the host, which is then distributed to all the other clients.

Registering

Before actions and commands can be sent, they need to be registered. This is done in the following manner:

  • Actions are registered like so: TableRealmsTiny.Actions.RegisterAction("start", StartGame);
    • “start” is the name of the action, and “StartGame” is the function that needs to be called when the “start” action is triggered.
  • Commands are registered like so: TableRealmsTiny.P2PManager.RegisterGameCommand("setup", GameSetup);

Sending

Once the actions and commands have been registered in the game file, they are sent in the following manner:

  • Actions are sent from the Lua by using SendAction("name", arg1, arg2, arg_etc);
  • Commands are sent within the game script using the following API call: TableRealmsTiny.P2PManager.SendGameCommand("setup", "");

Model Data

Listening for Changes

You may want to use changes to model data as a trigger for certain functions. In order to detect those changes to the data, a model change listener needs to be set up.

TableRealmsTiny.Model.AddListener("game.state", GameStateChanged);

When the listener detects a change in the value of the key, it will call the callback.

Getting and Setting Data

Setting

Setting the model data is as simple as calling the SetData(); function within your UTiny project.

TableRealmsTiny.Model.SetData(key,value, true);

The condition “True” is used to force the update. If it is not set to “True”, it wont send all the events and other data if the values have not been changed.

Getting

Much like setting model data, to retrieve data from the model all you need is to call a GetData(); function within your UTiny project.

let gameOver = TableRealmsTiny.Model.GetData("key.key");