Un mondo finto che cambia nel tempo
Un mondo vero cambia da solo (un orologio gira, una palla vola, un punteggio sale) e un mondo finto fa lo stesso attraverso funzioni nei suoi data. Lo fanno cambiare tre forme: (1) una funzione del tempo che dà un valore nuovo ogni secondo, (2) un oggetto { every, value } che ne dà uno all'intervallo che scegli tu e (3) una variabile del tuo file che una callback cambia quando la persona agisce e che una di queste funzioni legge. Nell'esempio premi Shoot per segnare.
import { useWorld } from './useWorld.js';
// The fake world reads this variable, and the person's messages change it.
let goals = 0;
// A fake world that changes over time. Since `now` stays fixed for its whole life, what changes goes in `data`.
const match = {
name: 'Match',
now: { text: 'Second half' },
data: {
// A function of time (in milliseconds) gives a new value every second.
minute: (time) => 45 + (Math.floor(time / 1000) % 45),
// { every, value } gives a new value as often as you say, here every 100 ms.
ball: { every: 100, value: (time) => Math.round(50 + 45 * Math.sin(time / 400)) },
// The world reads the variable every 200 ms and changes when the person acts.
goals: { every: 200, value: () => goals },
},
onMessage: () => {
goals += 1;
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: match } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Drawn again at every new value.
return (
<>
<p>{world.now?.text}, minute {world.data.minute}</p>
<div style={{ position: 'relative', height: 24, background: '#3c8d5a', borderRadius: 4 }}>
<div
style={{
position: 'absolute', top: 4, left: `calc(${world.data.ball}% - 8px)`,
width: 16, height: 16, borderRadius: '50%', background: 'white',
}}
/>
</div>
<p>Goals: {world.data.goals}</p>
<button onClick={() => world.send('shoot')}>Shoot</button>
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The fake world reads this variable, and the person's messages change it.
let goals = 0;
// A fake world that changes over time. Since `now` stays fixed for its whole life, what changes goes in `data`.
const match = {
name: 'Match',
now: { text: 'Second half' },
data: {
// A function of time (in milliseconds) gives a new value every second.
minute: (time) => 45 + (Math.floor(time / 1000) % 45),
// { every, value } gives a new value as often as you say, here every 100 ms.
ball: { every: 100, value: (time) => Math.round(50 + 45 * Math.sin(time / 400)) },
// The world reads the variable every 200 ms and changes when the person acts.
goals: { every: 200, value: () => goals },
},
onMessage: () => {
goals += 1;
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: match } });
const minute = document.createElement('p');
const field = document.createElement('div');
field.style.cssText = 'position: relative; height: 24px; background: #3c8d5a; border-radius: 4px';
const ball = document.createElement('div');
ball.style.cssText = 'position: absolute; top: 4px; width: 16px; height: 16px; border-radius: 50%; background: white';
field.append(ball);
const score = document.createElement('p');
const shoot = document.createElement('button');
shoot.textContent = 'Shoot';
shoot.onclick = () => world.send('shoot');
document.body.append(minute, field, score, shoot);
// Called at once, then at every new value.
world.subscribe((node) => {
minute.textContent = `${node.now?.text}, minute ${node.data.minute}`;
ball.style.left = `calc(${node.data.ball}% - 8px)`;
score.textContent = `Goals: ${node.data.goals}`;
});Come funziona
- Ogni secondo il mondo finto chiama
minute: (time) => ...con il tempo in millisecondi dall'epoca Unix (il valore diDate.now()) e la tua vista riceve il risultato come nuovo valore diminute. ball: { every: 100, value: (time) => ... }fa lo stesso ogni 100 millisecondi. Dati così veloci mostrano se la tua vista tiene il passo (Segui i dati veloci senza rallentare).goalsè una semplice variabile del file cheonMessageincrementa a ogni messaggio della persona.value: () => goalsla legge ogni 200 millisecondi e in questo modo il mondo risponde alla persona attraverso i suoi dati.
now, invece, mantiene il valore che hai scritto per tutta la vita del mondo finto. Metti in data quello che cambia (di chi è il turno, il punteggio, il tempo che resta). Anche i dati di un mondo vero arrivano in data e lo stesso codice della tua vista funziona quindi nella webapp.