Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down
11 changes: 8 additions & 3 deletions PROJECT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<id>/ingredients.json`
```json
Expand Down Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
47 changes: 32 additions & 15 deletions js/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,8 +273,9 @@ function dishTypesTab() {
return `
<div class="card-panel" style="margin-bottom:16px;">
<div class="row-label mono">Ajustes globales</div>
<div class="config-row"><label for="gc-min">Jugadores mínimo</label><input class="text-input" style="margin:0;" id="gc-min" type="number" value="${gc.minPlayers}" /></div>
<div class="config-row"><label for="gc-max">Jugadores máximo</label><input class="text-input" style="margin:0;" id="gc-max" type="number" value="${gc.maxPlayers}" /></div>
<div class="config-row"><label for="gc-min">Jugadores mínimo</label><input class="text-input" style="margin:0;" id="gc-min" type="number" min="1" step="1" inputmode="numeric" value="${esc(gc.minPlayers ?? 2)}" /></div>
<div class="config-row"><label for="gc-max">Jugadores máximo</label><input class="text-input" style="margin:0;" id="gc-max" type="number" min="1" step="1" inputmode="numeric" value="${esc(gc.maxPlayers ?? 8)}" /></div>
<div class="config-row"><label for="gc-typemax">Tipos de cena en la ronda 1 <span class="visual-badge">al azar · 0 = todos</span></label><input class="text-input" style="margin:0;" id="gc-typemax" type="number" min="0" step="1" inputmode="numeric" value="${esc(gc.dishTypeCandidateMax ?? 10)}" /></div>
<button class="cta small" data-action="save-gameconfig">Guardar ajustes globales</button>
</div>
${formHTML}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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");
}

Expand Down Expand Up @@ -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);
Expand Down
44 changes: 38 additions & 6 deletions js/app.js
Original file line number Diff line number Diff line change
@@ -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"];

Expand Down Expand Up @@ -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}`;

Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -289,10 +313,16 @@ function renderSetup() {
</div>
<div class="row-label mono">Nombres</div>
${state.names.map((n, i) => `<input class="name-input" data-name-idx="${i}" maxlength="16" value="${esc(n)}" aria-label="Nombre del jugador ${i + 1}" />`).join("")}
<div class="row-label mono" style="margin-top:14px;">Tipos de cena en juego</div>
<ul class="chip-list" style="margin-bottom:0;">
${dishTypes.map((t) => `<li class="chip">${emo(t.emoji)}${esc(t.name)}</li>`).join("")}
<div class="row-label mono" style="margin-top:14px;" id="types-label">Tipos de cena en juego</div>
<div role="group" aria-labelledby="types-label" aria-describedby="types-summary">
<ul class="chip-list" style="margin-bottom:8px;">
${dishTypes.map((t) => {
const on = !excludedTypes.has(t.id);
return `<li><button type="button" class="chip chip-toggle${on ? "" : " off"}" data-action="toggle-type" data-id="${esc(t.id)}" aria-pressed="${on}">${emo(on ? t.emoji : "🚫")}${esc(t.name)}</button></li>`;
}).join("")}
</ul>
</div>
<p class="subtitle" id="types-summary" style="margin:0; font-size:12px;">${esc(roundOneSummary())} Toca un tipo para quitarlo hoy.</p>
</div>
<button class="cta" data-action="start-round1" data-autofocus>${emo("🍽️")} Empezar ronda 1</button>
<a href="./admin.html" class="cta ghost small" style="text-decoration:none; text-align:center;">${emo("⚙️")} Configurar tipos, ingredientes y recetas</a>
Expand Down Expand Up @@ -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)();
Expand Down Expand Up @@ -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();
Expand Down
10 changes: 10 additions & 0 deletions js/shared.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 3 additions & 0 deletions tests/data.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
42 changes: 41 additions & 1 deletion tests/shared.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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" }];

Expand Down
Loading