From 50c26f5efa7cc3efdf0fbe65a2d04622efddb888 Mon Sep 17 00:00:00 2001 From: Pablo Date: Wed, 4 Nov 2026 20:31:46 +0100 Subject: [PATCH] feat: ronda 1 con muestra de tipos (dishTypeCandidateMax) y quitar tipos en el setup (#25) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit game-config.json definía dishTypeCandidateMax pero nadie lo usaba: la ronda 1 enseñaba todos los tipos, y con la biblioteca ampliada (~19) cada jugador tendría que deslizar 19 cartas. - shared.js: pickDishTypes(dishTypes, max) baraja y se queda con como mucho max (0 o sin valor = todos). Tests: tamaño, sin repetidos, aleatoriedad, max 0/mayor que el catálogo, sin mutar, valor por defecto 8-10. - Juego: la ronda 1 usa pickDishTypes sobre los tipos en juego. Los chips del setup pasan a ser botones conmutables (aria-pressed) para quitar tipos en esa partida (no se recuerda); siempre queda al menos uno. Un resumen indica cuántos hay en juego y si se sortearán. El render conserva el foco también por data-id. - Admin: campo "Tipos de cena en la ronda 1" en ajustes globales; los tres ajustes se validan con el lector común intReader() (antes `|| 2` / `|| 8`, y se podía guardar max < min). - CI: data.test valida dishTypeCandidateMax (entero >= 0). - Docs: PROJECT.md §4 y §5, CHANGELOG. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ PROJECT.md | 11 +++++++--- css/style.css | 2 ++ js/admin.js | 47 +++++++++++++++++++++++++++++-------------- js/app.js | 44 ++++++++++++++++++++++++++++++++++------ js/shared.js | 10 +++++++++ tests/data.test.mjs | 3 +++ tests/shared.test.mjs | 42 +++++++++++++++++++++++++++++++++++++- 8 files changed, 140 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff1d45e..6c089b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,9 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). siempre en texto (también en "También coincidisteis en" y en el admin); chips del admin usables con teclado; `prefers-reduced-motion`. - Deshacer el último voto del turno con "↶ Deshacer" o Ctrl+Z (#26). +- Ronda 1 con muestra de tipos: salen como mucho `dishTypeCandidateMax` + (10 por defecto) elegidos al azar. En el setup se pueden quitar tipos para + esa partida tocando su chip. El admin permite editar el ajuste (#25). ### Cambiado - Contraste WCAG AA: botones rellenos `#E1472B` → `#C93A1F`, textos @@ -31,6 +34,9 @@ Formato basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1.1.0/). o con red lenta, arranca desde caché (#5). ### Corregido +- Admin, ajustes globales: mínimo y máximo de jugadores se validan (antes + `|| 2` / `|| 8` sustituían valores inválidos en silencio, y se podía + guardar un máximo menor que el mínimo) (#25). - Admin: el foco ya no se pierde al re-renderizar. Al cambiar de pestaña queda en la pestaña; al abrir un formulario, en su primer campo; al guardar o cancelar, en el ✎ de la fila; al borrar, en la fila siguiente; diff --git a/PROJECT.md b/PROJECT.md index 889f4e3..0e6e4c2 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -82,6 +82,10 @@ suficiente para cambiar el contenido sin redeploy manual. { "minPlayers": 2, "maxPlayers": 8, "dishTypeCandidateMax": 10 } ``` Ajustes globales, independientes del tipo de cena elegido. +`dishTypeCandidateMax` es cuántos tipos de cena, como máximo, salen en la +ronda 1 (elegidos al azar entre los que estén en juego; `0` = todos). Con +muchos tipos evita que cada jugador tenga que deslizar decenas de cartas. +Por defecto, 10. ### `data/types//ingredients.json` ```json @@ -133,9 +137,10 @@ tipo. - **`buildBalancedPool(ingredients, config)`**: agrupa por `cat`, muestrea hasta `categoryCaps[cat]` de cada grupo (barajado), concatena y recorta a - `ingredientPoolSize`. Se usa en la ronda 2. La ronda 1 no lo usa: baraja - todos los tipos de `dish-types.json` con `shuffle` (limitar cuántos se - enseñan es la issue de `dishTypeCandidateMax`). + `ingredientPoolSize`. Se usa en la ronda 2. +- **`pickDishTypes(dishTypes, max)`**: mazo de la ronda 1. Baraja los tipos + en juego (los de `dish-types.json` menos los que el grupo quite en el + setup) y se queda con como mucho `dishTypeCandidateMax`. - **Match**: intersección de los ids marcados "sí" por todos los jugadores, en cualquier ronda. - **`resolveDishType(matchedTypes)`**: si hay más de un tipo de cena diff --git a/css/style.css b/css/style.css index 5f6853f..c25ecf4 100644 --- a/css/style.css +++ b/css/style.css @@ -95,6 +95,8 @@ button { font-family: inherit; } .dish-visual.stack .plate-fill { inset: 14px; border-radius: 18px; background: repeating-linear-gradient(180deg, #C97A2E 0 14%, #8B5A2B 14% 20%, #6B8F47 20% 28%, #E1472B 28% 34%, #C97A2E 34% 48%, #8B5A2B 48% 54%, #C97A2E 54% 68%); } .chip-list { width: 100%; display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin-bottom: 22px; } .chip { background: #241A15; border: 1px solid rgba(247,237,221,0.12); border-radius: 999px; padding: 6px 12px; font-size: 13px; display: flex; align-items: center; gap: 6px; } +.chip-toggle { font: inherit; font-size: 13px; color: #F7EDDD; cursor: pointer; } +.chip-toggle.off { color: rgba(247,237,221,0.62); text-decoration: line-through; border-style: dashed; } .empty-msg { text-align: center; color: rgba(247,237,221,0.55); font-size: 14px; margin-bottom: 26px; padding: 0 10px; } .extra-pizza-row { width: 100%; display: flex; flex-direction: column; gap: 8px; margin-bottom: 22px; } .extra-pizza { background: #241A15; border: 1px solid rgba(247,237,221,0.1); border-radius: 14px; padding: 12px 14px; display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; } diff --git a/js/admin.js b/js/admin.js index f23e854..3fdcc8e 100644 --- a/js/admin.js +++ b/js/admin.js @@ -273,8 +273,9 @@ function dishTypesTab() { return `
Ajustes globales
-
-
+
+
+
${formHTML} @@ -422,6 +423,22 @@ function configTab() { `; } +// Lectura de inputs numéricos: entero >= min; vacío → `fallback`. Un valor +// inválido no se sustituye en silencio: se anota en `errors`, se marca +// aria-invalid y devuelve undefined (quien llama avisa y no guarda). +function intReader() { + const errors = []; + const readInt = (input, label, min, fallback) => { + const raw = input.value.trim(); + if (raw === "") return fallback; + const n = Number(raw); + if (!Number.isInteger(n) || n < min) { errors.push(`${label} debe ser un entero ≥ ${min}`); input.setAttribute("aria-invalid", "true"); return undefined; } + input.removeAttribute("aria-invalid"); + return n; + }; + return { readInt, errors }; +} + // ---- Foco ---- // render() reescribe #app con innerHTML y destruye el elemento con foco. // Por defecto se devuelve el foco a su equivalente tras repintar (mismo id o @@ -554,8 +571,18 @@ document.getElementById("app").addEventListener("click", async (e) => { saveDraft(); render(); toast("Tipo de cena guardado"); } else if (action === "save-gameconfig") { - state.gameConfig.minPlayers = +document.getElementById("gc-min").value || 2; - state.gameConfig.maxPlayers = +document.getElementById("gc-max").value || 8; + const { readInt, errors } = intReader(); + const minInput = document.getElementById("gc-min"); + const maxInput = document.getElementById("gc-max"); + const minPlayers = readInt(minInput, "Jugadores mínimo", 1, 2); + const maxPlayers = readInt(maxInput, "Jugadores máximo", 1, 8); + const typeMax = readInt(document.getElementById("gc-typemax"), "Tipos en la ronda 1", 0, 10); + if (!errors.length && maxPlayers < minPlayers) { + errors.push("Jugadores máximo no puede ser menor que el mínimo"); + maxInput.setAttribute("aria-invalid", "true"); + } + if (errors.length) { toast(errors[0]); document.querySelector('[aria-invalid="true"]')?.focus(); return; } + Object.assign(state.gameConfig, { minPlayers, maxPlayers, dishTypeCandidateMax: typeMax }); saveDraft(); toast("Ajustes globales guardados"); } @@ -646,17 +673,7 @@ document.getElementById("app").addEventListener("click", async (e) => { } else if (action === "save-config") { const t = currentType(); - // Enteros >= min; vacío → valor por defecto (o "sin tope" en categorías). - // Un valor inválido no se sustituye en silencio: se avisa y no se guarda. - const errors = []; - const readInt = (input, label, min, fallback) => { - const raw = input.value.trim(); - if (raw === "") return fallback; - const n = Number(raw); - if (!Number.isInteger(n) || n < min) { errors.push(`${label} debe ser un entero ≥ ${min}`); input.setAttribute("aria-invalid", "true"); return undefined; } - input.removeAttribute("aria-invalid"); - return n; - }; + const { readInt, errors } = intReader(); const pool = readInt(document.getElementById("cfg-pool"), "Tamaño del mazo", 0, 0); const candMax = readInt(document.getElementById("cfg-candmax"), "Recetas candidatas", 1, 6); const candMin = readInt(document.getElementById("cfg-candmin"), "Solapamiento mínimo", 0, 2); diff --git a/js/app.js b/js/app.js index 2b1a7ad..1968d7a 100644 --- a/js/app.js +++ b/js/app.js @@ -1,4 +1,4 @@ -import { loadGameConfig, loadTypeData, shuffle, hashStr, esc, buildBalancedPool, pickCandidates, resolveDishType, ingObjs } from "./shared.js"; +import { loadGameConfig, loadTypeData, shuffle, hashStr, esc, buildBalancedPool, pickCandidates, pickDishTypes, resolveDishType, ingObjs } from "./shared.js"; const PLAYER_COLORS = ["#E1472B", "#E8A33D", "#6B8F47", "#B4654A", "#C98A3E", "#8C9E5E", "#D3562F", "#A46B2E"]; @@ -63,6 +63,30 @@ function showError(title, detail, retry) { render(); } +// Tipos que el grupo ha quitado hoy en el setup ("hoy no quiero pizza"). +// No se guarda: es una decisión de cada partida. +const excludedTypes = new Set(); +const typesInPlay = () => dishTypes.filter((t) => !excludedTypes.has(t.id)); + +function toggleType(id) { + if (!excludedTypes.has(id) && typesInPlay().length === 1) { + announce("Tiene que quedar al menos un tipo de cena en juego"); + return; + } + excludedTypes.has(id) ? excludedTypes.delete(id) : excludedTypes.add(id); + render(); + const t = dishTypes.find((x) => x.id === id); + announce(`${t.name} ${excludedTypes.has(id) ? "fuera" : "en juego"}. ${roundOneSummary()}`); +} + +function roundOneSummary() { + const n = typesInPlay().length; + const max = gameConfig.dishTypeCandidateMax; + return max > 0 && n > max + ? `${n} tipos en juego: en la ronda 1 saldrán ${max} al azar.` + : `${n} tipo${n === 1 ? "" : "s"} en juego.`; +} + const NAMES_KEY = "dinnerMatchNames"; const defaultName = (i) => `Jugador ${i + 1}`; @@ -93,7 +117,7 @@ function startRound1() { state.names = state.names.map((n, i) => n.trim() || defaultName(i)); try { localStorage.setItem(NAMES_KEY, JSON.stringify(state.names)); } catch { /* modo privado, sin cuota… */ } state.round = 1; - state.deck = shuffle(dishTypes); + state.deck = pickDishTypes(typesInPlay(), gameConfig.dishTypeCandidateMax); state.likesByPlayer = Array.from({ length: state.numPlayers }, () => []); state.playerIdx = 0; state.cardIdx = 0; @@ -289,10 +313,16 @@ function renderSetup() {
Nombres
${state.names.map((n, i) => ``).join("")} -
Tipos de cena en juego
-
    - ${dishTypes.map((t) => `
  • ${emo(t.emoji)}${esc(t.name)}
  • `).join("")} +
    Tipos de cena en juego
    +
    +
      + ${dishTypes.map((t) => { + const on = !excludedTypes.has(t.id); + return `
    • `; + }).join("")}
    +
    +

    ${esc(roundOneSummary())} Toca un tipo para quitarlo hoy.

    ${emo("⚙️")} Configurar tipos, ingredientes y recetas @@ -488,7 +518,8 @@ function render() { // devolvérselo a su equivalente (p. ej. el botón + del stepper). const prevFocus = document.activeElement?.closest?.("#app [data-action], #app [data-name-idx]"); const prevFocusSel = prevFocus - ? (prevFocus.dataset.nameIdx !== undefined ? `[data-name-idx="${prevFocus.dataset.nameIdx}"]` : `[data-action="${prevFocus.dataset.action}"]`) + ? (prevFocus.dataset.nameIdx !== undefined ? `[data-name-idx="${prevFocus.dataset.nameIdx}"]` + : `[data-action="${prevFocus.dataset.action}"]` + (prevFocus.dataset.id ? `[data-id="${CSS.escape(prevFocus.dataset.id)}"]` : "")) : null; app.innerHTML = (renderers[state.stage] || renderLoading)(); @@ -546,6 +577,7 @@ document.getElementById("app").addEventListener("click", (e) => { else if (action === "swipe-no") triggerSwipe(false); else if (action === "swipe-yes") triggerSwipe(true); else if (action === "undo") undoSwipe(); + else if (action === "toggle-type") toggleType(btn.dataset.id); else if (action === "start-round2") startRound2(); else if (action === "start-round3") startRound3(); else if (action === "reset") resetAll(); diff --git a/js/shared.js b/js/shared.js index 7489cc1..531621d 100644 --- a/js/shared.js +++ b/js/shared.js @@ -121,6 +121,16 @@ export function pickCandidates(matchedIds, recipes, config) { return merged.slice(0, max); } +/** + * Mazo de la ronda 1: muestra aleatoria de como mucho `max` tipos de cena + * (`game-config.json → dishTypeCandidateMax`), para que la ronda no se haga + * eterna con muchos tipos. Sin `max` (o con 0) entran todos, barajados. + */ +export function pickDishTypes(dishTypes, max) { + const deck = shuffle(dishTypes); + return max > 0 ? deck.slice(0, max) : deck; +} + /** * Resuelve el tipo de cena elegido a partir de los tipos matcheados en la * ronda 1. Si hay más de uno, se sortea entre los empatados. diff --git a/tests/data.test.mjs b/tests/data.test.mjs index 26b2612..226a727 100644 --- a/tests/data.test.mjs +++ b/tests/data.test.mjs @@ -31,6 +31,9 @@ test("game-config.json tiene un rango de jugadores válido", () => { const gc = readJSON("data/game-config.json"); assert.ok(Number.isInteger(gc.minPlayers) && gc.minPlayers >= 1, "minPlayers"); assert.ok(Number.isInteger(gc.maxPlayers) && gc.maxPlayers >= gc.minPlayers, "maxPlayers >= minPlayers"); + if ("dishTypeCandidateMax" in gc) { + assert.ok(Number.isInteger(gc.dishTypeCandidateMax) && gc.dishTypeCandidateMax >= 0, "dishTypeCandidateMax debe ser un entero >= 0 (0 = todos)"); + } }); const dishTypes = readJSON("data/dish-types.json"); diff --git a/tests/shared.test.mjs b/tests/shared.test.mjs index 1b33024..c9a3b34 100644 --- a/tests/shared.test.mjs +++ b/tests/shared.test.mjs @@ -6,7 +6,7 @@ import { test, describe } from "node:test"; import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; -import { buildBalancedPool, pickCandidates, resolveDishType, shuffle } from "../js/shared.js"; +import { buildBalancedPool, pickCandidates, pickDishTypes, resolveDishType, shuffle } from "../js/shared.js"; // Las funciones usan Math.random: las propiedades se comprueban en muchas // ejecuciones para no depender de una única barajada afortunada. @@ -239,6 +239,46 @@ describe("pickCandidates", () => { } }); +describe("pickDishTypes", () => { + const types = Array.from({ length: 19 }, (_, i) => ({ id: `t${i}`, name: `T${i}` })); + + test("nunca devuelve más de max tipos, sin repetidos y solo del catálogo", () => { + const catalog = new Set(ids(types)); + for (let r = 0; r < RUNS; r++) { + const out = ids(pickDishTypes(types, 10)); + assert.equal(out.length, 10); + assert.equal(new Set(out).size, 10); + assert.ok(out.every((id) => catalog.has(id))); + } + }); + + test("todos los tipos pueden salir (la muestra es aleatoria, no siempre los primeros)", () => { + const seen = new Set(); + for (let r = 0; r < RUNS; r++) for (const id of ids(pickDishTypes(types, 10))) seen.add(id); + assert.equal(seen.size, types.length); + }); + + test("con menos tipos que max, max 0 o sin max: entran todos, barajados", () => { + for (const max of [50, 19, 0, undefined]) { + assert.deepEqual(ids(pickDishTypes(types, max)).sort(), ids(types).sort(), `max=${max}`); + } + const orders = new Set(); + for (let r = 0; r < 20; r++) orders.add(ids(pickDishTypes(types, 0)).join()); + assert.ok(orders.size > 1, "no baraja"); + }); + + test("no muta la lista de entrada", () => { + const snapshot = structuredClone(types); + pickDishTypes(types, 5); + assert.deepEqual(types, snapshot); + }); + + test(`game-config.json: dishTypeCandidateMax por defecto razonable (8-10)`, () => { + const max = readJSON("data/game-config.json").dishTypeCandidateMax; + assert.ok(max >= 8 && max <= 10, String(max)); + }); +}); + describe("resolveDishType", () => { const types = [{ id: "pizza" }, { id: "hamburguesa" }, { id: "ensalada" }];