Skip to content

Make a move ​

A click on a square now sends the move to the world and Otto answers with a move of his own.

A move: a message or an action? ​

Your view can reach a world in two ways: (1) with a message (world.send) or (2) with one of the actions that its rules offer (world.act). Each world decides which of the two it takes for each kind of input.

In Crosses a move is a message whose text is the number of a square. A message fits a move for three reasons: (1) it carries a value (the square), (2) it can arrive at any time and (3) it appears in the conversation. Crosses keeps actions for the steps of the game itself such as starting a new round (step 5).

Another world could take a move as an action with the square in its arguments (world.act('play', { square: 5 })). To learn the form in which a world expects a move, ask its owner or read what its rules offer in now.actions.

Send the square ​

A click on a square sends its number:

jsx
const canPlay = world.data.turn === world.myRole && world.canSend;
// ...
<button
  disabled={!canPlay || mark !== ''}
  onClick={() => world.send(String(index + 1))}
>

canPlay is true when it is the turn of the person and the rules accept a message (canSend). A square is disabled when canPlay is false or when the square already holds a mark. The fake world checks the move as well and answers a move out of turn or on a taken square with "You cannot play there now."

Otto answers ​

The fake world plays Otto. Its board and its turn are now variables read by the functions in data in the same way as in Tutorial 1:

js
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';
// ...
data: {
  board: { every: 200, value: rows },
  turn: { every: 200, value: () => turn },
},

rows() splits the nine squares into three rows. onMessage puts the X on the square, gives the turn to Otto, waits 600 ms, puts his O and gives the turn back:

js
onMessage: async (message) => {
  const index = Number(message.text) - 1;
  if (turn !== 'X' || squares[index] !== '') return 'You cannot play there now.';
  squares[index] = 'X';
  const answer = ottoSquare();
  if (answer === undefined) return 'The board is full.';
  turn = 'O';
  await wait(600); // Otto thinks
  squares[answer] = 'O';
  turn = 'X';
  return `Otto plays square ${answer + 1}. Your turn.`;
},

onMessage can be async. The fake world then awaits its Promise and replies with the string it resolves to. During the 600 ms turn is 'O', the view shows "Otto is thinking…" and every square is disabled. Otto takes the first free square in a fixed order that starts from the middle and continues with the corners. Nobody wins yet because the world looks for three in a row only from step 4 on.

What the world said last ​

Under the board the view shows the last message that does not come from the person:

jsx
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return <p>{last ? last.text : 'Choose a square to play.'}</p>;

The code ​

The new lines are highlighted. Play a square to see the answer of Otto.

jsx
import { useWorld } from './useWorld.js';

// A fake world to build with, a game of tic-tac-toe that needs no account and no network.

// What changes in the fake world. The view reads it through `data`.
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';

// The board as rows of three, the way a world shows a grid.
function rows() {
	return [squares.slice(0, 3), squares.slice(3, 6), squares.slice(6, 9)];
}

// Otto's move: the first free square he likes, the center first.
function ottoSquare() {
	return [4, 0, 2, 6, 8, 1, 3, 5, 7].find((index) => squares[index] === '');
}

// Waits a little, as if Otto were thinking.
function wait(ms) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

const crosses = {
	name: 'Crosses',
	profile: { description: 'Tic-tac-toe: three in a row wins.' },
	// What the world shows, by name, given by functions that let the view see each move.
	data: {
		// The board: three rows of three squares.
		board: { every: 200, value: rows },
		// Whose turn it is: the role that plays now.
		turn: { every: 200, value: () => turn },
	},
	// Who is in the world: Otto, a fake agent who plays O. The person plays X.
	members: [{ name: 'Otto', role: 'O' }],
	roles: [
		{ name: 'X', description: 'Plays crosses, and moves first.' },
		{ name: 'O', description: 'Plays noughts.' },
	],
	myRole: 'X',
	// A move is a message: the number of a square, from 1 to 9. Otto answers with his own.
	onMessage: async (message) => {
		const index = Number(message.text) - 1;
		if (turn !== 'X' || squares[index] !== '') return 'You cannot play there now.';
		squares[index] = 'X';
		const answer = ottoSquare();
		if (answer === undefined) return 'The board is full.';
		turn = 'O';
		await wait(600); // Otto thinks
		squares[answer] = 'O';
		turn = 'X';
		return `Otto plays square ${answer + 1}. Your turn.`;
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: crosses } });

	// The three states of every view: it failed, it is connecting, it is here.
	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	return (
		<main>
			<h1>{world.name}</h1>
			<p>{world.profile.description}</p>
			<Players world={world} />
			<Board world={world} />
			<LastMessage world={world} />
		</main>
	);
}

// Who plays what and whose turn it is.
function Players({ world }) {
	const opponent = opponentOf(world);
	const isMyTurn = world.data.turn === world.myRole;
	return (
		<>
			<p>
				You play {world.myRole}. {opponent ? `${opponent.name} plays ${opponent.role}.` : 'Waiting for a second player.'}
			</p>
			<p>
				<strong>{isMyTurn ? 'Your turn.' : `${opponent?.name ?? 'The other player'} is thinking…`}</strong>
			</p>
		</>
	);
}

// The other player: the member whose role is not the person's.
function opponentOf(world) {
	return world.members?.find((member) => member.role !== world.myRole) ?? null;
}

// The board from the data of the world: nine squares, numbered 1 to 9 row by row.
function Board({ world }) {
	// Until the world sends its board, the squares are empty.
	const marks = world.data.board?.flat() ?? ['', '', '', '', '', '', '', '', ''];
	// The person plays on their turn, when the rules let them send. A move is a message with the number of the square.
	const canPlay = world.data.turn === world.myRole && world.canSend;
	return (
		<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 72px)', gap: 6 }}>
			{marks.map((mark, index) => (
				<button
					key={index}
					aria-label={`Square ${index + 1}, ${mark || 'empty'}`}
					disabled={!canPlay || mark !== ''}
					onClick={() => world.send(String(index + 1))}
					style={{ height: 72, fontSize: 32, fontWeight: 700, color: mark === 'X' ? '#3b82f6' : '#ef4444' }}
				>
					{mark}
				</button>
			))}
		</div>
	);
}

// The last message of the world: Otto's move, or why a move was refused.
function LastMessage({ world }) {
	const last = world.messages.filter((message) => !message.fromMe).at(-1);
	return <p>{last ? last.text : 'Choose a square to play.'}</p>;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with, a game of tic-tac-toe that needs no account and no network.

// What changes in the fake world. The view reads it through `data`.
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';

// The board as rows of three, the way a world shows a grid.
function rows() {
	return [squares.slice(0, 3), squares.slice(3, 6), squares.slice(6, 9)];
}

// Otto's move: the first free square he likes, the center first.
function ottoSquare() {
	return [4, 0, 2, 6, 8, 1, 3, 5, 7].find((index) => squares[index] === '');
}

// Waits a little, as if Otto were thinking.
function wait(ms) {
	return new Promise((resolve) => setTimeout(resolve, ms));
}

const crosses = {
	name: 'Crosses',
	profile: { description: 'Tic-tac-toe: three in a row wins.' },
	// What the world shows, by name, given by functions that let the view see each move.
	data: {
		// The board: three rows of three squares.
		board: { every: 200, value: rows },
		// Whose turn it is: the role that plays now.
		turn: { every: 200, value: () => turn },
	},
	// Who is in the world: Otto, a fake agent who plays O. The person plays X.
	members: [{ name: 'Otto', role: 'O' }],
	roles: [
		{ name: 'X', description: 'Plays crosses, and moves first.' },
		{ name: 'O', description: 'Plays noughts.' },
	],
	myRole: 'X',
	// A move is a message: the number of a square, from 1 to 9. Otto answers with his own.
	onMessage: async (message) => {
		const index = Number(message.text) - 1;
		if (turn !== 'X' || squares[index] !== '') return 'You cannot play there now.';
		squares[index] = 'X';
		const answer = ottoSquare();
		if (answer === undefined) return 'The board is full.';
		turn = 'O';
		await wait(600); // Otto thinks
		squares[answer] = 'O';
		turn = 'X';
		return `Otto plays square ${answer + 1}. Your turn.`;
	},
};

// The page: one element that holds the whole view.
const page = document.createElement('main');
page.textContent = 'Connecting…';
document.body.append(page);

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: crosses } });
page.textContent = '';
header(page, world);
players(page, world);
board(page, world);
lastMessage(page, world);

// The name of the world and what it is.
function header(container, world) {
	const title = document.createElement('h1');
	const about = document.createElement('p');
	container.append(title, about);

	// Called at once, then after every change of the world.
	return world.subscribe((node) => {
		title.textContent = node.name;
		about.textContent = node.profile.description ?? '';
	});
}

// Who plays what and whose turn it is.
function players(container, world) {
	const roles = document.createElement('p');
	const turn = document.createElement('p');
	turn.style.fontWeight = 'bold';
	container.append(roles, turn);

	return world.subscribe((node) => {
		const opponent = opponentOf(node);
		const isMyTurn = node.data.turn === node.myRole;
		roles.textContent = `You play ${node.myRole}. ${opponent ? `${opponent.name} plays ${opponent.role}.` : 'Waiting for a second player.'}`;
		turn.textContent = isMyTurn ? 'Your turn.' : `${opponent?.name ?? 'The other player'} is thinking…`;
	});
}

// The other player: the member whose role is not the person's.
function opponentOf(node) {
	return node.members?.find((member) => member.role !== node.myRole) ?? null;
}

// The board from the data of the world: nine squares, numbered 1 to 9 row by row.
function board(container, world) {
	const grid = document.createElement('div');
	grid.style.cssText = 'display: grid; grid-template-columns: repeat(3, 72px); gap: 6px';
	// The nine squares are made once, and every change of the world writes their marks.
	const squares = [];
	for (let index = 0; index < 9; index += 1) {
		const square = document.createElement('button');
		square.style.cssText = 'height: 72px; font-size: 32px; font-weight: 700';
		// A move is a message to the world with the number of the square.
		square.onclick = () => world.send(String(index + 1));
		squares.push(square);
	}
	grid.append(...squares);
	container.append(grid);

	return world.subscribe((node) => {
		// Until the world sends its board, the squares are empty.
		const marks = node.data.board?.flat() ?? [];
		// The person plays on their turn, when the rules let them send.
		const canPlay = node.data.turn === node.myRole && node.canSend;
		squares.forEach((square, index) => {
			const mark = marks[index] ?? '';
			square.textContent = mark;
			square.setAttribute('aria-label', `Square ${index + 1}, ${mark || 'empty'}`);
			square.style.color = mark === 'X' ? '#3b82f6' : '#ef4444';
			square.disabled = !canPlay || mark !== '';
		});
	});
}

// The last message of the world: Otto's move, or why a move was refused.
function lastMessage(container, world) {
	const line = document.createElement('p');
	container.append(line);

	return world.subscribe((node) => {
		const last = node.messages.filter((message) => !message.fromMe).at(-1);
		line.textContent = last ? last.text : 'Choose a square to play.';
	});
}
Live, on a fake world
Open

Next steps ​

Step 4: The winner ends the round on three in a row or on a full board and shows the result.

Messages and actions are described in Messages and questions and The actions the rules offer. The recipe A fake world that changes over time shows other ways to make a fake world change.

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.