WinnerBanner
WinnerBanner mostra il vincitore alla fine di una partita o di una gara e di solito va sopra o sotto il tabellone. Il banner mostra You win! quando il vincitore è uguale al ruolo della persona in world.myRole. Per qualsiasi altro vincitore mostra il nome seguito da "wins!" ("Ann wins!"). Ha un pulsante Close e un pulsante Play again che compare solo se passi onPlayAgain.
import { useEffect, useState } from 'react';
import { useWorld } from './useWorld.js';
// The component: copy this part.
/**
* WinnerBanner: a banner when the game ends, with who won ("You win!" when
* it is the person's role). It shows when the world names a winner in its
* data. The person can then close it or play again.
* @param {object} props
* @param {object} props.world - The world, from useWorld.
* @param {string} [props.name='winner'] - The name in `world.data` of the winner (a name or a role).
* @param {() => void} [props.onPlayAgain] - With it, a "Play again" button calls it.
*/
export function WinnerBanner({ world, name = 'winner', onPlayAgain }) {
// The winner for whom the person closed the banner. It stays closed for that winner
// until the world names no winner again (a new game), which forgets the choice.
const [closedFor, setClosedFor] = useState(null);
const winner = world.data[name];
const hasWinner = typeof winner === 'string' && winner !== '';
useEffect(() => {
if (!hasWinner) setClosedFor(null);
}, [hasWinner]);
if (typeof winner !== 'string' || winner === '' || winner === closedFor) return null;
const text = winner === world.myRole ? 'You win!' : `${winner} wins!`;
return (
<div role="status" style={{ display: 'grid', gap: 10, justifyItems: 'center', padding: '20px 24px', borderRadius: 16, textAlign: 'center', border: '1px solid rgba(240, 165, 78, 0.7)', background: 'rgba(240, 165, 78, 0.18)' }}>
<span aria-hidden="true" style={{ fontSize: 40, lineHeight: 1 }}>🏆</span>
<strong style={{ fontSize: 24 }}>{text}</strong>
<div style={{ display: 'flex', gap: 8 }}>
{onPlayAgain && (
<button type="button" onClick={onPlayAgain}
style={{ padding: '8px 18px', borderRadius: 10, border: 0, background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: 600, cursor: 'pointer' }}>
Play again
</button>
)}
<button type="button" onClick={() => setClosedFor(winner)}
style={{ padding: '8px 18px', borderRadius: 10, border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer' }}>
Close
</button>
</div>
</div>
);
}
// Using it, on a fake world.
// When the fake game started: Ann wins two and a half seconds later.
let startedAt = Date.now();
// A fake world to build with: it names a winner in its data and starts a new game when it gets "again".
const race = {
name: 'Race',
data: { winner: { every: 200, value: (time) => (time - startedAt > 2500 ? 'Ann' : null) } },
onMessage: (message) => {
if (message.text === 'again') startedAt = Date.now();
},
};
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: race } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
return (
<div style={{ display: 'grid', gap: 12, maxWidth: 420 }}>
<h2 style={{ margin: 0 }}>{world.name}</h2>
<p style={{ margin: 0 }}>{world.data.winner ? 'The race is over.' : 'The race is on…'}</p>
<WinnerBanner world={world} onPlayAgain={() => world.send('again')} />
</div>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// The component: copy this part.
/**
* Draws a banner into `container` when the game ends, with who won ("You
* win!" when it is the person's role). The banner shows when the world names
* a winner in its data. The person can then close it or play again.
* @param {HTMLElement} container - Where to draw it.
* @param {object} world - The world, from connectToHost.
* @param {{name?: string, onPlayAgain?: () => void}} [options] - The name in `world.data` of the winner
* (a name or a role, default 'winner'), and what "Play again" does (without it, there is no such button).
* @returns {() => void} Stops following the world and removes what it drew.
*/
export function winnerBanner(container, world, { name = 'winner', onPlayAgain } = {}) {
const banner = document.createElement('div');
banner.setAttribute('role', 'status');
Object.assign(banner.style, { gap: '10px', justifyItems: 'center', padding: '20px 24px', borderRadius: '16px', textAlign: 'center', border: '1px solid rgba(240, 165, 78, 0.7)', background: 'rgba(240, 165, 78, 0.18)' });
const cup = document.createElement('span');
cup.setAttribute('aria-hidden', 'true');
cup.textContent = '🏆';
Object.assign(cup.style, { fontSize: '40px', lineHeight: '1' });
const words = document.createElement('strong');
words.style.fontSize = '24px';
const buttons = document.createElement('div');
Object.assign(buttons.style, { display: 'flex', gap: '8px' });
if (onPlayAgain) {
const again = document.createElement('button');
again.type = 'button';
again.textContent = 'Play again';
again.onclick = onPlayAgain;
Object.assign(again.style, { padding: '8px 18px', borderRadius: '10px', border: '0', background: '#2A54C4', color: '#fff', font: 'inherit', fontWeight: '600', cursor: 'pointer' });
buttons.append(again);
}
const close = document.createElement('button');
close.type = 'button';
close.textContent = 'Close';
Object.assign(close.style, { padding: '8px 18px', borderRadius: '10px', border: '1px solid rgba(127, 127, 127, 0.45)', background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer' });
buttons.append(close);
banner.append(cup, words, buttons);
container.append(banner);
// The winner for whom the person closed the banner. It stays closed for that winner
// until the world names no winner again (a new game), which forgets the choice.
let closedFor = null;
/** Draws the banner from the newest world. */
const draw = () => {
const node = world.get();
const winner = node.data[name];
const hasWinner = typeof winner === 'string' && winner !== '';
if (!hasWinner) closedFor = null;
const isShown = hasWinner && winner !== closedFor;
banner.style.display = isShown ? 'grid' : 'none';
if (isShown) words.textContent = winner === node.myRole ? 'You win!' : `${winner} wins!`;
};
close.onclick = () => {
closedFor = world.get().data[name];
draw();
};
// Called at once, then after every change of the world.
const stop = world.subscribe(draw);
return () => {
stop();
banner.remove();
};
}
// Using it, on a fake world.
// When the fake game started: Ann wins two and a half seconds later.
let startedAt = Date.now();
// A fake world to build with: it names a winner in its data and starts a new game when it gets "again".
const race = {
name: 'Race',
data: { winner: { every: 200, value: (time) => (time - startedAt > 2500 ? 'Ann' : null) } },
onMessage: (message) => {
if (message.text === 'again') startedAt = Date.now();
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: race } });
const page = document.createElement('div');
Object.assign(page.style, { display: 'grid', gap: '12px', maxWidth: '420px' });
const title = document.createElement('h2');
title.style.margin = '0';
title.textContent = world.name;
const state = document.createElement('p');
state.style.margin = '0';
const place = document.createElement('div');
page.append(title, state, place);
document.body.append(page);
winnerBanner(place, world, { onPlayAgain: () => world.send('again') });
world.subscribe((node) => {
state.textContent = node.data.winner ? 'The race is over.' : 'The race is on…';
});Il banner compare appena il mondo indica nei suoi dati un vincitore con una stringa non vuota. Nell'esempio world.data.winner resta null per due secondi e mezzo e poi diventa 'Ann'. La callback onPlayAgain dell'esempio invia al mondo finto il messaggio che fa partire una nuova corsa. Close nasconde il banner per il vincitore attuale. Una nuova partita vinta dallo stesso nome mostra di nuovo il banner perché il componente dimentica questa scelta quando i dati smettono di indicare un vincitore (I dati del mondo).
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo, da useWorld. |
name | 'winner' | La chiave in world.data che contiene il vincitore come nome o come ruolo. |
onPlayAgain | nessuno | Una callback () => void per un pulsante Play again che compare solo se la passi. |
Parametri
winnerBanner(container, world, options) disegna il banner dentro container e a ogni cambiamento del mondo lo mostra o lo nasconde.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo, da connectToHost. |
options.name | La chiave in world.data che contiene il vincitore. Predefinito 'winner'. |
options.onPlayAgain | Una callback () => void per un pulsante Play again che compare solo se la passi. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove il banner.
Modificalo
- Un mondo che finisce senza un vincitore nei dati: mostra il banner con un tuo testo quando
world.statusè'ended'. - Un pareggio: se il mondo pubblica
'draw', scrivi "It is a draw" invece di "draw wins!". - Sopra tutta la vista: avvolgi il banner in un riquadro fisso con uno sfondo scuro (
position: 'fixed', inset: 0) come faBackPanel. - Giocare di nuovo attraverso le regole: se le regole del mondo offrono un'azione per una nuova partita, in
onPlayAgainchiamaworld.act(name)invece di inviare un messaggio.
Vedi anche
Scoreboard: la classifica prima della fine.Timer: il conto alla rovescia fino alla fine.- Tutorial: un gioco a turni.