Fai una mossa
Adesso un clic su una casella invia la mossa al mondo e Otto risponde con una mossa sua.
Una mossa: un messaggio o un'azione?
La tua vista può raggiungere un mondo in due modi: (1) con un messaggio (world.send) o (2) con una delle azioni che le sue regole offrono (world.act). Ogni mondo decide quale dei due accetta per ogni tipo di input.
In Crosses una mossa è un messaggio il cui testo è il numero di una casella. Un messaggio si adatta a una mossa per tre motivi: (1) porta un valore (la casella), (2) può arrivare in qualsiasi momento e (3) compare nella conversazione. Crosses tiene le azioni per i passaggi del gioco vero e proprio come far partire una nuova partita (passo 5).
Un altro mondo potrebbe accettare una mossa come azione con la casella tra i suoi argomenti (world.act('play', { square: 5 })). Per sapere in che forma un mondo si aspetta una mossa, chiedilo al suo proprietario o leggi che cosa offrono le sue regole in now.actions.
Invia la casella
Un clic su una casella ne invia il numero:
const canPlay = world.data.turn === world.myRole && world.canSend;
// ...
<button
disabled={!canPlay || mark !== ''}
onClick={() => world.send(String(index + 1))}
>canPlay è true quando tocca alla persona e le regole accettano un messaggio (canSend). Una casella è disattivata quando canPlay è false o quando ha già un segno. Anche il mondo finto controlla la mossa e risponde "You cannot play there now." a una mossa fuori turno o su una casella occupata.
Otto risponde
Otto è giocato dal mondo finto. La sua griglia e il suo turno adesso sono variabili che le funzioni in data leggono allo stesso modo del Tutorial 1:
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';
// ...
data: {
board: { every: 200, value: rows },
turn: { every: 200, value: () => turn },
},rows() divide le nove caselle in tre righe. onMessage mette la X sulla casella, passa il turno a Otto, aspetta 600 ms, mette la sua O e restituisce il turno alla persona:
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 può essere async. In quel caso il mondo finto aspetta la sua Promise e risponde con la stringa con cui si risolve. Durante i 600 ms turn vale 'O', la vista mostra "Otto is thinking…" e ogni casella è disattivata. Otto prende la prima casella libera in un ordine fisso che parte dal centro e prosegue con gli angoli. Ancora nessuno vince perché il mondo cerca il tris solo dal passo 4 in poi.
L'ultima parola del mondo
Sotto la griglia la vista mostra l'ultimo messaggio che non viene dalla persona:
const last = world.messages.filter((message) => !message.fromMe).at(-1);
return <p>{last ? last.text : 'Choose a square to play.'}</p>;Il codice
Le righe nuove sono evidenziate. Gioca una casella per vedere la risposta di Otto.
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>;
}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.';
});
}Prossimi passi
Il passo 4: Il vincitore chiude la partita con un tris o con la griglia piena e mostra il risultato.
Messaggi e azioni sono descritti in Messaggi e domande e in Le azioni che offrono le regole. La ricetta Un mondo finto che cambia nel tempo mostra altri modi di far cambiare un mondo finto.