diff --git a/test/browser.mjs b/test/browser.mjs index 4ce4d94..79b7c09 100644 --- a/test/browser.mjs +++ b/test/browser.mjs @@ -91,6 +91,76 @@ try { 0, ); assert.equal(await page.locator(".player-board .inventory").count(), 0); + const scoreState = structuredClone(resourceCards); + scoreState.players[0].vp = 4; + scoreState.players[0].buildings = [{ id: "smallSugar", w: 0, c: 0 }]; + scoreState.events.push({ + type: "ship", + p: 0, + round: 1, + goods: { corn: 3 }, + vp: 4, + }); + await page.evaluate( + (s) => host.emit("state", s), + E.stripSecret(scoreState, 0), + ); + assert.equal( + await page.locator('.player-strip [data-score="1"]').count(), + 0, + ); + await page.locator('[data-player="1"] .player-name').click(); + await page.locator('.player-strip [data-score="0"]').press("Enter"); + assert.equal(await page.locator(".score-detail").count(), 1); + assert.match( + await page.locator(".score-detail").innerText(), + /Marchandises expédiées/, + ); + assert.match( + await page.locator(".score-detail").innerText(), + /Bonus d’expédition/, + ); + assert.match( + await page.locator(".score-detail").innerText(), + /Petite sucrerie/, + ); + assert.equal( + await page.locator('[data-player="1"].selected').count(), + 1, + "opening VP details does not switch boards", + ); + assert.deepEqual(await page.evaluate(() => played), []); + const total = E.scoreBreakdown(scoreState, 0).total; + assert.equal( + await page + .locator(".score-total .score-value") + .getAttribute("aria-label"), + `${total} Points de victoire`, + ); + await page.locator(".score-history summary").click(); + scoreState.players[0].vp++; + scoreState.events.push({ + type: "produce", + p: 0, + round: 2, + goods: {}, + vp: 1, + }); + await page.evaluate( + (s) => host.emit("state", s), + E.stripSecret(scoreState, 0), + ); + assert.match(await page.locator(".score-detail").innerText(), /Chapelle/); + assert.equal(await page.locator(".score-history").getAttribute("open"), ""); + assert.equal( + await page + .locator(".pr-modal") + .evaluate((el) => el.scrollWidth > el.clientWidth), + false, + ); + await page.screenshot({ path: `.local/qa/${width}-score-detail.png` }); + await page.keyboard.press("Escape"); + await page.locator('[data-player="0"] .player-name').click(); await page.evaluate( (s) => host.emit("state", s), E.stripSecret(original, 0), @@ -176,6 +246,25 @@ try { while (s.tasks[0].kind !== "recruit") s = E.moveAI(s); await page.evaluate((s) => host.emit("state", s), E.stripSecret(s, 0)); await page.evaluate(() => scrollTo(0, 0)); + assert.equal( + await page + .locator('.role[aria-current="step"]') + .getAttribute("data-role-id"), + "recruiter", + ); + assert.match(await page.locator(".role.current").innerText(), /En cours/); + const betweenRoles = structuredClone(s); + betweenRoles.tasks = [{ kind: "role", p: 1 }]; + await page.evaluate( + (s) => host.emit("state", s), + E.stripSecret(betweenRoles, 0), + ); + assert.equal( + await page.locator('.role[aria-current="step"]').count(), + 0, + "last role is not marked current during the next role choice", + ); + await page.evaluate((s) => host.emit("state", s), E.stripSecret(s, 0)); const recruitButtons = page.locator(".action-dock [data-move]"); assert.equal(await recruitButtons.count(), 2); for (const button of await recruitButtons.all()) { @@ -420,6 +509,8 @@ try { await page.locator("[data-scores]").click(); assert.equal(await overflow(), false); assert.ok((await page.locator(".scores article").count()) === 3); + await page.locator('.scores [data-score="1"]').click(); + assert.match(await page.locator(".score-total").innerText(), /Total final/); await page.keyboard.press("Escape"); // Scroll starts on disabled controls without interception. await page.evaluate( diff --git a/test/score-ui.test.js b/test/score-ui.test.js new file mode 100644 index 0000000..5ef56a6 --- /dev/null +++ b/test/score-ui.test.js @@ -0,0 +1,90 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import * as E from "../engine/index.js"; +import { RELEASE } from "../release-config.js"; +import { tokenSources, scoreContent } from "../viewer/score.js"; +import { translator } from "../viewer/i18n.js"; + +function fixture() { + const s = E.init(3, RELEASE.expansions, RELEASE.options, "score-ui"); + s.players[0].vp = 11; + s.events = [ + { p: 0, round: 1, type: "ship", goods: { corn: 3 }, vp: 5 }, + { p: 0, round: 1, type: "smallWharf", goods: { corn: 1, sugar: 2 }, vp: 2 }, + { p: 0, round: 1, type: "festival", id: "farming", reward: { vp: 3 } }, + { p: 0, round: 2, type: "pass", phase: "produce", vp: 1 }, + { p: 0, round: 2, type: "build", id: "smallSugar", vp: 1, point: 1 }, + { p: 1, round: 2, type: "ship", goods: { corn: 9 }, vp: 9 }, + ]; + return s; +} + +test("earned points reconcile shipping bonuses, festival rewards and spent tokens", () => { + assert.deepEqual(tokenSources(fixture(), 0), [ + { id: "scoreShipping", points: 4 }, + { id: "scoreShippingBonus", points: 3 }, + { id: "farming", points: 3 }, + { id: "chapel", points: 1 }, + { id: "church", points: 1 }, + { id: "hiddenMarket", points: -1 }, + ]); +}); + +test("score details use the canonical score and count only completed achievements", () => { + const s = fixture(); + s.players[0].buildings = [ + { id: "monument", w: 0, c: 0 }, + { id: "customsHouse", w: 1, c: 0 }, + ]; + s.players[0].reserve.c = 2; + s.players[0].achievements = [ + { id: "bigSpender", completed: true }, + { id: "dealCloser", completed: false }, + ]; + const r = E.scoreBreakdown(s, 0); + for (const locale of ["en", "fr"]) { + const t = translator(locale); + const html = scoreContent(E.stripSecret(s, 0), 0, t); + assert.ok(html.includes(`aria-label="${r.total} ${t("vp")}"`)); + assert.ok(html.includes(t("scoreEstimateTotal"))); + assert.ok(html.includes(t("customsHouse"))); + assert.ok(!html.includes("Négociateur")); + assert.ok(!html.includes("Deal Closer")); + } +}); + +test("hidden VP totals are not reconstructed from public history", () => { + const s = E.stripSecret(fixture(), 1); + assert.deepEqual(tokenSources(s, 0), []); + assert.equal( + scoreContent(s, 0, translator("fr")), + `

${translator("fr")("scoreHidden")}

`, + ); +}); + +test("incomplete history is labelled without inventing a source", () => { + const s = fixture(); + s.events = []; + assert.deepEqual(tokenSources(s, 0), [{ id: "scoreUnrecorded", points: 11 }]); +}); + +test("full games account for every earned token, including Puertoma rewards", () => { + for (const options of [ + RELEASE.options, + { ...RELEASE.options, puertoma: { humans: 1, difficulty: "normal" } }, + ]) { + let s = E.init(3, RELEASE.expansions, options, "score-audit"); + while (!s.finished) s = E.moveAI(s); + for (let p = 0; p < s.players.length; p++) { + const sources = tokenSources(s, p); + assert.ok(!sources.some((x) => x.id === "scoreUnrecorded")); + assert.equal( + sources.reduce((n, x) => n + x.points, 0), + s.players[p].vp, + ); + const html = scoreContent(E.stripSecret(s, p), p, translator("fr")); + assert.ok(html.includes("Total final")); + assert.ok(!html.includes("undefined")); + } + } +}); diff --git a/viewer/i18n.js b/viewer/i18n.js index 585ade2..3c5e497 100644 --- a/viewer/i18n.js +++ b/viewer/i18n.js @@ -329,6 +329,64 @@ const labels = { bohioMove: ["Move a Bohío worker", "Déplacer un ouvrier du Bohío"], outpost: ["Outpost", "Relais"], finalScore: ["Final scores", "Scores finaux"], + scoreDetails: ["Victory point breakdown", "Détail des points de victoire"], + scoreHidden: [ + "This player's VP tokens stay hidden until game end.", + "Les jetons PV de ce joueur restent cachés jusqu’à la fin de la partie.", + ], + scoreEarned: ["VP tokens earned", "Jetons PV gagnés"], + scoreCounterHint: [ + "These are the points shown on the player card.", + "Ce sont les points affichés sur la carte joueur.", + ], + scoreNoTokens: [ + "No VP tokens earned yet.", + "Aucun jeton PV gagné pour le moment.", + ], + scoreShipping: ["Goods shipped", "Marchandises expédiées"], + scoreShippingBonus: ["Shipping bonuses", "Bonus d’expédition"], + scoreShippingBonusHint: [ + "Captain privilege and building effects.", + "Privilège du Capitaine et effets des bâtiments.", + ], + scoreOther: ["Other rewards", "Autres récompenses"], + scoreUnrecorded: [ + "Points not detailed in the saved history", + "Points non détaillés dans l’historique sauvegardé", + ], + scoreSpent: [ + "VP tokens spent on construction.", + "Jetons PV dépensés pour construire.", + ], + scoreHistory: ["VP history", "Historique des PV"], + scoreEndGame: ["Added at game end", "À ajouter en fin de partie"], + scoreEstimateHint: [ + "Based on the current board; separate from the VP token counter. Building bonuses require an occupied building.", + "Selon le plateau actuel, en plus du compteur de jetons PV. Les bonus des bâtiments nécessitent un bâtiment occupé.", + ], + scoreFinalHint: [ + "These points are added to the VP tokens earned.", + "Ces points s’ajoutent aux jetons PV gagnés.", + ], + scoreBuildings: ["Printed building points", "Points imprimés des bâtiments"], + scoreCitizensHint: [ + "1 VP per citizen, including those in reserve.", + "1 PV par citoyen, y compris ceux en réserve.", + ], + scoreNoAchievements: [ + "No completed Achievements yet.", + "Aucun objectif personnel accompli pour le moment.", + ], + scoreSoloAchievements: [ + "In solo play, incomplete human Achievements score for Puertomas only.", + "En solo, les objectifs humains non accomplis rapportent des points uniquement aux Puertomas.", + ], + scoreFinalTotal: ["Final total", "Total final"], + scoreEstimateTotal: [ + "Total if the game ended now", + "Total si la partie finissait maintenant", + ], + currentRole: ["In progress", "En cours"], tie: ["Coins + goods (tiebreak)", "Pièces + marchandises (départage)"], tokens: ["VP tokens", "Jetons de score"], bonuses: ["Bonifications", "Bonus"], diff --git a/viewer/score.js b/viewer/score.js new file mode 100644 index 0000000..2a523d9 --- /dev/null +++ b/viewer/score.js @@ -0,0 +1,114 @@ +import { scoreBreakdown } from "../engine/index.js"; +import { BUILDINGS as B } from "../engine/catalog.js"; +import { achievementText, abilityTexts } from "./achievement-text.js"; +import { journalContent } from "./journal.js"; +import { icon, scoreToken } from "./icons.js"; + +const esc = (value) => + String(value ?? "").replace( + /[&<>"']/g, + (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + c + ], + ); +const sum = (values) => values.reduce((a, b) => a + b, 0); + +// Use recorded rewards, rather than today's buildings, to explain past gains. +export function tokenSources(state, player) { + if (!Number.isFinite(state.players[player]?.vp)) return []; + const sources = new Map(); + const add = (id, points) => { + if (points) sources.set(id, (sources.get(id) ?? 0) + points); + }; + for (const e of state.events ?? []) { + if (e.p !== player) continue; + if (e.type === "festival") add(e.id, e.reward?.vp); + else if (["ship", "smallWharf"].includes(e.type) && e.vp) { + const goods = sum(Object.values(e.goods ?? {})); + const base = e.type === "smallWharf" ? Math.floor(goods / 2) : goods; + add("scoreShipping", base); + add("scoreShippingBonus", e.vp - base); + } else if (e.vp) { + const source = + { + build: "church", + produce: "chapel", + pass: "chapel", + parkReward: "parkAuthority", + assembly: "assemblyHall", + pension: "pensionOffice", + plunder: "plunder", + }[e.type] ?? (e.type === "puertomaBonus" ? e.id : "scoreOther"); + add(source, e.vp); + } + if (e.type === "build") add("hiddenMarket", -(e.point ?? 0)); + } + const unrecorded = state.players[player].vp - sum([...sources.values()]); + add("scoreUnrecorded", unrecorded); + return [...sources].map(([id, points]) => ({ id, points })); +} + +export function scoreContent(state, player, t) { + const a = state.players[player]; + if (!a || !Number.isFinite(a.vp)) return `

${t("scoreHidden")}

`; + const score = state.results?.[player] ?? scoreBreakdown(state, player); + const points = (n) => + `${scoreToken(n, 28)}`; + const row = (label, n, hint = "") => + `
  • ${label}${hint ? `
    ${hint}
    ` : ""}
    ${points(n)}
  • `; + const label = (id) => esc(abilityTexts[id]?.[t.fr ? 1 : 0] ?? t(id)); + const sources = tokenSources(state, player); + const history = []; + let round; + for (const e of state.events ?? []) { + if ( + e.p !== player || + !(e.vp || e.reward?.vp || (e.type === "build" && e.point)) + ) + continue; + if (e.round !== round) { + round = e.round; + history.push({ type: "round", round }); + } + history.push(e); + } + const buildings = a.buildings + .map((b) => row(`${icon("building", 16)} ${esc(t(b.id))}`, B[b.id].vp)) + .join(""); + const completed = (a.achievements ?? []).filter((c) => c.completed); + const bonuses = Object.entries(score.bonus) + .map(([id, n]) => { + const detail = + id === "achievements" + ? state.puertoma + ? t("scoreSoloAchievements") + : completed + .map((c) => { + const card = achievementText(c.id, t); + return `${esc(card.name)} · ${card.vp} ${t.fr ? "PV" : "VP"}`; + }) + .join("
    ") || t("scoreNoAchievements") + : B[id] + ? t.effectHtml(id) + : ""; + return row(label(id), n, detail); + }) + .join(""); + return `
    +

    ${t("scoreEarned")}

    ${points(score.tokens)}
    +

    ${t("scoreCounterHint")}

    + ${sources.length ? `` : `

    ${t("scoreNoTokens")}

    `} + ${history.length ? `
    ${t("scoreHistory")}${journalContent({ ...state, events: history }, t)}
    ` : ""} +
    +

    ${t("scoreEndGame")}

    ${points(score.total - score.tokens)}
    +

    ${t(state.finished ? "scoreFinalHint" : "scoreEstimateHint")}

    + +
    + +
    `; +} diff --git a/viewer/style.css b/viewer/style.css index b8ffd7c..eb4bad8 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -212,6 +212,10 @@ background: transparent; border-width: 0 0 3px; border-radius: 0; + border-style: solid; + border-color: var(--line); + cursor: pointer; + touch-action: manipulation; } .pr-game .player-tab.turn { border-bottom-color: var(--gold); @@ -248,6 +252,26 @@ white-space: nowrap; font-weight: 650; } +.pr-game button.player-name { + min-height: 24px; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + justify-content: flex-start; +} +.pr-game .score-button { + padding: 0; + min-height: 28px; + min-width: 28px; + border: 0; + background: transparent; + border-radius: 4px; +} +.pr-game .score-button:hover { + background: var(--selected); + box-shadow: 0 0 0 1px var(--gold); +} .pr-game .player-tab > .metric { font-size: 12px; } @@ -407,6 +431,31 @@ .pr-game .role.taken > b { opacity: 0.58; } +.pr-game .role.current { + background: var(--selected); + border-color: var(--gold); + box-shadow: + inset 0 0 0 1px var(--gold), + 0 2px 0 var(--gold); + padding-top: 14px; +} +.pr-game .role.current > .role-icon, +.pr-game .role.current > b { + opacity: 1; +} +.pr-game .role.current .role-icon > .icon { + width: 26px; + height: 26px; +} +.pr-game .role-status { + position: absolute; + top: 2px; + left: 4px; + font-size: 9px; + font-weight: 750; + line-height: 12px; + color: var(--ink); +} .pr-game .role > .player-marker { position: absolute; top: 3px; @@ -1091,6 +1140,11 @@ justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid var(--line); + gap: 12px; +} +.pr-game dialog > header h2 { + min-width: 0; + overflow-wrap: anywhere; } .pr-game .modal-body { overflow: auto; @@ -1303,6 +1357,72 @@ display: grid; gap: 12px; } +.pr-game .score-detail { + display: grid; + gap: 22px; +} +.pr-game .score-detail section > header, +.pr-game .score-total, +.pr-game .score-lines > li, +.pr-game .score-building-list > li { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; +} +.pr-game .score-detail h3 { + margin: 0; + font-size: 15px; + text-transform: none; + letter-spacing: normal; +} +.pr-game .score-detail .score-note, +.pr-game .score-hint { + margin: 5px 0 0; + color: var(--muted); + font-size: 12px; + line-height: 1.5; +} +.pr-game .score-lines, +.pr-game .score-building-list { + list-style: none; + margin: 8px 0 0; + padding: 0; +} +.pr-game .score-lines > li { + align-items: flex-start; + padding: 9px 0; + border-top: 1px solid var(--line); +} +.pr-game .score-lines .score-label { + flex: 1; + min-width: 0; +} +.pr-game .score-value { + display: inline-flex; + flex-shrink: 0; +} +.pr-game .score-building-list { + margin-right: 6px; +} +.pr-game .score-building-list > li { + padding: 3px 0; +} +.pr-game .score-building-list .score-token { + width: 22px; + height: 22px; +} +.pr-game .score-history summary { + cursor: pointer; + padding: 8px 0; + font-size: 12px; + font-weight: 600; +} +.pr-game .score-total { + background: var(--selected); + border-top: 2px solid var(--gold); + padding: 12px; +} .pr-game .scores article { border: 1px solid var(--line); border-radius: 8px; diff --git a/viewer/ui.js b/viewer/ui.js index aa17f80..2ca4c2c 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -14,6 +14,7 @@ import { import { translator } from "./i18n.js"; import { icon, scoreToken } from "./icons.js"; import { journalContent } from "./journal.js"; +import { scoreContent } from "./score.js"; import { buildingSymbols } from "./building-symbols.js"; import { richText } from "./rich-text.js"; import { town } from "./town.js"; @@ -73,6 +74,7 @@ export function mountGame( tool = "w", lastFocus, modalMode = "", + scorePlayer = null, actionContext = "", roleConfirmation = null, scrollLog = 0; @@ -112,6 +114,10 @@ export function mountGame( }; const pointsBadge = (n) => `${scoreToken(n, 28)}`; + const scoreButton = (i, n = state.players[i].vp) => + Number.isFinite(n) + ? `` + : `${metric("vp", "?")}`; let chatView; function configureChat() { if (!chat) return; @@ -484,12 +490,19 @@ export function mountGame( function sharedBoard() { const acting = allowed(), task = state.tasks[0]; + const currentRole = + !state.finished && task && task.kind !== "role" + ? state.role === "adventurer" + ? state.events.filter((e) => e.type === "role").at(-1)?.id + : state.role + : null; return `
    ${state.roles .map((r) => { const m = state.legal.find((m) => m.type === "role" && m.id === r.id), selected = r.taken !== null, + current = r.id === currentRole, warning = m && acting ? state.roleWarnings?.[r.id] : null; - return ``; + return ``; }) .join( "", @@ -538,7 +551,7 @@ export function mountGame( const stock = goods.length ? `${goods.map((g) => metric(g, p.goods[g])).join("")}` : ""; - return ``; + return `
    ${metric("coin", p.coins)}${scoreButton(i)}${people || stock ? `${people}${stock}` : ""}
    `; } function playerSummary() { const a = state.players[seat]; @@ -546,7 +559,7 @@ export function mountGame( const reserve = playerReserve(a, seat); const stat = (id, n, label) => `${metric(id, n)}`; - return ``; + return ``; } function market() { const task = state.tasks[0], @@ -731,6 +744,23 @@ export function mountGame( body.innerHTML = journal(); body.scrollTop = scrollLog; } + if (modal.open && modalMode === "score") { + if (!Number.isFinite(state.players[scorePlayer]?.vp)) hide(modal); + else { + modal.querySelector("h2").textContent = + `${t("vp")} · ${state.players[scorePlayer].name}`; + morphdom( + body, + ``, + { + childrenOnly: true, + onBeforeElUpdated(from, to) { + if (from.tagName === "DETAILS" && from.open) to.open = true; + }, + }, + ); + } + } } function roleReference(id) { const solo = id === "smuggler" || id.startsWith("adventurer"); @@ -826,7 +856,7 @@ export function mountGame( `
    ${(state.results ?? []) .map( (r, i) => - `

    ${esc(state.players[i].name)}

    ${metric("vp", r.total)}

    ${t("tokens")} ${r.tokens}

    ${t("market")} ${r.buildings}

    ${t("citizens")} ${r.citizens}

    ${Object.entries( + `

    ${esc(state.players[i].name)}

    ${scoreButton(i, r.total)}

    ${t("tokens")} ${r.tokens}

    ${t("market")} ${r.buildings}

    ${t("citizens")} ${r.citizens}

    ${Object.entries( r.bonus, ) .map(([id, n]) => `

    ${t(id)} ${n}

    `) @@ -921,6 +951,22 @@ export function mountGame( } function click(event) { const el = event.target.closest("button"); + if (el?.hasAttribute("data-score")) { + scorePlayer = Number(el.dataset.score); + if (Number.isFinite(state.players[scorePlayer]?.vp)) + show( + `${t("vp")} · ${state.players[scorePlayer].name}`, + scoreContent(state, scorePlayer, t), + "score", + ); + return; + } + const card = event.target.closest("[data-player]"); + if (card) { + view = Number(card.dataset.player); + render(); + return; + } if (!el || el.disabled) return; if (el.hasAttribute("data-close")) { hide(el.closest("dialog")); @@ -976,11 +1022,6 @@ export function mountGame( festivalInfo(Number(el.dataset.festival)); return; } - if (el.dataset.player !== undefined) { - view = Number(el.dataset.player); - render(); - return; - } if (el.dataset.local) { localControls?.(el.dataset.local); return;