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 } }.
import { apply } from '@kiranpg/goban';
board.onIntent(action => apply(board.state, action));What the handler returns decides what the board does:
| The handler returns | The board |
|---|---|
| An ok result | Shows the game in it. |
| A refusal | Shows the refusal's message under the board and changes nothing. |
| Nothing, or a promise | Changes 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:
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:
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.
onIntentis asked before a change, and only for what people do on the board.onChangeis told after every change. Its event'ssourceis'user'for a person's input and'api'forboard.show. For user changes it also includes theaction.
const stop = board.onChange((game, { source, action }) => {
console.log(source, action?.type, game.moveNumber);
});
stop(); // stops listeningShowing the game that's already shown does nothing and doesn't call onChange.