Skip to content

Controlled boards ​

By default a board applies what people do on it itself: a click plays a stone. A controlled board doesn't. It hands you each action, and shows whatever you decide.

Use a controlled board when something other than the board decides what happens: a server that checks moves, an online game where it might not be this person's turn, or an app that keeps the game in its own state.

Take control ​

Pass a handler to onIntent. It receives an Action, such as { type: 'play', point: { x: 3, y: 3 } }.

js
import { apply } from '@kiranpg/goban';

board.onIntent(action => apply(board.state, action));

What the handler returns decides what the board does:

The handler returnsThe board
An ok resultShows the game in it.
A refusalShows the refusal's message under the board and changes nothing.
Nothing, or a promiseChanges nothing. You can show a game later with board.show, so an async handler works too.

The example above behaves exactly like an uncontrolled board. Its point is that you can change it.

Examples ​

Ignore clicks when it isn't this person's turn:

js
board.onIntent(action => {
  if (action.type === 'play' && board.state.toPlay !== myColor) return;
  return apply(board.state, action);
});

Send moves to a server and show what it sends back:

js
import { openSgf } from '@kiranpg/goban';

board.onIntent(action => {
  socket.send(JSON.stringify(action));
  // Return nothing: the board waits for the server.
});

socket.addEventListener('message', event => {
  const result = openSgf(event.data, { mode: 'play' });
  if (result.ok) board.show(result.game);
});

Give control back ​

onIntent(null) makes the board uncontrolled again. A board has one handler at a time; setting a new one replaces the old.

onChange and onIntent ​

They do different jobs, and you can use both.

  • onIntent is asked before a change, and only for what people do on the board.
  • onChange is told after every change. Its event's source is 'user' for a person's input and 'api' for board.show. For user changes it also includes the action.
js
const stop = board.onChange((game, { source, action }) => {
  console.log(source, action?.type, game.moveNumber);
});

stop(); // stops listening

Showing the game that's already shown does nothing and doesn't call onChange.

Released under the MIT License.