WinnerBanner
WinnerBanner shows the winner at the end of a game or a contest and usually goes above or below the board. The banner reads You win! when the winner equals the role of the person in world.myRole. For any other winner it reads the name followed by "wins!" ("Ann wins!"). It has a Close button and a Play again button that appears only when you pass 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…';
});The banner appears as soon as the world names a winner in its data with a non-empty string. In the example world.data.winner is null for two and a half seconds and then becomes 'Ann'. The onPlayAgain callback of the example sends the fake world the message that starts a new race. Close hides the banner for the current winner. A new game won by the same name shows the banner again because the component forgets that choice when the data stop naming a winner (The data of the world).
Props
| Prop | Default | What it is |
|---|---|---|
world | (required) | The world, from useWorld. |
name | 'winner' | The key in world.data that holds the winner as a name or a role. |
onPlayAgain | none | A () => void callback for a Play again button rendered only when you pass it. |
Parameters
winnerBanner(container, world, options) draws the banner into container and shows or hides it at every change of the world.
| Parameter | What it is |
|---|---|
container | The element to draw into. |
world | The world, from connectToHost. |
options.name | The key in world.data that holds the winner. Default 'winner'. |
options.onPlayAgain | A () => void callback for a Play again button rendered only when you pass it. |
It returns a function that unsubscribes from the world and removes the banner.
Change it
- A world that ends without a winner in its data: show the banner when
world.statusis'ended'with a text of your own. - A draw: if the world publishes
'draw', write "It is a draw" instead of "draw wins!". - Over the whole view: wrap the banner in a fixed box with a dark backdrop (
position: 'fixed', inset: 0) likeBackPaneldoes. - Play again through the rules: if the rules of the world offer an action for a new game, call
world.act(name)inonPlayAgaininstead of sending a message.
See also
Scoreboard: the ranking before the end.Timer: the countdown to the end.- Tutorial: a turn-based game.