Skip to content

Disegna la griglia ​

La prima versione della vista di Crosses si collega al mondo e disegna le nove caselle della griglia con i segni già giocati.

La griglia è un dato ​

Un mondo passa alla tua vista i valori che mostra come voci con un nome in data. Crosses invia la sua griglia con il nome board come tre righe di tre caselle. Ogni casella contiene 'X', 'O' oppure '' per una casella vuota.

Il mondo finto di questo passo parte da una partita già a metà:

js
const crosses = {
  name: 'Crosses',
  profile: { description: 'Tic-tac-toe: three in a row wins.' },
  data: {
    board: [
      ['X', '', ''],
      ['', 'O', ''],
      ['', '', ''],
    ],
  },
};

Nove caselle ​

La vista appiattisce le righe in nove segni con flat() e disegna una casella per ciascuno. Le caselle sono numerate da 1 a 9 riga per riga (la casella 1 è l'angolo in alto a sinistra, la 5 il centro e la 9 l'angolo in basso a destra).

jsx
const marks = world.data.board?.flat() ?? ['', '', '', '', '', '', '', '', ''];

Finché il mondo non invia board, il valore di riserva dopo ?? dà nove caselle vuote che tengono la griglia sulla pagina fin dal primo render.

Ogni casella è un <button> che mostra il suo segno (la X in blu e la O in rosso) e porta un aria-label con il suo numero e il suo segno come "Square 5, O" o "Square 6, empty". Per ora un clic non fa niente perché le caselle diventano mosse solo al passo 3.

La versione in JavaScript semplice crea i nove pulsanti una volta sola e a ogni cambiamento del mondo riscrive soltanto i loro segni. Un pulsante ricreato a ogni cambiamento potrebbe perdere un clic quando le caselle diventeranno mosse.

Il codice ​

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.
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', ''],
			['', '', ''],
		],
	},
};

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>
			<Board world={world} />
		</main>
	);
}

// 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>
	);
}
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.
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', ''],
			['', '', ''],
		],
	},
};

// 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);
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 ?? '';
	});
}

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

Prossimi passi ​

Il passo 2: Giocatori e turni aggiunge chi gioca con quale segno e a chi tocca.

Tutti i tipi di valore che un mondo può mostrare sono in I dati del mondo. Una griglia come questa esiste anche già pronta nel componente Grid.

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