Skip to content

Le azioni offerte dalle regole ​

In ogni momento le regole di un mondo dicono che cosa sta succedendo, che cosa può venire dopo e quali azioni può scegliere la persona (per esempio votare, fare un'offerta, passare o cominciare un nuovo round). world.now contiene queste tre cose e world.act(name) chiede alle regole una delle azioni. Una vista legge now per mostrare il momento attuale e per offrire le azioni disponibili come pulsanti (con degli argomenti quando un'azione ne ha bisogno) e chiama act quando la persona preme uno dei pulsanti. Un terzo campo, world.canSend, è true quando la persona può inviare un messaggio.

Che cosa sta succedendo adesso ​

world.now ha tre campi: (1) text con la descrizione del momento attuale ("Place your bets"), (2) next con i nomi di quello che può venire dopo e (3) actions con le azioni che la persona può scegliere (più avanti).

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

// A fake world: what its rules say now, and what can come next.
const roulette = {
	name: 'Roulette',
	now: { text: 'Place your bets', next: ['spinning', 'paying'] },
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	// `now` is null when the rules say nothing (an ended world, an agent without rules).
	if (!world.now) return <h2>Nothing is happening.</h2>;
	return (
		<>
			<h2>Now: {world.now.text ?? '…'}</h2>
			<p>What can come next: {world.now.next.join(', ') || 'nothing'}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake world: what its rules say now, and what can come next.
const roulette = {
	name: 'Roulette',
	now: { text: 'Place your bets', next: ['spinning', 'paying'] },
};

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

const text = document.createElement('h2');
const next = document.createElement('p');
document.body.append(text, next);

// Called at once, then after every change of the world.
world.subscribe((node) => {
	// `now` is null when the rules say nothing (an ended world, an agent without rules).
	if (!node.now) {
		text.textContent = 'Nothing is happening.';
		next.textContent = '';
		return;
	}
	text.textContent = `Now: ${node.now.text ?? '…'}`;
	next.textContent = `What can come next: ${node.now.next.join(', ') || 'nothing'}`;
});
Live, on a fake world
Open
  • now può essere null quando le regole non dicono niente (un agente senza regole o un mondo che è finito). Controllalo prima di leggerne i campi.
  • now.text è null quando le regole non hanno una descrizione per il momento attuale.
  • now.next contiene i nomi interni delle regole ('spinning', 'paying') e include la destinazione di ogni azione. Questi nomi servono per una barra di avanzamento o per scegliere un'immagine. Il testo da mostrare alla persona sta invece in now.text e nel text di ogni azione.

Quando le regole vanno avanti now cambia e il tuo listener di subscribe viene eseguito di nuovo come per ogni altro cambiamento.

Le azioni che la persona può scegliere ​

world.now.actions elenca le azioni che la persona può chiedere adesso. Ogni azione ha questi campi:

CampoChe cos'è
nameIl nome che passi ad act.
textL'etichetta del suo pulsante. Quando è null, mostra name.
toIl nome di quello che viene dopo (uno di now.next).
argsI suoi argomenti così come li danno le regole.
canChoosetrue quando la persona può chiederla, false quando avviene da sola e null quando il mondo non lo dice.
isRequestedtrue quando qualcuno l'ha già chiesta.

Disegna un pulsante per ogni azione. Le azioni cambiano quando le regole vanno avanti e i pulsanti le seguono.

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

// A fake council: two actions to choose, and the votes in `data`.
let yes = 0;
let no = 0;
const council = {
	name: 'Council',
	now: {
		text: 'Vote on the new park',
		actions: [
			{ name: 'vote-yes', text: 'Vote yes', to: 'counting' },
			{ name: 'vote-no', text: 'Vote no', to: 'counting' },
		],
	},
	data: { yes: { every: 200, value: () => yes }, no: { every: 200, value: () => no } },
	// Called when the person chooses one of `now.actions`. Its answer arrives as a message.
	onAction: (name) => {
		if (name === 'vote-yes') yes += 1;
		if (name === 'vote-no') no += 1;
		return 'Your vote is counted.';
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: council } });
	// What the rules said to the person's last request, kept by the view and not by the world.
	const [request, setRequest] = useState('');

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

	// Asks the rules for an action, and shows what they said.
	async function choose(name) {
		const result = await world.act(name);
		setRequest(`Your request: ${result}`);
	}

	const news = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<h2>{world.now?.text}</h2>
			{/* One button per action the rules offer the person now. */}
			<div>
				{(world.now?.actions ?? []).map((action) => (
					// canChoose false: the action happens on its own and the person cannot ask for it.
					<button key={action.name} disabled={action.canChoose === false} onClick={() => choose(action.name)}>
						{action.text ?? action.name}
					</button>
				))}
			</div>
			<p>{request}</p>
			<p>Yes: {world.data.yes} · No: {world.data.no}</p>
			<p>{news?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake council: two actions to choose, and the votes in `data`.
let yes = 0;
let no = 0;
const council = {
	name: 'Council',
	now: {
		text: 'Vote on the new park',
		actions: [
			{ name: 'vote-yes', text: 'Vote yes', to: 'counting' },
			{ name: 'vote-no', text: 'Vote no', to: 'counting' },
		],
	},
	data: { yes: { every: 200, value: () => yes }, no: { every: 200, value: () => no } },
	// Called when the person chooses one of `now.actions`. Its answer arrives as a message.
	onAction: (name) => {
		if (name === 'vote-yes') yes += 1;
		if (name === 'vote-no') no += 1;
		return 'Your vote is counted.';
	},
};

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

const title = document.createElement('h2');
const buttons = document.createElement('div');
const request = document.createElement('p');
const votes = document.createElement('p');
const news = document.createElement('p');
document.body.append(title, buttons, request, votes, news);

// Asks the rules for an action, and shows what they said.
async function choose(name) {
	const result = await world.act(name);
	request.textContent = `Your request: ${result}`;
}

// The actions that the buttons show. The buttons are made again only when the actions change,
// because the votes change often and new buttons at every vote would lose the keyboard focus.
let shownActions = null;

// Called at once, then after every change of the world.
world.subscribe((node) => {
	title.textContent = node.now?.text ?? '';
	votes.textContent = `Yes: ${node.data.yes} · No: ${node.data.no}`;
	news.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';

	const actions = node.now?.actions ?? [];
	if (JSON.stringify(actions) === shownActions) return;
	shownActions = JSON.stringify(actions);
	// One button per action the rules offer the person now.
	buttons.replaceChildren(...actions.map((action) => {
		const button = document.createElement('button');
		button.textContent = action.text ?? action.name;
		// canChoose false: the action happens on its own and the person cannot ask for it.
		button.disabled = action.canChoose === false;
		button.onclick = () => choose(action.name);
		return button;
	}));
});
Live, on a fake world
Open
  • Disegna i pulsanti da now.actions e mai da una lista tua. Una vista che segue questa regola non offre mai un'azione che le regole adesso non offrono.
  • canChoose: false indica un'azione che avviene da sola quando lo decidono le regole. Mostrala come informazione o lasciala fuori. Un'azione con canChoose uguale a null (il mondo non lo dice) viene offerta come tutte le altre.
  • isRequested: true vuol dire che la persona o qualcun altro ha già chiesto l'azione e che questa è in attesa. Mostra che è in attesa ("Waiting for the vote to close") invece di offrirla di nuovo (Mostra quale azione è in attesa).
  • Il mondo risponde con un messaggio (la riga sotto i voti) e scrive il nuovo conteggio in data.
  • In JavaScript semplice ricostruisci i pulsanti solo quando cambiano le azioni. Dato che il mondo cambia spesso (nell'esempio i voti cambiano ogni 200 ms), pulsanti ricostruiti a ogni cambiamento perderebbero il focus della tastiera mentre la persona li usa.

Chiedere un'azione: act ​

world.act(name) chiede alle regole una delle now.actions. Sono le regole a decidere se e quando l'azione avviene e quindi la chiamata è soltanto una richiesta. La Promise restituita da act si risolve con un valore che dice se le regole hanno accettato la richiesta. L'azione vera e propria, quando avviene, arriva alla vista attraverso subscribe come ogni altro cambiamento.

RisultatoSignificatoChe cosa fare
'requested'Le regole hanno accettato la richiesta.Niente. Il mondo cambia quando l'azione avviene e fino ad allora la vista può mostrare "Inviata".
'refused'L'azione è offerta. In questo momento le regole non hanno accettato una richiesta per questa azione o non hanno risposto entro 10 secondi.Avvisa la persona. Di solito now.text dà il motivo.
'not-allowed'In now.actions non c'è nessuna azione con questo nome.Disegna i pulsanti da now.actions per evitarlo.

Dentro la webapp è la webapp a inoltrare act alle regole come già fa con send. Quando la webapp non riesce a passare la richiesta alle regole, la Promise di act viene rifiutata con un errore il cui code è 'failed'.

js
async function choose(name) {
  try {
    const result = await world.act(name);
    if (result === 'refused') notice.textContent = 'Not now: the rules did not take it.';
  } catch (error) {
    notice.textContent = `Could not act (${error.code}).`;
  }
}

Un risultato 'requested' non vuol dire che l'azione sia avvenuta. La vista la mostra come avvenuta solo dopo che il mondo è cambiato (Pensare per viste).

Azioni con argomenti ​

Alcune azioni hanno bisogno di dettagli come l'importo di un'offerta o la destinazione di una mossa. Passali in un oggetto come secondo argomento di act (world.act('bid', { amount: 25 })). È il mondo a decidere quali argomenti prende ogni azione. Te li indica il proprietario del mondo e action.args li elenca nella forma in cui li danno le regole.

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

// A fake auction: one action, `bid`, that takes an amount.
let best = 0;
const auction = {
	name: 'Auction',
	now: { text: 'A painting is for sale', actions: [{ name: 'bid', text: 'Bid' }] },
	data: { best: { every: 200, value: () => best } },
	// `args` holds what the view gave to `act`.
	onAction: (name, args) => {
		if (args.amount <= best) return `${args.amount} is not enough.`;
		best = args.amount;
		return `You bid ${args.amount}. You lead!`;
	},
};

export default function App() {
	// While building: the fake world. In the webapp: useWorld()
	const { world, error } = useWorld({ fake: { world: auction } });
	// The amount the person is typing, kept by the view and not by the world.
	const [amount, setAmount] = useState('10');

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

	// The button works only while the rules offer the action.
	const bid = world.now?.actions.find((action) => action.name === 'bid');
	const news = world.messages.filter((message) => !message.fromMe).at(-1);
	return (
		<>
			<h2>{world.now?.text}</h2>
			<p>Best bid: {world.data.best}</p>
			<label>
				Amount <input type="number" value={amount} onChange={(event) => setAmount(event.target.value)} />
			</label>
			{/* The action with its arguments. The amount is a number, not the text of the field. */}
			<button disabled={!bid || bid.canChoose === false} onClick={() => world.act('bid', { amount: Number(amount) })}>
				{bid?.text ?? 'Bid'}
			</button>
			<p>{news?.text ?? ''}</p>
		</>
	);
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// A fake auction: one action, `bid`, that takes an amount.
let best = 0;
const auction = {
	name: 'Auction',
	now: { text: 'A painting is for sale', actions: [{ name: 'bid', text: 'Bid' }] },
	data: { best: { every: 200, value: () => best } },
	// `args` holds what the view gave to `act`.
	onAction: (name, args) => {
		if (args.amount <= best) return `${args.amount} is not enough.`;
		best = args.amount;
		return `You bid ${args.amount}. You lead!`;
	},
};

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

const title = document.createElement('h2');
const bestLine = document.createElement('p');
const label = document.createElement('label');
const amount = document.createElement('input');
amount.type = 'number';
amount.value = '10';
label.append('Amount ', amount);
const button = document.createElement('button');
const news = document.createElement('p');
document.body.append(title, bestLine, label, button, news);

// The action with its arguments. The amount is a number, not the text of the field.
button.onclick = () => world.act('bid', { amount: Number(amount.value) });

// Called at once, then after every change of the world.
world.subscribe((node) => {
	title.textContent = node.now?.text ?? '';
	bestLine.textContent = `Best bid: ${node.data.best}`;
	// The button works only while the rules offer the action.
	const bid = node.now?.actions.find((action) => action.name === 'bid');
	button.textContent = bid?.text ?? 'Bid';
	button.disabled = !bid || bid.canChoose === false;
	news.textContent = node.messages.filter((message) => !message.fromMe).at(-1)?.text ?? '';
});
Live, on a fake world
Open

Il value di un <input> è una stringa anche con type="number". Convertilo con Number(amount) in modo da passare al mondo il numero 25 invece della stringa '25'.

canSend: la persona può inviare adesso? ​

world.canSend lo decidono le regole del mondo. È false quando la persona adesso non può inviare un messaggio: (1) non è il suo turno, (2) il mondo è offline o (3) uno dei suoi messaggi è ancora in corso (per un momento dopo ogni send). Un send chiamato mentre è false si risolve con 'not-allowed'.

Collega a canSend la casella dei messaggi e ogni pulsante che invia e mostra accanto a loro una riga che dice alla persona perché non può inviare.

js
world.subscribe((node) => {
  sendButton.disabled = !node.canSend;
  hint.textContent = node.canSend ? '' : 'Wait for your turn.';
});

canSend riguarda soltanto i messaggi. Le azioni seguono invece now.actions e ogni azione di quella lista si può chiedere. La ricetta Disattiva la casella dei messaggi quando la persona non può inviare ha una casella dei messaggi completa collegata a canSend.

Le azioni in un mondo finto ​

Un mondo finto elenca le sue azioni nel suo now e risponde con onAction.

js
const council = {
  name: 'Council',
  now: {
    text: 'Vote on the new park',
    actions: [{ name: 'vote-yes', text: 'Vote yes', to: 'counting' }],
  },
  // name: the action; args: what the view gave to act(); sender: who asked.
  onAction: (name, args, sender) => `${sender.name} asked for ${name}.`,
};
  • Come onMessage, anche onAction restituisce la risposta del mondo oppure niente. La risposta arriva alla vista come un messaggio delle regole (con isSystem: true).
  • Il now di un mondo finto è fisso per tutta la sua vita e le sue azioni non cambiano mai. Tieni quello che cambia (i voti, di chi è il turno) in data attraverso una variabile aggiornata da onAction (come negli esempi qui sopra).
  • Ogni azione finta ha canChoose: true e isRequested: false. act si risolve con 'requested' per un'azione in now.actions e con 'not-allowed' per qualsiasi altro nome. Non si risolve mai con 'refused'.

Provare con i mondi finti tratta i mondi finti per intero.

A che cosa stare attenti ​

  • now può essere null. Controllalo prima di leggere now.text o now.actions.
  • I pulsanti vengono da now.actions con l'etichetta text ?? name.
  • Un risultato non è un errore. act si risolve con 'refused' e con 'not-allowed'. Una chiamata che la webapp non è riuscita a fare viene invece rifiutata con l'errore 'failed'. Gestisci tutti e due i casi.
  • 'requested' non vuol dire avvenuta. Aspetta che il mondo cambi.

Prossimi passi ​

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