Skip to content

I dati del mondo ​

Un punteggio, un tabellone, un frame della fotocamera e un file da scaricare arrivano tutti alla tua vista in world.data con i loro nomi e pronti da usare. Ogni tipo di valore si mostra in un modo suo. Tre casi richiedono più attenzione: (1) un valore che cambia molte volte al secondo, (2) la storia recente di un valore e (3) i dati di un mondo finto durante lo sviluppo.

Che cosa sono i dati ​

world.data è un oggetto che associa a ogni nome usato dal mondo il suo valore più recente.

js
world.subscribe((node) => {
  score.textContent = node.data.score;   // a number
  board.draw(node.data.board);           // a grid
  camera.src = node.data.camera;         // a picture
});
  • I nomi li sceglie il mondo. Il suo proprietario ti dice quali usa e Object.keys(world.data) elenca quelli presenti.
  • I valori sono pronti da usare. Un numero arriva come numero, un'immagine come URL o data URI per img.src e un file come oggetto con un nome e un URL.
  • Un nuovo valore è un cambiamento del mondo. Il tuo listener di subscribe viene eseguito di nuovo con i nuovi data ogni volta che il mondo ne invia uno.
  • Un nome compare dopo che il mondo gli ha dato un valore. Fino ad allora node.data.score è undefined e la vista mostra un segnaposto come node.data.score ?? '–'.

Anche la vista di un agente riceve data con i valori dell'agente. In un mondo anche ogni membro ha i propri data (Persone e ruoli).

I tipi di valori ​

L'esempio mostra nel modo più semplice un valore per ogni tipo:

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

// A small picture, written as an image source (an SVG data URI).
const cover = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" rx="8" fill="teal"/></svg>')}`;

// A fake world that shows one value of each kind.
const atelier = {
	name: 'Atelier',
	data: {
		players: 3, // a number
		motto: 'Paint together', // text
		board: [[0, 1, 0], [1, 0, 1]], // a grid, as an array of rows
		cover, // a picture, as an image source
		rules: { name: 'rules.txt', type: 'text/plain', url: 'data:text/plain,Be%20kind.' }, // a file
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const { data } = world;
	return (
		<>
			<p>Players: {data.players}</p>
			<p>Motto: {data.motto}</p>
			{/* One table row per row of the grid, one cell per value. */}
			<table>
				<tbody>
					{data.board.map((row, y) => (
						<tr key={y}>
							{row.map((value, x) => <td key={x}>{value ? '●' : '·'}</td>)}
						</tr>
					))}
				</tbody>
			</table>
			<img src={data.cover} alt="The cover" />
			<a href={data.rules.url} download={data.rules.name}>Download {data.rules.name}</a>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A small picture, written as an image source (an SVG data URI).
const cover = `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60"><rect width="60" height="60" rx="8" fill="teal"/></svg>')}`;

// A fake world that shows one value of each kind.
const atelier = {
	name: 'Atelier',
	data: {
		players: 3, // a number
		motto: 'Paint together', // text
		board: [[0, 1, 0], [1, 0, 1]], // a grid, as an array of rows
		cover, // a picture, as an image source
		rules: { name: 'rules.txt', type: 'text/plain', url: 'data:text/plain,Be%20kind.' }, // a file
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: atelier } });

const players = document.createElement('p');
const motto = document.createElement('p');
const board = document.createElement('table');
const picture = document.createElement('img');
const file = document.createElement('a');
picture.alt = 'The cover';
document.body.append(players, motto, board, picture, file);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	const { data } = node;
	players.textContent = `Players: ${data.players}`;
	motto.textContent = `Motto: ${data.motto}`;
	// One table row per row of the grid, one cell per value.
	board.replaceChildren(...data.board.map((row) => {
		const line = document.createElement('tr');
		line.append(...row.map((value) => {
			const cell = document.createElement('td');
			cell.textContent = value ? '●' : '·';
			return cell;
		}));
		return line;
	}));
	picture.src = data.cover;
	file.href = data.rules.url;
	file.download = data.rules.name;
	file.textContent = `Download ${data.rules.name}`;
});
Live, on a fake world
Open
TipoChe cosa riceviCome disegnarlo
Numero42, 3.5textContent. Arrotondalo con toFixed e formattalo con toLocaleString.
Testouna stringatextContent (o {text} in React) e mai innerHTML perché il testo arriva da altri.
Grigliaun array di righe come [[0, 1, 0], [1, 0, 1]] letto come grid[y][x]una tabella (un canvas per le griglie grandi).
Listaun array come [3, 1, 4]una lista o un grafico.
Immagineun URL o, più spesso, un data URI come 'data:image/png;base64,...'img.src
File{ name, type, url } con un data URI in url e un tipo MIME come 'application/pdf' in typeun link (<a href={url} download={name}>)
Qualsiasi altra cosail valore così come l'ha inviato il mondo (true, un oggetto)il tuo codice.

Un array di un solo elemento arriva come l'elemento

I mondi inviano i valori numerici come array annidati i cui livelli esterni a volte contengono un solo elemento. Il kit toglie ognuno di questi livelli e un punteggio inviato come [[42]] arriva come 42. La stessa regola però trasforma una griglia con una sola riga in quella riga e una lista con un solo elemento nell'elemento. Quando la dimensione può cambiare, ripristina i livelli prima di disegnare:

js
// Makes sure a grid is an array of rows, even with one row or one cell.
function rowsOf(value) {
  if (!Array.isArray(value)) return [[value]]; // a single cell
  return Array.isArray(value[0]) ? value : [value]; // a single row
}

Le griglie ​

Una griglia è un array di righe i cui elementi sono le caselle. grid[y][x] legge la casella nella riga y e nella colonna x. Ogni cambiamento della griglia ti dà una griglia tutta nuova da disegnare di nuovo da zero:

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

// A fake world with a road, a grid of 3 rows and 5 columns where 1 is the car.
// A new grid every half second, with the car one column further to the right.
function road(time) {
	const column = Math.floor(time / 500) % 5;
	return [0, 1, 2].map((y) => [0, 1, 2, 3, 4].map((x) => (y === 1 && x === column ? 1 : 0)));
}
const track = { name: 'Track', data: { road: { every: 500, value: road } } };

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const rows = world.data.road;
	// rows[y][x] reads the row first, then the column.
	const column = rows[1].indexOf(1);
	return (
		<>
			<table style={{ fontSize: 24 }}>
				<tbody>
					{rows.map((row, y) => (
						<tr key={y}>
							{row.map((value, x) => <td key={x}>{value === 1 ? '■' : '·'}</td>)}
						</tr>
					))}
				</tbody>
			</table>
			<p>The car is in column {column + 1} of {rows[1].length}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with a road, a grid of 3 rows and 5 columns where 1 is the car.
// A new grid every half second, with the car one column further to the right.
function road(time) {
	const column = Math.floor(time / 500) % 5;
	return [0, 1, 2].map((y) => [0, 1, 2, 3, 4].map((x) => (y === 1 && x === column ? 1 : 0)));
}
const track = { name: 'Track', data: { road: { every: 500, value: road } } };

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: track } });

const table = document.createElement('table');
table.style.fontSize = '24px';
const where = document.createElement('p');
document.body.append(table, where);

// Called at once, then after every change of the world, with a new grid each time.
world.subscribe((node) => {
	const rows = node.data.road;
	table.replaceChildren(...rows.map((row) => {
		const line = document.createElement('tr');
		line.append(...row.map((value) => {
			const cell = document.createElement('td');
			cell.textContent = value === 1 ? '■' : '·';
			return cell;
		}));
		return line;
	}));
	// rows[y][x] reads the row first, then the column.
	const column = rows[1].indexOf(1);
	where.textContent = `The car is in column ${column + 1} of ${rows[1].length}`;
});
Live, on a fake world
Open

Una tabella funziona fino a qualche centinaio di caselle. Un tabellone più grande o che cambia più volte al secondo va disegnato su un canvas (Disegna una griglia su un canvas).

Le immagini ​

Un'immagine in data è un URL o un data URI che assegni a img.src così com'è. I mondi che riprendono o disegnano qualcosa (una fotocamera, una mappa, un grafico) ne inviano una nuova a ogni cambiamento dell'immagine.

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

// Draws a dial whose hand moves every second, as an image source (an SVG data URI).
// A real world sends its pictures the same way, often the frames of a camera as JPEG or PNG.
function dial(time) {
	const angle = (Math.floor(time / 1000) % 60) * 6;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120">
		<circle cx="60" cy="60" r="54" fill="white" stroke="black" stroke-width="4"/>
		<line x1="60" y1="60" x2="60" y2="14" stroke="crimson" stroke-width="5" transform="rotate(${angle} 60 60)"/>
	</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world with a picture. A function of time gives a new one every second.
const observatory = { name: 'Observatory', data: { sky: dial } };

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			{/* React changes `src` only when the picture changed. */}
			<img src={world.data.sky} alt="The sky, as the world shows it" width={120} height={120} />
			<p>The world’s picture, new every second.</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// Draws a dial whose hand moves every second, as an image source (an SVG data URI).
// A real world sends its pictures the same way, often the frames of a camera as JPEG or PNG.
function dial(time) {
	const angle = (Math.floor(time / 1000) % 60) * 6;
	const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120">
		<circle cx="60" cy="60" r="54" fill="white" stroke="black" stroke-width="4"/>
		<line x1="60" y1="60" x2="60" y2="14" stroke="crimson" stroke-width="5" transform="rotate(${angle} 60 60)"/>
	</svg>`;
	return `data:image/svg+xml,${encodeURIComponent(svg)}`;
}

// A fake world with a picture. A function of time gives a new one every second.
const observatory = { name: 'Observatory', data: { sky: dial } };

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: observatory } });

const picture = document.createElement('img');
picture.alt = 'The sky, as the world shows it';
picture.width = 120;
picture.height = 120;
const caption = document.createElement('p');
caption.textContent = 'The world’s picture, new every second.';
document.body.append(picture, caption);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// Only when the picture changed, because the world also changes for other reasons (a message, another value).
	if (picture.getAttribute('src') !== node.data.sky) picture.src = node.data.sky;
});
Live, on a fake world
Open
  • Dai all'immagine una dimensione fissa (width e height o il CSS) per evitare che il layout si sposti mentre si carica ogni nuova immagine.
  • Cambia src solo quando l'immagine è cambiata. Il tuo listener viene eseguito anche per altri cambiamenti come un messaggio o un altro valore. React salta già un src che non è cambiato. In JavaScript semplice l'esempio confronta il nuovo valore con getAttribute('src').
  • Le immagini grandi non rallentano la webapp. Un'immagine grande viene inviata alla tua vista una volta sola e non di nuovo a ogni messaggio (Prestazioni).
  • Per disegnare un'immagine su un canvas caricala prima con const image = new Image(); image.onload = () => context.drawImage(image, 0, 0); image.src = node.data.camera;. La ricetta Mostra un'immagine dai dati ha un esempio completo.

I file ​

Un file è un oggetto { name, type, url }:

  • url è un data URI con il contenuto del file per un link o per un <img>.
  • type è il tipo MIME ('application/pdf', 'image/png', 'text/csv'). La vista lo legge per scegliere se mostrare un'immagine od offrire un link.
  • name è il nome del file oppure null quando il mondo non ne ha dato uno. file.name ?? 'download' copre tutti e due i casi.
js
const link = document.createElement('a');
link.href = node.data.report.url;
link.download = node.data.report.name ?? 'report';
link.textContent = `Download ${node.data.report.name ?? 'the report'}`;

La ricetta Scarica un file dai dati offre un singolo file con un link di questo tipo. Il componente FileList elenca più file con il loro tipo e la loro dimensione.

Seguire un valore: onData ​

subscribe chiama il suo listener con il mondo intero a ogni cambiamento. world.onData(name, listener) chiama invece listener solo con ogni nuovo valore di un nome e restituisce una funzione che lo ferma.

Usalo per un valore che cambia spesso e che mostri da solo senza ridisegnare ogni volta tutta la pagina o rifare il re-render di React. Nell'esempio una posizione arriva 20 volte al secondo e la vista ridisegna soltanto il canvas:

jsx
import { useEffect, useRef } from 'react';
import { useWorld } from './useWorld.js';

// A fake world with fast data, a new position [x, y] 20 times a second.
const radar = {
	name: 'Radar',
	data: {
		blip: { every: 50, value: (time) => [100 + 70 * Math.cos(time / 600), 100 + 70 * Math.sin(time / 600)] },
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return (
		<>
			<h2>{world.name}</h2>
			<Blip world={world} />
			<p>The dot is drawn by onData, at every new position.</p>
		</>
	);
}

// Draws the position on a canvas, without asking React to render again.
function Blip({ world }) {
	const canvasRef = useRef(null);

	useEffect(() => {
		const canvas = canvasRef.current;
		const context = canvas.getContext('2d');
		function drawBlip([x, y]) {
			context.clearRect(0, 0, canvas.width, canvas.height);
			context.fillStyle = 'crimson';
			context.beginPath();
			context.arc(x, y, 8, 0, 2 * Math.PI);
			context.fill();
		}
		// onData calls you only with each NEW value of one name. Draw the value it has now first.
		if (world.data.blip) drawBlip(world.data.blip);
		// It returns the function that stops it, and React calls it when the component goes away.
		return world.onData('blip', drawBlip);
		// Start once, when the component appears, because onData keeps following the newest world.
		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, []);

	return <canvas ref={canvasRef} width={200} height={200} style={{ border: '1px solid gray' }} />;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with fast data, a new position [x, y] 20 times a second.
const radar = {
	name: 'Radar',
	data: {
		blip: { every: 50, value: (time) => [100 + 70 * Math.cos(time / 600), 100 + 70 * Math.sin(time / 600)] },
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: radar } });

const title = document.createElement('h2');
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
canvas.style.border = '1px solid gray';
const note = document.createElement('p');
note.textContent = 'The dot is drawn by onData, at every new position.';
document.body.append(title, canvas, note);

// Draws one position on the canvas.
const context = canvas.getContext('2d');
function drawBlip([x, y]) {
	context.clearRect(0, 0, canvas.width, canvas.height);
	context.fillStyle = 'crimson';
	context.beginPath();
	context.arc(x, y, 8, 0, 2 * Math.PI);
	context.fill();
}

// onData calls you only with each NEW value of one name. Draw the value it has now first.
if (world.data.blip) drawBlip(world.data.blip);
world.onData('blip', drawBlip);

// The rest of the page still follows the world with subscribe.
world.subscribe((node) => {
	title.textContent = node.name;
});
Live, on a fake world
Open

Il comportamento di onData ha tre aspetti che contano:

  • Passa solo i valori nuovi e mai quello attuale. L'esempio disegna prima world.data[name]. Senza questo passo il canvas resta vuoto fino al valore successivo.
  • Un valore che non cambia mai non chiama mai il listener (per esempio un valore fisso in un mondo finto).
  • Dentro la webapp scatta solo quando la webapp invia alla tua vista il mondo aggiornato e quindi al massimo una volta per animation frame. Di un valore sostituito due volte nello stesso frame ricevi soltanto il più recente. Quando ti servono tutti i valori, dataHistory li dà tutti.

In React chiama onData in un effetto che viene eseguito una volta sola e restituisci dall'effetto la sua funzione di stop in modo che React la chiami all'unmount. Non fa differenza se chiami onData su world o su un nodo ricevuto dal tuo listener perché onData consegna sempre i valori più recenti.

I dati veloci ​

Alcuni mondi inviano molti valori al secondo (frame della fotocamera, letture di sensori, posizioni in un gioco). Tre pratiche tengono fluida una vista:

  • Mostra i valori veloci a parte con onData su un canvas o su un <img> invece di ridisegnare tutta la pagina per ognuno.
  • In React tieni i valori veloci fuori dallo stato. Ogni setState rifà il render del tuo componente e 30 render al secondo si sommano. L'esempio qui sopra disegna attraverso un ref e tiene nello stato soltanto quello che mostra il resto della pagina.
  • Tieni leggero il listener di subscribe. Viene eseguito anche per ognuno di quei cambiamenti veloci. Crea quindi i tuoi elementi una volta sola e dentro il listener aggiorna soltanto il loro testo.

La ricetta Segui i dati veloci senza rallentare e la pagina Prestazioni vanno più a fondo. Tutorial: un agente con la fotocamera costruisce una vista completa su una fotocamera che invia dieci immagini al secondo.

I valori recenti: dataHistory ​

world.dataHistory(name) restituisce i valori recenti di un nome dal più vecchio al più recente come [{ value, time }, ...] con il momento di arrivo di ognuno. Tiene fino a 200 valori e restituisce un array vuoto per un nome che il mondo non ha usato.

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

// A fake world with a temperature that changes four times a second.
const station = {
	name: 'Weather station',
	data: {
		temperature: { every: 250, value: (time) => Math.round((20 + 2 * Math.sin(time / 2000)) * 10) / 10 },
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: station } });
	// The summary the person asked for, kept in the state of the page until they ask again.
	const [summary, setSummary] = useState('');

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	// The recent values, asked for when the person wants them. Await them, because inside the webapp they come as a promise.
	async function showHistory() {
		const history = await world.dataHistory('temperature');
		if (history.length === 0) {
			setSummary('No values yet.');
			return;
		}
		const values = history.map((item) => item.value);
		const seconds = Math.round((history.at(-1).time - history[0].time) / 1000);
		setSummary(`${history.length} values in ${seconds} s, lowest ${Math.min(...values)} °C, highest ${Math.max(...values)} °C`);
	}

	return (
		<>
			{/* The value now, from the world at every render. */}
			<p>Temperature now: {world.data.temperature} °C</p>
			<button onClick={showHistory}>Show the recent values</button>
			<p>{summary}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world with a temperature that changes four times a second.
const station = {
	name: 'Weather station',
	data: {
		temperature: { every: 250, value: (time) => Math.round((20 + 2 * Math.sin(time / 2000)) * 10) / 10 },
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: station } });

const now = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Show the recent values';
const summary = document.createElement('p');
document.body.append(now, button, summary);

// The value now, from the world at every change.
world.subscribe((node) => {
	now.textContent = `Temperature now: ${node.data.temperature} °C`;
});

// The recent values, asked for when the person wants them. Await them, because inside the webapp they come as a promise.
button.onclick = async () => {
	const history = await world.dataHistory('temperature');
	if (history.length === 0) {
		summary.textContent = 'No values yet.';
		return;
	}
	const values = history.map((item) => item.value);
	const seconds = Math.round((history.at(-1).time - history[0].time) / 1000);
	summary.textContent = `${history.length} values in ${seconds} s, lowest ${Math.min(...values)} °C, highest ${Math.max(...values)} °C`;
};
Live, on a fake world
Open
  • Usa sempre await. Dentro la webapp restituisce una Promise perché la storia è conservata dalla webapp e il kit deve richiederla. Con un mondo finto restituisce direttamente l'array e await funziona in tutti e due i casi.
  • È un'istantanea. Chiamala di nuovo ogni volta che ti serve (alla pressione di un pulsante o ogni secondo per un grafico) invece di chiamarla una volta all'avvio.
  • time è in millisecondi dall'epoca Unix come Date.now(). new Date(item.time) lo trasforma in una data.

La ricetta Un grafico di un numero nel tempo disegna un valore nel tempo.

I dati in un mondo finto ​

I data di un mondo finto accettano tre tipi di valori:

  1. Un valore fisso come table: 'Table 7' che resta uguale per tutta la vita del mondo finto.
  2. Una funzione del tempo (time) => value che il mondo finto chiama ogni secondo con il tempo in millisecondi.
  3. { every, value } per dati più veloci o per un valore che segue una variabile. Il mondo finto chiama value(time) ogni every millisecondi.

Per fare in modo che i dati seguano quello che fa la persona, tieni una variabile nel tuo file, cambiala in onMessage o in onAction e leggila in una funzione { every, value }:

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

// The dice, kept in a variable of this file that the fake world changes.
let dice = 1;

// A fake world with the three kinds of fake data.
const diceTable = {
	name: 'Dice table',
	data: {
		// 1. A fixed value, the same for the whole life of the fake world.
		table: 'Table 7',
		// 2. A function of time, called every second.
		seconds: (time) => Math.floor(time / 1000) % 60,
		// 3. `{ every, value }`, called every 200 ms. It reads the variable and therefore follows the dice.
		dice: { every: 200, value: () => dice },
	},
	// The person's message changes the variable, and the next reading shows it.
	onMessage: (message) => {
		if (message.text !== 'roll') return 'Say roll to roll the dice.';
		dice = 1 + Math.floor(Math.random() * 6);
		return `You rolled ${dice}.`;
	},
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;

	const answer = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<p>Table: {world.data.table}</p>
			<p>Seconds: {world.data.seconds}</p>
			<p>Dice: {world.data.dice}</p>
			<button onClick={() => world.send('roll')}>Roll the dice</button>
			<p>{answer?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The dice, kept in a variable of this file that the fake world changes.
let dice = 1;

// A fake world with the three kinds of fake data.
const diceTable = {
	name: 'Dice table',
	data: {
		// 1. A fixed value, the same for the whole life of the fake world.
		table: 'Table 7',
		// 2. A function of time, called every second.
		seconds: (time) => Math.floor(time / 1000) % 60,
		// 3. `{ every, value }`, called every 200 ms. It reads the variable and therefore follows the dice.
		dice: { every: 200, value: () => dice },
	},
	// The person's message changes the variable, and the next reading shows it.
	onMessage: (message) => {
		if (message.text !== 'roll') return 'Say roll to roll the dice.';
		dice = 1 + Math.floor(Math.random() * 6);
		return `You rolled ${dice}.`;
	},
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: diceTable } });

const table = document.createElement('p');
const seconds = document.createElement('p');
const shown = document.createElement('p');
const button = document.createElement('button');
button.textContent = 'Roll the dice';
button.onclick = () => world.send('roll');
const answer = document.createElement('p');
document.body.append(table, seconds, shown, button, answer);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	table.textContent = `Table: ${node.data.table}`;
	seconds.textContent = `Seconds: ${node.data.seconds}`;
	shown.textContent = `Dice: ${node.data.dice}`;
	answer.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';
});
Live, on a fake world
Open

Il now di un mondo finto è fisso per tutta la sua vita e quindi quello che cambia (di chi è il turno, un punteggio, un tabellone) va in data come nell'esempio. Un mondo finto dà tutti i suoi dati insieme quando la tua vista si connette. Diversamente da lui, un agente finto parte con data vuoto e dà i suoi valori un momento dopo come fa un agente vero. Provare con i mondi finti tratta le altre funzioni di un mondo finto.

A che cosa stare attenti ​

  • undefined prima del primo valore. Disegna un segnaposto finché il nome non compare.
  • Un array di un solo elemento arriva come l'elemento. Usa rowsOf qui sopra per le griglie la cui dimensione cambia.
  • Niente copie. Leggi node.data dentro il tuo listener e world.get().data in un handler di clic (Pensare per viste).
  • Niente innerHTML. Il testo di data arriva da altri e va in textContent.
  • onData parte vuoto. Disegna il valore attuale prima che arrivi il primo valore nuovo.

Prossimi passi ​

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