Skip to content

Aspetto e rifinitura ​

L'ultimo passo aggiunge in una volta sola quattro cose a cui il Tutorial 1 dedica un passo ciascuna: (1) il tema della webapp, (2) i bordi del telefono, (3) un messaggio quando una chiamata fallisce e (4) caselle più grandi per un dito.

Il tema della webapp e il telefono ​

world.webapp dà il theme della webapp e le parti dello schermo da lasciare libere (insets in pixel per il notch e la barra home e keyboard per l'altezza della tastiera sullo schermo). Tutta la vista sta in un solo elemento fisso che copre l'iframe e fa scorrere il proprio contenuto. Questo elemento riceve i colori del tema, colorScheme: theme e un padding che tiene il contenuto lontano dalle aree di insets e dalla tastiera:

jsx
const { theme, insets, keyboard } = world.webapp;
const colors = COLORS[theme];
// ...
style={{
  position: 'fixed',
  inset: 0,
  overflowY: 'auto',
  colorScheme: theme,
  background: colors.page,
  color: colors.text,
  paddingTop: insets.top + 16,
  paddingRight: insets.right + 16,
  paddingBottom: Math.max(insets.bottom, keyboard) + 16,
  paddingLeft: insets.left + 16,
}}

Grazie a colorScheme anche Canvas e CanvasText del menu (passo 6) seguono il tema della webapp. Ogni riga è spiegata in Adattati alla webapp e al telefono.

Quando qualcosa va storto ​

Come in Gestisci gli errori e concludi del Tutorial 1, la vista gestisce due errori:

  • In una pagina aperta fuori dalla webapp connectToHost() viene rifiutata con 'no-host' e la vista mostra una breve spiegazione con un link a UNaIVERSE.
  • world.send e world.act vengono rifiutate con il codice 'failed' quando la webapp non riesce a eseguire la chiamata. La vista avvolge tutte e due le chiamate in run, il cui catch trasforma il code dell'errore in un avviso per la persona:
jsx
<button onClick={() => run(() => world.send(String(index + 1)))}>
jsx
{newRound && <button onClick={() => run(() => world.act(newRound.name))}>{newRound.text ?? 'New round'}</button>}

Il mondo finto non fa mai fallire queste chiamate e nell'esempio l'avviso resta quindi nascosto.

Una griglia più bella ​

Le caselle crescono fino a 84 pixel e prendono uno sfondo grigio semitrasparente senza bordo con gli angoli arrotondati di 12 pixel. Sopra una casella che si può giocare il cursore diventa pointer. Cambiano solo gli stili e la griglia funziona come prima.

Il codice ​

Le righe nuove sono evidenziate nella vista completa.

jsx
import { useEffect, useState } from 'react';
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 };
let rounds = {}; // the finished rounds, by number

// 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 };
		rounds = { ...rounds, [round]: { winner, board: rows() } };
	} 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 },
		rounds: { every: 200, value: () => rounds },
	},
	// 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 two themes of the webapp. The view takes the colors of the one the webapp shows.
const COLORS = {
	light: { page: '#f6f7fb', text: '#1b2030' },
	dark: { page: '#151a24', text: '#e8ebf2' },
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: crosses } });
	const [isMenuOpen, setMenuOpen] = useState(false);
	// The round shown in place of the game, or null. At first, the one in the address of the page.
	const [openRound, setOpenRound] = useState(roundInAddress);
	// Why the last move did not work, or null.
	const [problem, setProblem] = useState(null);

	// A page opened alone, outside the webapp, has no world. Say where the view works.
	if (error?.code === 'no-host') return <OutsideTheWebapp />;
	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting to the match…</p>;

	// Does something for the person (a move, a new round) and explains the error if it fails.
	async function run(action) {
		setProblem(null);
		try {
			await action();
		} catch (failure) {
			setProblem(explain(failure.code));
		}
	}

	// Shows a finished round and writes it into the address of the webapp, to let a link open the view on it.
	function showRound(number) {
		setOpenRound(number);
		world.setPath(`/rounds/${number}`);
	}
	// Back to the game, and to the first address of the view.
	function showGame() {
		setOpenRound(null);
		world.setPath('/');
	}

	const pastRound = openRound ? world.data.rounds?.[openRound] : null;
	// The theme of the webapp and the parts of the screen to keep clear.
	const { theme, insets, keyboard } = world.webapp;
	const colors = COLORS[theme];
	return (
		<main
			style={{
				position: 'fixed',
				inset: 0,
				overflowY: 'auto',
				colorScheme: theme,
				background: colors.page,
				color: colors.text,
				paddingTop: insets.top + 16,
				paddingRight: insets.right + 16,
				paddingBottom: Math.max(insets.bottom, keyboard) + 16,
				paddingLeft: insets.left + 16,
			}}
		>
			<button style={{ float: 'right' }} onClick={() => setMenuOpen(true)}>
				Menu
			</button>
			<h1>{world.name}</h1>
			<p>{world.profile.description}</p>
			<Scoreboard world={world} />
			<Players world={world} />
			{problem && (
				<p role="alert" style={NOTICE}>
					{problem}
				</p>
			)}
			{pastRound ? (
				<PastRound world={world} number={openRound} round={pastRound} onClose={showGame} />
			) : (
				<>
					<Board world={world} run={run} />
					<WinnerBanner world={world} run={run} />
					<LastMessage world={world} />
				</>
			)}
			<PastRounds world={world} onOpen={showRound} />
			{isMenuOpen && <Menu world={world} onClose={() => setMenuOpen(false)} />}
		</main>
	);
}

// A notice above the game.
const NOTICE = { padding: '8px 12px', borderRadius: 8, background: 'rgba(255, 170, 0, 0.25)' };

// What to tell the person, by error code, when the webapp could not do a move.
function explain(code) {
	// 'failed': something went wrong in the webapp, and the move did not leave.
	if (code === 'failed') return 'That move did not work. Try again in a moment.';
	// Any other code, including one that a later kit adds, is shown as it is.
	return `That did not work (${code}).`;
}

// Shown when the page is opened alone, outside the UNaIVERSE webapp.
function OutsideTheWebapp() {
	return (
		<main>
			<h1>Crosses</h1>
			<p>This page is the view of a world of UNaIVERSE. Open the world in UNaIVERSE to play.</p>
			<a href="https://unaiverse.io">Go to UNaIVERSE</a>
		</main>
	);
}

// The round in the address of the page (like /rounds/2), or null.
// The webapp opens the view at the address a link names.
function roundInAddress() {
	const match = /^\/rounds\/(\d+)$/.exec(window.location.pathname);
	return match ? Number(match[1]) : null;
}

// A finished round: its last board. While it is shown, the back button closes it.
function PastRound({ world, number, round, onClose }) {
	useEffect(() => {
		const giveBack = world.onBack(() => {
			onClose();
			return true; // handled: the webapp stays where it is
		});
		return giveBack;
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<section>
			<h2>
				Round {number}: {resultText(world, round.winner)}
			</h2>
			<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 40px)', gap: 4 }}>
				{round.board.flat().map((mark, index) => (
					<div
						key={index}
						style={{ height: 40, display: 'grid', placeItems: 'center', fontWeight: 700, borderRadius: 6, background: 'rgba(127, 127, 127, 0.15)' }}
					>
						{mark}
					</div>
				))}
			</div>
			<p>
				<button onClick={onClose}>Back to the game</button>
			</p>
		</section>
	);
}

// The finished rounds, from the data of the world. Each one opens in place of the game.
function PastRounds({ world, onOpen }) {
	const rounds = world.data.rounds ?? {};
	const numbers = Object.keys(rounds);
	if (numbers.length === 0) return null;
	return (
		<section>
			<h2>Past rounds</h2>
			<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
				{numbers.map((number) => (
					<button key={number} onClick={() => onOpen(Number(number))}>
						Round {number}: {resultText(world, rounds[number].winner)}
					</button>
				))}
			</div>
		</section>
	);
}

// The menu: how to play and the roles. While it is open, the back button closes it.
function Menu({ world, onClose }) {
	useEffect(() => {
		// Take the back button while the menu is open, and give it back when the menu closes.
		const giveBack = world.onBack(() => {
			onClose();
			return true; // handled: the webapp stays where it is
		});
		return giveBack;
		// Once, when the menu opens: the world changes at every move, but the menu stays the same.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return (
		<div
			role="dialog"
			aria-label="Menu"
			style={{ position: 'fixed', inset: 0, display: 'grid', placeItems: 'center', background: 'rgba(0, 0, 0, 0.4)' }}
		>
			<div style={{ maxWidth: 320, margin: 16, padding: 20, borderRadius: 12, background: 'Canvas', color: 'CanvasText' }}>
				<h2 style={{ marginTop: 0 }}>How to play</h2>
				<p>Take turns. Three of your marks in a row, a column or a diagonal win the round.</p>
				<ul>
					{(world.roles ?? []).map((role) => (
						<li key={role.name}>
							<strong>{role.name}</strong>: {role.description}
						</li>
					))}
				</ul>
				<button onClick={onClose}>Close</button>
			</div>
		</div>
	);
}

// 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, run }) {
	// 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, 84px)', gap: 8, margin: '16px 0' }}>
			{marks.map((mark, index) => (
				<button
					key={index}
					aria-label={`Square ${index + 1}, ${mark || 'empty'}`}
					disabled={!canPlay || mark !== ''}
					onClick={() => run(() => world.send(String(index + 1)))}
					style={{
						height: 84,
						fontSize: 40,
						fontWeight: 700,
						border: 'none',
						borderRadius: 12,
						background: 'rgba(127, 127, 127, 0.15)',
						color: mark === 'X' ? '#3b82f6' : '#ef4444',
						cursor: !canPlay || mark !== '' ? 'default' : 'pointer',
					}}
				>
					{mark}
				</button>
			))}
		</div>
	);
}

// The end of the round, from the data of the world: who won, or a draw.
function WinnerBanner({ world, run }) {
	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={() => run(() => 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>;
}
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.

// 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 };
let rounds = {}; // the finished rounds, by number

// 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 };
		rounds = { ...rounds, [round]: { winner, board: rows() } };
	} 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 },
		rounds: { every: 200, value: () => rounds },
	},
	// 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 two themes of the webapp. The view takes the colors of the one the webapp shows.
const COLORS = {
	light: { page: '#f6f7fb', text: '#1b2030' },
	dark: { page: '#151a24', text: '#e8ebf2' },
};

// A notice above the game.
const NOTICE = 'padding: 8px 12px; border-radius: 8px; background: rgba(255, 170, 0, 0.25)';

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

// Why the last move did not work.
const problem = document.createElement('p');
problem.setAttribute('role', 'alert');
problem.style.cssText = NOTICE;
problem.hidden = true;

let world = null;
try {
	// While building: the fake world. In the webapp: world = await connectToHost();
	world = await connectToHost({ fake: { world: crosses } });
} catch (error) {
	// A page opened alone, outside the webapp, has no world. Say where the view works.
	if (error.code === 'no-host') outsideTheWebapp(page);
	else page.textContent = `Could not connect (${error.code}).`;
}

if (world) {
	page.textContent = '';
	lookAndScreen(page, world);
	menu(page, world);
	header(page, world);
	scoreboard(page, world);
	players(page, world);
	page.append(problem);
	// The game: the board, the banner and the last message of the world. A past round can take its place.
	const game = document.createElement('div');
	page.append(game);
	board(game, world);
	winnerBanner(game, world);
	lastMessage(game, world);
	pastRounds(page, game, world);
}

// Does something for the person (a move, a new round) and explains the error if it fails.
async function run(action) {
	problem.hidden = true;
	try {
		await action();
	} catch (failure) {
		problem.textContent = explain(failure.code);
		problem.hidden = false;
	}
}

// What to tell the person, by error code, when the webapp could not do a move.
function explain(code) {
	// 'failed': something went wrong in the webapp, and the move did not leave.
	if (code === 'failed') return 'That move did not work. Try again in a moment.';
	// Any other code, including one that a later kit adds, is shown as it is.
	return `That did not work (${code}).`;
}

// Shown when the page is opened alone, outside the UNaIVERSE webapp.
function outsideTheWebapp(page) {
	const title = document.createElement('h1');
	title.textContent = 'Crosses';
	const text = document.createElement('p');
	text.textContent = 'This page is the view of a world of UNaIVERSE. Open the world in UNaIVERSE to play.';
	const link = document.createElement('a');
	link.href = 'https://unaiverse.io';
	link.textContent = 'Go to UNaIVERSE';
	page.replaceChildren(title, text, link);
}

// The page follows what the webapp says about itself: its theme and the parts of the screen to keep clear.
function lookAndScreen(page, world) {
	page.style.cssText = 'position: fixed; inset: 0; overflow-y: auto';

	return world.subscribe((node) => {
		const { theme, insets, keyboard } = node.webapp;
		const colors = COLORS[theme];
		page.style.colorScheme = theme;
		page.style.background = colors.page;
		page.style.color = colors.text;
		page.style.paddingTop = `${insets.top + 16}px`;
		page.style.paddingRight = `${insets.right + 16}px`;
		page.style.paddingBottom = `${Math.max(insets.bottom, keyboard) + 16}px`;
		page.style.paddingLeft = `${insets.left + 16}px`;
	});
}

// The round in the address of the page (like /rounds/2), or null.
// The webapp opens the view at the address a link names.
function roundInAddress() {
	const match = /^\/rounds\/(\d+)$/.exec(window.location.pathname);
	return match ? Number(match[1]) : null;
}

// The finished rounds: a list, and the round the person opens, shown in place of the game.
function pastRounds(container, game, world) {
	// The open round: its result, its last board, and a way back.
	const view = document.createElement('section');
	const heading = document.createElement('h2');
	const grid = document.createElement('div');
	grid.style.cssText = 'display: grid; grid-template-columns: repeat(3, 40px); gap: 4px';
	const back = document.createElement('button');
	back.textContent = 'Back to the game';
	const backLine = document.createElement('p');
	backLine.append(back);
	view.append(heading, grid, backLine);
	// The list of finished rounds.
	const list = document.createElement('section');
	const listHeading = document.createElement('h2');
	listHeading.textContent = 'Past rounds';
	const buttons = document.createElement('div');
	buttons.style.cssText = 'display: flex; gap: 8px; flex-wrap: wrap';
	list.append(listHeading, buttons);
	container.append(view, list);

	// The round shown in place of the game, or null. At first, the one in the address of the page.
	let openRound = roundInAddress();
	let giveBack = null;

	// Shows a finished round and writes it into the address of the webapp, to let a link open the view on it.
	function showRound(number) {
		openRound = number;
		world.setPath(`/rounds/${number}`);
		draw(world.get());
	}
	// Back to the game, and to the first address of the view.
	function showGame() {
		openRound = null;
		world.setPath('/');
		draw(world.get());
	}
	back.onclick = showGame;

	let shownList = '';
	function draw(node) {
		const rounds = node.data.rounds ?? {};
		const round = openRound ? rounds[openRound] : null;
		// The open round, in place of the game.
		game.hidden = Boolean(round);
		view.hidden = !round;
		if (round) {
			heading.textContent = `Round ${openRound}: ${resultText(node, round.winner)}`;
			const cells = round.board.flat().map((mark) => {
				const cell = document.createElement('div');
				cell.style.cssText = 'height: 40px; display: grid; place-items: center; font-weight: 700; border-radius: 6px; background: rgba(127, 127, 127, 0.15)';
				cell.textContent = mark;
				return cell;
			});
			grid.replaceChildren(...cells);
		}
		// While a round is shown, the back button closes it.
		if (round && !giveBack) {
			giveBack = world.onBack(() => {
				showGame();
				return true; // handled: the webapp stays where it is
			});
		}
		if (!round && giveBack) {
			giveBack();
			giveBack = null;
		}
		// The list: drawn again only when the rounds changed.
		const numbers = Object.keys(rounds);
		list.hidden = numbers.length === 0;
		const key = JSON.stringify(numbers);
		if (key === shownList) return;
		shownList = key;
		const items = numbers.map((number) => {
			const button = document.createElement('button');
			button.textContent = `Round ${number}: ${resultText(node, rounds[number].winner)}`;
			button.onclick = () => showRound(Number(number));
			return button;
		});
		buttons.replaceChildren(...items);
	}
	return world.subscribe(draw);
}

// The menu: how to play and the roles. While it is open, the back button closes it.
function menu(container, world) {
	const open = document.createElement('button');
	open.textContent = 'Menu';
	open.style.float = 'right';
	// The panel over the page, hidden until the person opens it.
	const panel = document.createElement('div');
	panel.setAttribute('role', 'dialog');
	panel.setAttribute('aria-label', 'Menu');
	panel.style.cssText = 'position: fixed; inset: 0; display: none; place-items: center; background: rgba(0, 0, 0, 0.4)';
	const box = document.createElement('div');
	box.style.cssText = 'max-width: 320px; margin: 16px; padding: 20px; border-radius: 12px; background: Canvas; color: CanvasText';
	const heading = document.createElement('h2');
	heading.style.marginTop = '0';
	heading.textContent = 'How to play';
	const rules = document.createElement('p');
	rules.textContent = 'Take turns. Three of your marks in a row, a column or a diagonal win the round.';
	const roles = document.createElement('ul');
	const close = document.createElement('button');
	close.textContent = 'Close';
	box.append(heading, rules, roles, close);
	panel.append(box);
	container.append(open, panel);

	let giveBack = null;
	function show() {
		panel.style.display = 'grid';
		// Take the back button while the menu is open.
		giveBack = world.onBack(() => {
			hide();
			return true; // handled: the webapp stays where it is
		});
	}
	function hide() {
		panel.style.display = 'none';
		// Give the back button back to the webapp.
		giveBack?.();
		giveBack = null;
	}
	open.onclick = show;
	close.onclick = hide;

	return world.subscribe((node) => {
		const items = (node.roles ?? []).map((role) => {
			const item = document.createElement('li');
			const name = document.createElement('strong');
			name.textContent = role.name;
			item.append(name, `: ${role.description ?? ''}`);
			return item;
		});
		roles.replaceChildren(...items);
	});
}

// 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, 84px); gap: 8px; margin: 16px 0';
	// 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: 84px; font-size: 40px; font-weight: 700; border: none; border-radius: 12px; background: rgba(127, 127, 127, 0.15)';
		// A move is a message to the world with the number of the square.
		square.onclick = () => run(() => 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 !== '';
			square.style.cursor = square.disabled ? 'default' : 'pointer';
		});
	});
}

// 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 = () => run(() => 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.';
	});
}
Live, on a fake world
Open

Che cosa hai costruito ​

La vista finita disegna la griglia e i turni dai dati del mondo, invia le mosse come messaggi, mostra il vincitore e il punteggio, fa partire nuove partite come azioni delle regole, apre un menu che il tasto indietro chiude e dà un link a ogni partita finita.

Per metterla nella webapp chiama useWorld() o connectToHost() senza il mondo finto, pubblica la vista sul tuo server e scrivi il suo indirizzo nelle impostazioni del tuo mondo (Andare online).

Prossimi passi ​

Il GUI kit di UNaIVERSE, rilasciato con licenza Apache 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.