Skip to content

Fai una mossa ​

Ora la persona cammina sull'isola con quattro pulsanti (North, West, East e South). Accanto a ogni mossa la vista mostra se il mondo l'ha ricevuta.

Una mossa è un messaggio ​

Su Treasure Island una mossa è un messaggio il cui testo nomina una direzione ("north", "west", "east" o "south"). Come la casella di testo del passo 3, ogni pulsante di mossa invia quel testo con world.send:

jsx
<button disabled={!world.canSend} onClick={() => world.send(move.direction)}>
  {move.label}
</button>

Una griglia CSS di tre colonne dispone i pulsanti a bussola assegnando a ognuno il suo gridRow e il suo gridColumn.

I comandi che un mondo vero accetta sono definiti dalle sue regole. Per il mondo finto di questo tutorial sono le stringhe che onMessage controlla.

Un mondo finto che cambia ​

La posizione del passo 2 era un valore fisso. Per lasciare che il mondo finto sposti la persona tieni la posizione in una variabile e associa a position in data una funzione che la legge:

js
let position = { row: 3, column: 1 };

const island = {
  // ...
  data: {
    // ...
    position: { every: 200, value: () => position },
  },
  onMessage: (message) => {
    const word = message.text.trim().toLowerCase();
    if (STEPS[word]) return walk(word);
    // ...
  },
};

walk aggiorna position e restituisce la risposta del mondo ("You walk north." oppure "Water! You cannot go west."). Il mondo finto chiama value ogni 200 millisecondi e pubblica il risultato per la vista. Dopo una mossa la chiamata successiva restituisce la nuova posizione e la vista disegna la persona sulla nuova casella.

In tutti i mondi finti di questa documentazione onMessage (e dal passo 6 anche onAction) scrive delle variabili che poi le funzioni in data leggono.

La consegna ​

La consegna di un messaggio al mondo può fallire e per questo ogni messaggio della persona ha uno status:

  • 'sending': la consegna è in corso.
  • 'sent': il mondo ha ricevuto il messaggio.
  • 'failed': la consegna è fallita. message.retry() invia di nuovo il messaggio.
jsx
function Delivery({ message }) {
  if (message.status === 'sending') return <small> · sending…</small>;
  if (message.status === 'failed') {
    return (
      <small>
        {' '}
        · not delivered <button onClick={() => message.retry()}>Retry</button>
      </small>
    );
  }
  return <small> · sent ✓</small>;
}

La Promise restituita da world.send si risolve con lo stesso esito: 'sent', 'failed' o 'not-allowed' (le regole hanno rifiutato il messaggio e non è stato inviato niente). Questa vista non la aspetta e legge lo stato dalla lista.

Con failNext: true il mondo finto fa fallire il primo messaggio della persona. Nell'esempio qui sotto premi North e poi Retry.

Dato che anche un cambio di stato deve ricostruire la lista, in JavaScript semplice la chiave introdotta nel passo 3 contiene ora l'id e lo stato di ogni messaggio:

js
const key = JSON.stringify(node.messages.map((message) => [message.id, message.status]));

Il codice ​

Le righe nuove sono evidenziate.

jsx
import { useState } from 'react';
import { useWorld } from './useWorld.js';

// A fake world to build with, a small treasure hunt that needs no account and no network.

// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
	['🌊', '🌊', '🌴', '🌊', '🌊'],
	['🌊', '🌴', '·', '⛰️', '🌊'],
	['🌴', '·', '·', '·', '🌴'],
	['🌊', '·', '⛰️', '·', '🌊'],
	['🌊', '🌊', '·', '🌴', '🌊'],
];

// How each move changes the row and the column.
const STEPS = { north: [-1, 0], south: [1, 0], east: [0, 1], west: [0, -1] };

// What changes in the fake world. The view reads it through `data`.
let position = { row: 3, column: 1 };

// Moves you one square, unless there is water.
function walk(direction) {
	const [down, right] = STEPS[direction];
	const next = { row: position.row + down, column: position.column + right };
	const ground = MAP[next.row]?.[next.column];
	if (!ground || ground === '🌊') return `Water! You cannot go ${direction}.`;
	position = next;
	return `You walk ${direction}.`;
}

const island = {
	name: 'Treasure Island',
	profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
	now: { text: 'The hunt is on.' },
	// What the world shows, by name.
	data: {
		map: MAP,
		// Where you are on the map, given by a function that lets the view see each move.
		position: { every: 200, value: () => position },
		// The tide rises and falls: a function of time gives a new value every second.
		tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
	},
	// The world reads what the person writes and answers.
	onMessage: (message) => {
		const word = message.text.trim().toLowerCase();
		if (STEPS[word]) return walk(word);
		if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
		return `The island does not know “${message.text}”. Try: north, south, east, west or look.`;
	},
	// The first message the person sends fails, to let you try the delivery.
	failNext: true,
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: island } });

	// 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>
			<Header world={world} />
			<IslandMap data={world.data} />
			<Moves world={world} />
			<Conversation world={world} />
		</main>
	);
}

// The name of the world, what it is about and what is happening now.
function Header({ world }) {
	return (
		<header>
			<h1>{world.name}</h1>
			<p>{world.profile.description}</p>
			<p>
				Now: {world.now?.text} The world is {world.status}.
			</p>
		</header>
	);
}

// The island from the data of the world: one square per cell, you on yours, and the tide.
function IslandMap({ data }) {
	const { map, position, tide } = data;
	// A name of `data` can be missing for a moment while the world sends it.
	if (!map || !position) return <p>The map is on its way…</p>;

	return (
		<section>
			<div
				role="img"
				aria-label="Map of the island"
				style={{ display: 'grid', gridTemplateColumns: `repeat(${map[0].length}, 44px)`, gap: 2 }}
			>
				{map.map((row, rowIndex) =>
					row.map((ground, columnIndex) => {
						const isHere = rowIndex === position.row && columnIndex === position.column;
						return (
							<div
								key={`${rowIndex}-${columnIndex}`}
								style={{
									height: 44,
									display: 'grid',
									placeItems: 'center',
									fontSize: 24,
									borderRadius: 6,
									background: isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)',
								}}
							>
								{isHere ? '🧍' : ground}
							</div>
						);
					}),
				)}
			</div>
			<p>
				Tide <meter min={0} max={100} value={tide} /> {tide}%
			</p>
		</section>
	);
}

// The four moves, placed like a compass. Each one is a message to the world, like the ones you write.
function Moves({ world }) {
	const moves = [
		{ direction: 'north', label: '↑ North', row: 1, column: 2 },
		{ direction: 'west', label: '← West', row: 2, column: 1 },
		{ direction: 'east', label: '→ East', row: 2, column: 3 },
		{ direction: 'south', label: '↓ South', row: 3, column: 2 },
	];
	return (
		<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 84px)', gap: 4, margin: '12px 0' }}>
			{moves.map((move) => (
				<button
					key={move.direction}
					style={{ gridRow: move.row, gridColumn: move.column }}
					disabled={!world.canSend}
					onClick={() => world.send(move.direction)}
				>
					{move.label}
				</button>
			))}
		</div>
	);
}

// The conversation with the world, oldest first, and a box to write to it.
function Conversation({ world }) {
	const [text, setText] = useState('');

	function handleSubmit(event) {
		event.preventDefault();
		if (!text.trim()) return;
		// Sends as the person. The world reads it and answers with a message.
		world.send(text);
		setText('');
	}

	return (
		<section>
			<h2>Messages</h2>
			{world.messages.length === 0 && <p>No messages yet. Write “look” to the world.</p>}
			<ul style={{ listStyle: 'none', padding: 0 }}>
				{world.messages.map((message) => (
					<Message key={message.id} message={message} />
				))}
			</ul>
			<form onSubmit={handleSubmit} style={{ display: 'flex', gap: 8 }}>
				<input
					value={text}
					onChange={(event) => setText(event.target.value)}
					placeholder="Write to the world"
					aria-label="Write to the world"
					style={{ flex: 1 }}
				/>
				{/* canSend: the rules of the world let the person send now. */}
				<button disabled={!world.canSend}>Send</button>
			</form>
		</section>
	);
}

// One message: who said it and what. The person's own are on the right.
function Message({ message }) {
	return (
		<li style={{ margin: '6px 0', textAlign: message.fromMe ? 'right' : 'left' }}>
			<span style={{ display: 'inline-block', padding: '6px 10px', borderRadius: 10, background: 'rgba(127, 127, 127, 0.15)' }}>
				{message.fromMe ? 'You' : message.from}: {message.text}
			</span>
			{message.fromMe && <Delivery message={message} />}
		</li>
	);
}

// The delivery of one of the person's messages: on its way, sent, or failed.
function Delivery({ message }) {
	if (message.status === 'sending') return <small> · sending…</small>;
	if (message.status === 'failed') {
		return (
			<small>
				{' '}
				· not delivered <button onClick={() => message.retry()}>Retry</button>
			</small>
		);
	}
	return <small> · sent ✓</small>;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world to build with, a small treasure hunt that needs no account and no network.

// The island, row by row: 🌊 water, 🌴 palm trees, ⛰️ rocks, · sand.
const MAP = [
	['🌊', '🌊', '🌴', '🌊', '🌊'],
	['🌊', '🌴', '·', '⛰️', '🌊'],
	['🌴', '·', '·', '·', '🌴'],
	['🌊', '·', '⛰️', '·', '🌊'],
	['🌊', '🌊', '·', '🌴', '🌊'],
];

// How each move changes the row and the column.
const STEPS = { north: [-1, 0], south: [1, 0], east: [0, 1], west: [0, -1] };

// What changes in the fake world. The view reads it through `data`.
let position = { row: 3, column: 1 };

// Moves you one square, unless there is water.
function walk(direction) {
	const [down, right] = STEPS[direction];
	const next = { row: position.row + down, column: position.column + right };
	const ground = MAP[next.row]?.[next.column];
	if (!ground || ground === '🌊') return `Water! You cannot go ${direction}.`;
	position = next;
	return `You walk ${direction}.`;
}

const island = {
	name: 'Treasure Island',
	profile: { description: 'A treasure is buried somewhere on this island. Find it!' },
	now: { text: 'The hunt is on.' },
	// What the world shows, by name.
	data: {
		map: MAP,
		// Where you are on the map, given by a function that lets the view see each move.
		position: { every: 200, value: () => position },
		// The tide rises and falls: a function of time gives a new value every second.
		tide: (time) => Math.round(50 + 40 * Math.sin(time / 8000)),
	},
	// The world reads what the person writes and answers.
	onMessage: (message) => {
		const word = message.text.trim().toLowerCase();
		if (STEPS[word]) return walk(word);
		if (word === 'look') return 'Sand, palm trees and the sea all around. The treasure must be near.';
		return `The island does not know “${message.text}”. Try: north, south, east, west or look.`;
	},
	// The first message the person sends fails, to let you try the delivery.
	failNext: true,
};

// 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: island } });
page.textContent = '';
header(page, world);
islandMap(page, world);
moves(page, world);
conversation(page, world);

// The name of the world, what it is about and what is happening now.
function header(container, world) {
	const title = document.createElement('h1');
	const about = document.createElement('p');
	const now = document.createElement('p');
	container.append(title, about, now);

	// Called at once, then after every change of the world.
	return world.subscribe((node) => {
		title.textContent = node.name;
		about.textContent = node.profile.description ?? '';
		now.textContent = `Now: ${node.now?.text ?? ''} The world is ${node.status}.`;
	});
}

// The island from the data of the world: one square per cell, you on yours, and the tide.
function islandMap(container, world) {
	const grid = document.createElement('div');
	grid.setAttribute('role', 'img');
	grid.setAttribute('aria-label', 'Map of the island');
	grid.style.cssText = 'display: grid; gap: 2px';
	const tide = document.createElement('p');
	const meter = document.createElement('meter');
	meter.min = 0;
	meter.max = 100;
	const level = document.createElement('span');
	tide.append('Tide ', meter, level);
	container.append(grid, tide);

	return world.subscribe((node) => {
		const { map, position } = node.data;
		// A name of `data` can be missing for a moment while the world sends it.
		if (!map || !position) {
			grid.textContent = 'The map is on its way…';
			return;
		}
		grid.style.gridTemplateColumns = `repeat(${map[0].length}, 44px)`;
		const cells = [];
		map.forEach((row, rowIndex) => {
			row.forEach((ground, columnIndex) => {
				const isHere = rowIndex === position.row && columnIndex === position.column;
				const cell = document.createElement('div');
				cell.style.cssText = 'height: 44px; display: grid; place-items: center; font-size: 24px; border-radius: 6px';
				cell.style.background = isHere ? 'rgba(255, 190, 0, 0.6)' : 'rgba(127, 127, 127, 0.12)';
				cell.textContent = isHere ? '🧍' : ground;
				cells.push(cell);
			});
		});
		grid.replaceChildren(...cells);
		meter.value = node.data.tide;
		level.textContent = ` ${node.data.tide}%`;
	});
}

// The four moves, placed like a compass. Each one is a message to the world, like the ones you write.
function moves(container, world) {
	const moves = [
		{ direction: 'north', label: '↑ North', row: 1, column: 2 },
		{ direction: 'west', label: '← West', row: 2, column: 1 },
		{ direction: 'east', label: '→ East', row: 2, column: 3 },
		{ direction: 'south', label: '↓ South', row: 3, column: 2 },
	];
	const compass = document.createElement('div');
	compass.style.cssText = 'display: grid; grid-template-columns: repeat(3, 84px); gap: 4px; margin: 12px 0';
	const buttons = moves.map((move) => {
		const button = document.createElement('button');
		button.textContent = move.label;
		button.style.gridRow = move.row;
		button.style.gridColumn = move.column;
		button.onclick = () => world.send(move.direction);
		return button;
	});
	compass.append(...buttons);
	container.append(compass);

	return world.subscribe((node) => {
		for (const button of buttons) button.disabled = !node.canSend;
	});
}

// The conversation with the world, oldest first, and a box to write to it.
function conversation(container, world) {
	const heading = document.createElement('h2');
	heading.textContent = 'Messages';
	const empty = document.createElement('p');
	empty.textContent = 'No messages yet. Write “look” to the world.';
	const list = document.createElement('ul');
	list.style.cssText = 'list-style: none; padding: 0';
	const form = document.createElement('form');
	form.style.cssText = 'display: flex; gap: 8px';
	const input = document.createElement('input');
	input.placeholder = 'Write to the world';
	input.setAttribute('aria-label', 'Write to the world');
	input.style.flex = '1';
	const send = document.createElement('button');
	send.textContent = 'Send';
	form.append(input, send);
	container.append(heading, empty, list, form);

	form.onsubmit = (event) => {
		event.preventDefault();
		if (!input.value.trim()) return;
		// Sends as the person. The world reads it and answers with a message.
		world.send(input.value);
		input.value = '';
	};

	let shown = '';
	return world.subscribe((node) => {
		// canSend: the rules of the world let the person send now.
		send.disabled = !node.canSend;
		empty.hidden = node.messages.length > 0;
		// Draw the list again only when the messages changed, not at every change of the data.
		const key = JSON.stringify(node.messages.map((message) => [message.id, message.status]));
		if (key === shown) return;
		shown = key;
		list.replaceChildren(...node.messages.map(messageItem));
	});
}

// One message: who said it and what. The person's own are on the right.
function messageItem(message) {
	const item = document.createElement('li');
	item.style.margin = '6px 0';
	item.style.textAlign = message.fromMe ? 'right' : 'left';
	const bubble = document.createElement('span');
	bubble.style.cssText = 'display: inline-block; padding: 6px 10px; border-radius: 10px; background: rgba(127, 127, 127, 0.15)';
	bubble.textContent = `${message.fromMe ? 'You' : message.from}: ${message.text ?? ''}`;
	item.append(bubble);
	if (message.fromMe) item.append(delivery(message));
	return item;
}

// The delivery of one of the person's messages: on its way, sent, or failed.
function delivery(message) {
	const note = document.createElement('small');
	if (message.status === 'sending') {
		note.textContent = ' · sending…';
	} else if (message.status === 'failed') {
		const retry = document.createElement('button');
		retry.textContent = 'Retry';
		retry.onclick = () => message.retry();
		note.append(' · not delivered ', retry);
	} else {
		note.textContent = ' · sent ✓';
	}
	return note;
}
Live, on a fake world
Open

Prossimi passi ​

Da qualche parte sull'isola c'è un forziere chiuso a chiave. La persona prova ad aprirlo nel passo 5: Rispondi a una domanda.

Le ricette Mostra se un messaggio è stato consegnato e Riprova un messaggio fallito trattano la consegna da sola.

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