Writing the rulesΒΆ

  1. In tac-tac-toe, the only player action possible is for a player to place a token on the grid.
  • In the last section, we set up the board so that whenever the player clicks on a given board area, a message like place_token 00 will be sent to the backend.
  • To respond to this message, we need to define a receiver for this message like so:
RECEIVE place_token $position:
  ...
END_RECEIVE
  1. When the message place_token 00 is received, this receiver function will be executed, and $position will evaluate to 00 within the body of that function. For now, let’s leave the receiver definition blank, as we need to define how to set up the game first.
  2. set_up is a special function that is executed at the start of the game (if it exists). So far, we have defined the tokens but not instantiated them – all our containers from the initial state JSON are empty. If we want to be able to use the tokens during the game, we need to instantiate them first, and set_up is a good place to do so.
DEF set_up:
  INSTANTIATE_TOKEN 12 "x" 5 "x_tokens";
  INSTANTIATE_TOKEN 12 "o" 4 "o_tokens";
END_DEF

RECEIVE place_token $position:
  ACCEPT;
END_RECEIVE

Replace 12 with the tokenset id of the tokenset you created.

  1. At this point, you have the full skeleton of a tic-tac-toe game. You can create a game from your game spec, and when you click on a board area an appropriate message will be sent to the backend and processed. The only thing that remains is to add the correct logic to the place_token function.
  2. Anyone can click on any board area and trigger a place_token message. We need to check a few things:
  • the person clicking is the current turn player (ignore messages that are sent out of turn)
  • the position clicked is empty (someone has not already placed a token there)
  • if the above are satisfied, place a token into the indicated position and end this person’s turn

The following logic will accomplish this:

RECEIVE place_token $position:
  IF NOT EQUAL $PLAYER_NAME $CURRENT_PLAYER:
    REJECT "Not your turn";
  END_IF
  ASSIGN 'target' GET_CONTAINER $position;
  ASSIGN 'token_source' GET_CONTAINER CONCAT $CURRENT_PLAYER "_tokens";
  IF EQUAL SIZE $target 0:
    APPEND $target POP $token_source 0;
    ROTATE_PLAY_ORDER;
    ACCEPT;
  END_IF
  REJECT "Can't play there (non-empty)";
END_RECEIVE

For more details, see the LudL Language manual. A couple highlights:

At this point, you should be able to create a game of tic-tac-toe and be able to place tokens into the grid by clicking on the desired position.