Disegna la mappa
Immagini, numeri, scacchiere e ogni altro valore che un mondo mostra oltre al suo testo arrivano alla vista in data. Dai data del mondo la vista ora disegna la mappa di Treasure Island, la posizione della persona e il livello della marea.
I dati del mondo
world.data è un oggetto che associa a ogni nome scelto dal mondo un valore pronto da usare. Treasure Island ha tre nomi:
map: l'isola come array di righe, ognuna un array di caselle. Una casella è una stringa (🌊 per l'acqua, 🌴 per una palma, ⛰️ per una roccia e · per la sabbia).position: la casella della persona come{ row, column }.tide: un numero da 0 a 100.
Ogni mondo sceglie i propri nomi e la forma dei loro valori. Un mondo vero li definisce nel suo codice mentre in un mondo finto li scegli tu.
I dati in un mondo finto
I data di un mondo finto associano a ogni nome un valore fisso o una funzione del tempo che viene chiamata ogni secondo per calcolare il nuovo valore.
data: {
map: MAP,
position: { row: 3, column: 1 },
// 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)),
},MAP è l'array delle righe definito sopra il mondo finto. La marea esiste solo come esempio di un valore che cambia. Dato che la vista ridisegna tutto il mondo a ogni cambiamento, nell'esempio qui sotto la barra della marea si muove senza codice scritto apposta per la marea.
Disegna una griglia
La vista scorre le righe della mappa e le caselle di ogni riga. Al posto del terreno la casella che corrisponde a position mostra 🧍:
map.forEach((row, rowIndex) => {
row.forEach((ground, columnIndex) => {
const isHere = rowIndex === position.row && columnIndex === position.column;
// ...a cell that shows '🧍' when isHere, and the ground otherwise
});
});Una griglia CSS con gridTemplateColumns: repeat(5, 44px) dà a ogni casella di una riga una colonna sua. Il 5 è la lunghezza di una riga (map[0].length).
In React è il componente IslandMap a mostrare le caselle. La funzione islandMap della versione in JavaScript semplice crea la griglia una volta sola e ne ricostruisce le caselle a ogni cambiamento del mondo. Ricostruire 25 semplici riquadri senza listener costa poco.
I dati possono mancare
Il valore di un nome in data resta undefined finché il mondo non lo invia per la prima volta. Controlla il valore prima di disegnare e mostra un segnaposto finché manca:
if (!map || !position) return <p>The map is on its way…</p>;Il codice
Le righe nuove sono evidenziate.
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 = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
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.
position: { row: 3, column: 1 },
// 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)),
},
};
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} />
</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>
);
}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 = [
['🌊', '🌊', '🌴', '🌊', '🌊'],
['🌊', '🌴', '·', '⛰️', '🌊'],
['🌴', '·', '·', '·', '🌴'],
['🌊', '·', '⛰️', '·', '🌊'],
['🌊', '🌊', '·', '🌴', '🌊'],
];
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.
position: { row: 3, column: 1 },
// 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 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);
// 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}%`;
});
}Prossimi passi
La persona non si può ancora muovere. Su quest'isola una mossa è un messaggio al mondo e prima serve la conversazione che il passo 3: Parla con il mondo aggiunge alla vista.
I dati del mondo tratta ogni tipo di valore che un mondo può inviare e il modo di mostrarlo. La ricetta Disegna una griglia su un canvas disegna su un canvas una griglia come questa mappa.