Giocatori e turni
Prima di una mossa la persona deve sapere tre cose: (1) quale dei due giocatori è, (2) chi gioca contro di lei e (3) a chi tocca. Adesso la vista le mostra tutte e tre sopra la griglia.
I ruoli
La persona e ogni membro di un mondo hanno ciascuno un ruolo. Dei due ruoli di Crosses (X e O) il mondo finto dà la X alla persona e la O al membro Otto:
members: [{ name: 'Otto', role: 'O' }],
roles: [
{ name: 'X', description: 'Plays crosses, and moves first.' },
{ name: 'O', description: 'Plays noughts.' },
],
myRole: 'X',La tua vista li legge come world.myRole, world.members e world.roles. L'altro giocatore è il membro il cui ruolo è diverso da quello della persona:
function opponentOf(world) {
return world.members?.find((member) => member.role !== world.myRole) ?? null;
}A chi tocca
Il kit non ha un campo per il turno perché ogni mondo decide dove tenerlo. Crosses tiene il ruolo a cui tocca giocare in data.turn accanto alla griglia. Quando turn è uguale a myRole, tocca alla persona:
const isMyTurn = world.data.turn === world.myRole;
// ...
<strong>{isMyTurn ? 'Your turn.' : `${opponent?.name ?? 'The other player'} is thinking…`}</strong>Il mondo finto tiene turn fisso a 'X' finché il passo 3 non lo fa cambiare a ogni mossa.
Il codice
Le righe nuove sono evidenziate.
import { useWorld } from './useWorld.js';
// A fake world to build with, a game of tic-tac-toe that needs no account and no network.
const crosses = {
name: 'Crosses',
profile: { description: 'Tic-tac-toe: three in a row wins.' },
// What the world shows, by name. The board: three rows of three squares, a round already started.
data: {
board: [
['X', '', ''],
['', 'O', ''],
['', '', ''],
],
// Whose turn it is: the role that plays now.
turn: 'X',
},
// 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',
};
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} />
</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() ?? ['', '', '', '', '', '', '', '', ''];
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'}`}
style={{ height: 72, fontSize: 32, fontWeight: 700, color: mark === 'X' ? '#3b82f6' : '#ef4444' }}
>
{mark}
</button>
))}
</div>
);
}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.
const crosses = {
name: 'Crosses',
profile: { description: 'Tic-tac-toe: three in a row wins.' },
// What the world shows, by name. The board: three rows of three squares, a round already started.
data: {
board: [
['X', '', ''],
['', 'O', ''],
['', '', ''],
],
// Whose turn it is: the role that plays now.
turn: 'X',
},
// 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',
};
// 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);
// 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';
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() ?? [];
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';
});
});
}Prossimi passi
Quando tocca alla persona, un clic su una casella ancora non fa niente. Il passo 3: Fai una mossa invia le mosse al mondo e fa rispondere Otto.
Membri e ruoli sono trattati per intero in Persone e ruoli. Il componente TurnIndicator mostra una riga già pronta che dice a chi tocca.