Skip to content

Scoreboard ​

Each member of a world has its own data in which it can publish a number such as the points in a quiz, the coins in a market or the accuracy of an agent. Scoreboard ranks the members by that number from the highest to the lowest and updates the ranking at every change. Equal numbers share a place (1, 2, 2, 4) and every member in first place gets a highlighted row.

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

// The component: copy this part.

/**
 * Ranks the members by a number of their data, highest first. Equal scores
 * share a place (1, 2, 2, 4). Members without that number are left out.
 * @param {Array<object>} members - The members of the world.
 * @param {string} field - The name of the number in each member's `data`.
 * @returns {Array<{member: object, score: number, place: number}>} The ranking.
 */
function rank(members, field) {
	const scored = members
		.filter((member) => typeof member.data?.[field] === 'number')
		.map((member) => ({ member, score: member.data[field] }))
		.sort((a, b) => b.score - a.score);
	return scored.map((row) => ({ ...row, place: scored.findIndex((other) => other.score === row.score) + 1 }));
}

/**
 * Scoreboard: the members of the world ranked by a number that each one shows
 * in its own data (a score, points, coins), highest first. It draws again as they change.
 * @param {object} props
 * @param {object} props.world - The world, from useWorld.
 * @param {string} [props.field='score'] - The name of the number in each member's `data`.
 * @param {string} [props.title='Scores'] - The title of the table.
 */
export function Scoreboard({ world, field = 'score', title = 'Scores' }) {
	const rows = rank(world.members ?? [], field);
	const cell = { padding: '8px 12px', textAlign: 'left' };
	return (
		<table style={{ borderCollapse: 'collapse', minWidth: 260 }}>
			<caption style={{ textAlign: 'left', fontWeight: 600, padding: '0 0 8px' }}>{title}</caption>
			<thead>
				<tr style={{ fontSize: 13, opacity: 0.7, borderBottom: '1px solid rgba(127, 127, 127, 0.3)' }}>
					<th scope="col" style={cell}>Place</th>
					<th scope="col" style={cell}>Name</th>
					<th scope="col" style={{ ...cell, textAlign: 'right' }}>Score</th>
				</tr>
			</thead>
			<tbody>
				{rows.length === 0 && (
					<tr><td colSpan={3} style={{ ...cell, opacity: 0.6 }}>No scores yet.</td></tr>
				)}
				{rows.map(({ member, score, place }) => (
					<tr key={member.id} style={{ borderBottom: '1px solid rgba(127, 127, 127, 0.15)', background: place === 1 ? 'rgba(240, 165, 78, 0.18)' : 'transparent', fontWeight: place === 1 ? 600 : 400 }}>
						<td style={cell}>{place}</td>
						<th scope="row" style={{ ...cell, fontWeight: 'inherit' }}>{member.name ?? 'Someone'}</th>
						<td style={{ ...cell, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{score.toLocaleString(world.webapp.language)}</td>
					</tr>
				))}
			</tbody>
		</table>
	);
}

// Using it, on a fake world.

// A fake world to build with: four players, each showing a score in its own data.
// Ann's score changes every second. Bob and Dan are even.
const quiz = {
	name: 'Quiz night',
	members: [
		{ name: 'Ann', data: { score: { every: 1000, value: (time) => 10 + (Math.floor(time / 1000) % 6) } } },
		{ name: 'Bob', data: { score: 13 } },
		{ name: 'Cleo', data: { score: 7 } },
		{ name: 'Dan', data: { score: 13 } },
	],
};

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

	if (error) return <p>Could not connect ({error.code}).</p>;
	if (!world) return <p>Connecting…</p>;
	return <Scoreboard world={world} />;
}
js
import { connectToHost } from '@unaiverse/gui-kit';

// The component: copy this part.

/**
 * Ranks the members by a number of their data, highest first. Equal scores
 * share a place (1, 2, 2, 4). Members without that number are left out.
 * @param {Array<object>} members - The members of the world.
 * @param {string} field - The name of the number in each member's `data`.
 * @returns {Array<{member: object, score: number, place: number}>} The ranking.
 */
function rank(members, field) {
	const scored = members
		.filter((member) => typeof member.data?.[field] === 'number')
		.map((member) => ({ member, score: member.data[field] }))
		.sort((a, b) => b.score - a.score);
	return scored.map((row) => ({ ...row, place: scored.findIndex((other) => other.score === row.score) + 1 }));
}

/**
 * Draws the members of the world into `container`, ranked by a number that
 * each one shows in its own data (a score, points, coins), highest first,
 * then draws them again as they change.
 * @param {HTMLElement} container - Where to draw it.
 * @param {object} world - The world, from connectToHost.
 * @param {{field?: string, title?: string}} [options] - The name of the number in each member's `data`
 *   (default 'score'), and the title of the table (default 'Scores').
 * @returns {() => void} Stops following the world and removes what it drew.
 */
export function scoreboard(container, world, { field = 'score', title = 'Scores' } = {}) {
	const cell = { padding: '8px 12px', textAlign: 'left' };
	/** Makes a cell of the table. */
	const makeCell = (tag, text, style = {}) => {
		const element = document.createElement(tag);
		element.textContent = text;
		Object.assign(element.style, cell, style);
		return element;
	};

	const table = document.createElement('table');
	Object.assign(table.style, { borderCollapse: 'collapse', minWidth: '260px' });
	const caption = table.createCaption();
	caption.textContent = title;
	Object.assign(caption.style, { textAlign: 'left', fontWeight: '600', padding: '0 0 8px' });
	const head = table.createTHead().insertRow();
	Object.assign(head.style, { fontSize: '13px', opacity: '0.7', borderBottom: '1px solid rgba(127, 127, 127, 0.3)' });
	for (const [text, align] of [['Place', 'left'], ['Name', 'left'], ['Score', 'right']]) {
		const heading = makeCell('th', text, { textAlign: align });
		heading.scope = 'col';
		head.append(heading);
	}
	const body = table.createTBody();
	container.append(table);

	// Called at once, then after every change of the world.
	const stop = world.subscribe((node) => {
		const rows = rank(node.members ?? [], field);
		if (rows.length === 0) {
			const row = document.createElement('tr');
			const empty = makeCell('td', 'No scores yet.', { opacity: '0.6' });
			empty.colSpan = 3;
			row.append(empty);
			body.replaceChildren(row);
			return;
		}
		body.replaceChildren(...rows.map(({ member, score, place }) => {
			const row = document.createElement('tr');
			Object.assign(row.style, { borderBottom: '1px solid rgba(127, 127, 127, 0.15)', background: place === 1 ? 'rgba(240, 165, 78, 0.18)' : 'transparent', fontWeight: place === 1 ? '600' : '400' });
			const name = makeCell('th', member.name ?? 'Someone', { fontWeight: 'inherit' });
			name.scope = 'row';
			row.append(
				makeCell('td', String(place)),
				name,
				makeCell('td', score.toLocaleString(node.webapp.language), { textAlign: 'right', fontVariantNumeric: 'tabular-nums' }),
			);
			return row;
		}));
	});

	return () => {
		stop();
		table.remove();
	};
}

// Using it, on a fake world.

// A fake world to build with: four players, each showing a score in its own data.
// Ann's score changes every second. Bob and Dan are even.
const quiz = {
	name: 'Quiz night',
	members: [
		{ name: 'Ann', data: { score: { every: 1000, value: (time) => 10 + (Math.floor(time / 1000) % 6) } } },
		{ name: 'Bob', data: { score: 13 } },
		{ name: 'Cleo', data: { score: 7 } },
		{ name: 'Dan', data: { score: 13 } },
	],
};

// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: quiz } });
const place = document.createElement('div');
document.body.append(place);
scoreboard(place, world);
Live, on a fake world
Open

In the example the score of Ann changes every second and moves her up and down the table.

The component reads member.data[field] for every entry of world.members (People and roles) and leaves out the members whose value is not a number. Without any such member the table shows "No scores yet.". Screen readers can read the board row by row because it is an HTML table with a caption, column headings and one row heading per member.

Props ​

PropDefaultWhat it is
world(required)The world, from useWorld.
field'score'The name of the number in the data of each member.
title'Scores'The caption of the table.

Parameters ​

scoreboard(container, world, options) draws the table into container and redraws its rows at every change of the world.

ParameterWhat it is
containerThe element to draw into.
worldThe world, from connectToHost.
options.fieldThe name of the number in the data of each member. Default 'score'.
options.titleThe caption of the table. Default 'Scores'.

It returns a function that unsubscribes from the world and removes the table.

Change it ​

  • Scores kept by the world: when the world publishes all the scores in its own data (for example world.data.scores as { Ann: 12, Bob: 13 }), build the rows from Object.entries of that object instead of from the members.
  • Lowest first for times or penalties: sort with a.score - b.score.
  • Only the top three: rows.slice(0, 3).
  • Show the change: keep the previous places and add an up or down arrow next to each member who moved.

See also ​

  • Members: everyone in the world with their roles.
  • WinnerBanner: the banner at the end of the game.
  • Chart: one number over time.

The UNaIVERSE GUI kit, released under the Apache License 2.0. Copyright 2024-2026 UNaIVERSE S.r.l.