Scoreboard
Ogni membro di un mondo può pubblicare nei suoi data un numero come i punti in un quiz, le monete in un mercato o l'accuratezza di un agente. Scoreboard mette in classifica i membri secondo quel numero dal più alto al più basso e aggiorna la classifica a ogni cambiamento. A numeri uguali corrisponde lo stesso posto (1, 2, 2, 4) e ogni membro al primo posto ha la riga evidenziata.
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} />;
}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);Nell'esempio il punteggio di Ann cambia ogni secondo e la fa salire e scendere nella tabella.
Il componente legge member.data[field] per ogni voce di world.members (Persone e ruoli) e lascia fuori i membri il cui valore non è un numero. Se nessun membro ha quel numero la tabella mostra "No scores yet.". Gli screen reader possono leggere la classifica riga per riga perché è una table HTML con una caption, le intestazioni delle colonne e un'intestazione di riga per ogni membro.
Props
| Prop | Predefinito | Che cos'è |
|---|---|---|
world | (obbligatorio) | Il mondo, da useWorld. |
field | 'score' | Il nome del numero nei data di ogni membro. |
title | 'Scores' | La didascalia della tabella. |
Parametri
scoreboard(container, world, options) disegna la tabella dentro container e ne ridisegna le righe a ogni cambiamento del mondo.
| Parametro | Che cos'è |
|---|---|
container | L'elemento in cui disegnare. |
world | Il mondo, da connectToHost. |
options.field | Il nome del numero nei data di ogni membro. Predefinito 'score'. |
options.title | La didascalia della tabella. Predefinito 'Scores'. |
Restituisce una funzione che annulla l'iscrizione al mondo e rimuove la tabella.
Modificalo
- Punteggi tenuti dal mondo: quando il mondo pubblica tutti i punteggi nei suoi dati (per esempio
world.data.scorescome{ Ann: 12, Bob: 13 }), costruisci le righe daObject.entriesdi quell'oggetto invece che dai membri. - Prima il più basso per tempi o penalità: ordina con
a.score - b.score. - Solo i primi tre:
rows.slice(0, 3). - Mostrare la variazione: conserva i posti precedenti e aggiungi una freccia in su o in giù accanto a ogni membro che si è spostato.
Vedi anche
Members: tutti quelli che sono nel mondo con i loro ruoli.WinnerBanner: il banner alla fine della partita.Chart: un numero nel tempo.