Una nuova partita e il punteggio
Alla fine di una partita la persona ha bisogno di un pulsante che faccia partire la successiva e di un punteggio che dica come sta andando la sfida.
Una nuova partita è un'azione
Una nuova partita è un passaggio del gioco vero e proprio e Crosses la offre come azione delle sue regole. Il mondo finto elenca l'azione in now.actions e la esegue in onAction:
now: { actions: [{ name: 'new-round', text: 'New round' }] },
// ...
onAction: (name) => {
if (name !== 'new-round' || !winner) return 'Finish this round first.';
squares = ['', '', '', '', '', '', '', '', ''];
turn = 'X';
winner = null;
round += 1;
return `Round ${round}. You start.`;
},Il now di un mondo finto non cambia mai e offre l'azione per tutta la vita del mondo. Prima della fine di una partita onAction la rifiuta con il messaggio "Finish this round first."
Il pulsante
Quando le regole offrono l'azione, il banner la trova per nome in now.actions e mostra un pulsante con il suo text:
const newRound = world.now?.actions.find((action) => action.name === 'new-round');
// ...
{newRound && <button onClick={() => world.act(newRound.name)}>{newRound.text ?? 'New round'}</button>}world.act(name) chiede alle regole di eseguire l'azione e la nuova partita arriva alla vista come un normale cambiamento del mondo che svuota la griglia, toglie il banner e aggiunge il messaggio "Round 2. You start."
Il punteggio
data.round contiene il numero della partita in corso e data.score un conteggio per ogni ruolo più uno per i pareggi ({ X: 1, O: 0, draw: 0 }). Alla fine di ogni partita il mondo finto aggiunge uno a score[winner] (al conteggio draw dopo un pareggio).
Il segnapunti legge round e score e mette per prima la persona:
const mine = `You ${score[world.myRole] ?? 0}`;
const theirs = `${opponent?.name ?? 'Them'} ${score[opponent?.role] ?? 0}`;
return <p>{`Round ${world.data.round ?? 1} · ${mine} · ${theirs} · Draws ${score.draw ?? 0}`}</p>;Il codice
Le righe nuove sono evidenziate. Finisci una partita e cominciane una nuova.
import { useWorld } from './useWorld.js';
// A fake world to build with, a game of tic-tac-toe that needs no account and no network.
// The eight lines of three squares: rows, columns and diagonals (squares 0 to 8).
const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
// What changes in the fake world. The view reads it through `data`.
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';
let winner = null; // 'X', 'O' or 'draw' once the round is over
let round = 1;
let score = { X: 0, O: 0, draw: 0 };
// 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)];
}
// 'X' or 'O' with three in a row, 'draw' when the board is full, otherwise null.
function winnerOf() {
for (const [a, b, c] of LINES) {
if (squares[a] !== '' && squares[a] === squares[b] && squares[a] === squares[c]) return squares[a];
}
return squares.includes('') ? null : 'draw';
}
// Puts a mark on a square, then gives the turn to the other player or ends the round.
function play(index, mark) {
squares[index] = mark;
winner = winnerOf();
if (winner) {
turn = null;
score = { ...score, [winner]: score[winner] + 1 };
} else {
turn = mark === 'X' ? 'O' : 'X';
}
}
// Otto's square: one that makes his three in a row, or one that stops yours, or the first he likes.
function ottoSquare() {
for (const mark of ['O', 'X']) {
for (const line of LINES) {
const marks = line.map((index) => squares[index]);
const isAlmostFull = marks.filter((each) => each === mark).length === 2 && marks.includes('');
if (isAlmostFull) return line[marks.indexOf('')];
}
}
return [4, 0, 2, 6, 8, 1, 3, 5, 7].find((index) => squares[index] === '');
}
// The end of a round, in the words of the world.
function endText() {
return winner === 'draw' ? 'The board is full: a draw.' : `Three in a row for ${winner}.`;
}
// 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.' },
// The rules offer the person one action: start a new round.
now: { actions: [{ name: 'new-round', text: 'New round' }] },
// 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 won the round: 'X', 'O', 'draw', or null while it goes on.
winner: { every: 200, value: () => winner },
round: { every: 200, value: () => round },
score: { every: 200, value: () => score },
},
// 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.';
play(index, 'X');
if (winner) return endText();
await wait(600); // Otto thinks
const answer = ottoSquare();
play(answer, 'O');
return `Otto plays square ${answer + 1}. ${winner ? endText() : 'Your turn.'}`;
},
// The action of the rules: a new round, once this one is over.
onAction: (name) => {
if (name !== 'new-round' || !winner) return 'Finish this round first.';
squares = ['', '', '', '', '', '', '', '', ''];
turn = 'X';
winner = null;
round += 1;
return `Round ${round}. You start.`;
},
};
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>
<Scoreboard world={world} />
<Players world={world} />
<Board world={world} />
<WinnerBanner world={world} />
<LastMessage world={world} />
</main>
);
}
// The round and the match score, from the data of the world.
function Scoreboard({ world }) {
const score = world.data.score ?? {};
const opponent = opponentOf(world);
const mine = `You ${score[world.myRole] ?? 0}`;
const theirs = `${opponent?.name ?? 'Them'} ${score[opponent?.role] ?? 0}`;
return <p>{`Round ${world.data.round ?? 1} · ${mine} · ${theirs} · Draws ${score.draw ?? 0}`}</p>;
}
// 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>
{/* Once the round is over, nobody's turn. */}
{!world.data.winner && (
<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 end of the round, from the data of the world: who won, or a draw.
function WinnerBanner({ world }) {
const winner = world.data.winner;
if (!winner) return null;
// The action of the rules that starts a new round, when they offer it.
const newRound = world.now?.actions.find((action) => action.name === 'new-round');
return (
<div
role="status"
style={{
display: 'flex',
alignItems: 'center',
gap: 12,
margin: '12px 0',
padding: '12px 16px',
borderRadius: 12,
background: 'rgba(255, 190, 0, 0.35)',
}}
>
<strong style={{ fontSize: 20 }}>{resultText(world, winner)}</strong>
{newRound && <button onClick={() => world.act(newRound.name)}>{newRound.text ?? 'New round'}</button>}
</div>
);
}
// The end of a round in words: who won, or a draw.
function resultText(world, winner) {
if (winner === 'draw') return 'A draw.';
if (winner === world.myRole) return 'You won! 🎉';
const member = world.members?.find((each) => each.role === winner);
return `${member?.name ?? winner} won.`;
}
// 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.
// The eight lines of three squares: rows, columns and diagonals (squares 0 to 8).
const LINES = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
// What changes in the fake world. The view reads it through `data`.
let squares = ['', '', '', '', '', '', '', '', ''];
let turn = 'X';
let winner = null; // 'X', 'O' or 'draw' once the round is over
let round = 1;
let score = { X: 0, O: 0, draw: 0 };
// 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)];
}
// 'X' or 'O' with three in a row, 'draw' when the board is full, otherwise null.
function winnerOf() {
for (const [a, b, c] of LINES) {
if (squares[a] !== '' && squares[a] === squares[b] && squares[a] === squares[c]) return squares[a];
}
return squares.includes('') ? null : 'draw';
}
// Puts a mark on a square, then gives the turn to the other player or ends the round.
function play(index, mark) {
squares[index] = mark;
winner = winnerOf();
if (winner) {
turn = null;
score = { ...score, [winner]: score[winner] + 1 };
} else {
turn = mark === 'X' ? 'O' : 'X';
}
}
// Otto's square: one that makes his three in a row, or one that stops yours, or the first he likes.
function ottoSquare() {
for (const mark of ['O', 'X']) {
for (const line of LINES) {
const marks = line.map((index) => squares[index]);
const isAlmostFull = marks.filter((each) => each === mark).length === 2 && marks.includes('');
if (isAlmostFull) return line[marks.indexOf('')];
}
}
return [4, 0, 2, 6, 8, 1, 3, 5, 7].find((index) => squares[index] === '');
}
// The end of a round, in the words of the world.
function endText() {
return winner === 'draw' ? 'The board is full: a draw.' : `Three in a row for ${winner}.`;
}
// 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.' },
// The rules offer the person one action: start a new round.
now: { actions: [{ name: 'new-round', text: 'New round' }] },
// 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 won the round: 'X', 'O', 'draw', or null while it goes on.
winner: { every: 200, value: () => winner },
round: { every: 200, value: () => round },
score: { every: 200, value: () => score },
},
// 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.';
play(index, 'X');
if (winner) return endText();
await wait(600); // Otto thinks
const answer = ottoSquare();
play(answer, 'O');
return `Otto plays square ${answer + 1}. ${winner ? endText() : 'Your turn.'}`;
},
// The action of the rules: a new round, once this one is over.
onAction: (name) => {
if (name !== 'new-round' || !winner) return 'Finish this round first.';
squares = ['', '', '', '', '', '', '', '', ''];
turn = 'X';
winner = null;
round += 1;
return `Round ${round}. You start.`;
},
};
// 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);
scoreboard(page, world);
players(page, world);
board(page, world);
winnerBanner(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 ?? '';
});
}
// The round and the match score, from the data of the world.
function scoreboard(container, world) {
const line = document.createElement('p');
container.append(line);
return world.subscribe((node) => {
const score = node.data.score ?? {};
const opponent = opponentOf(node);
const mine = `You ${score[node.myRole] ?? 0}`;
const theirs = `${opponent?.name ?? 'Them'} ${score[opponent?.role] ?? 0}`;
line.textContent = `Round ${node.data.round ?? 1} · ${mine} · ${theirs} · Draws ${score.draw ?? 0}`;
});
}
// 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…`;
// Once the round is over, nobody's turn.
turn.hidden = Boolean(node.data.winner);
});
}
// 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 end of the round, from the data of the world: who won, or a draw.
function winnerBanner(container, world) {
const banner = document.createElement('div');
banner.setAttribute('role', 'status');
banner.style.cssText = 'align-items: center; gap: 12px; margin: 12px 0; padding: 12px 16px; border-radius: 12px; background: rgba(255, 190, 0, 0.35)';
const result = document.createElement('strong');
result.style.fontSize = '20px';
const newRound = document.createElement('button');
newRound.onclick = () => world.act('new-round');
banner.append(result, newRound);
container.append(banner);
return world.subscribe((node) => {
const winner = node.data.winner;
// Shown only once the round is over.
banner.style.display = winner ? 'flex' : 'none';
result.textContent = winner ? resultText(node, winner) : '';
// The action of the rules that starts a new round, when they offer it.
const action = node.now?.actions.find((each) => each.name === 'new-round');
newRound.hidden = !action;
newRound.textContent = action?.text ?? 'New round';
});
}
// The end of a round in words: who won, or a draw.
function resultText(node, winner) {
if (winner === 'draw') return 'A draw.';
if (winner === node.myRole) return 'You won! 🎉';
const member = node.members?.find((each) => each.role === winner);
return `${member?.name ?? winner} won.`;
}
// 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 6: Un menu e il tasto indietro aggiunge un menu che spiega il gioco e si chiude con il tasto indietro del telefono.
Le azioni che offrono le regole e il riferimento di act descrivono le azioni per intero. Il componente Scoreboard mette in classifica i membri di un mondo secondo un numero che ciascuno di loro mostra.