feat: enhanced stats — streak, hard comarques, evolution, group comparison, per-question tracking
- BD: ADD COLUMN filter_group on sessions; CREATE TABLE session_answers (per-question detail) - server.js: POST /api/sessions accepts filter_group + answers array; GET stats returns totalSeconds, currentStreak, avgPct+evolution per level (1-8), hardComarques, groupStats - index.html: sessionAnswers[] tracking in L2/L4/L5/L6/L7/L8; saveSession sends new fields; loadStats rewritten with streak badge, 4-box stats grid, sparklines on level bars, hard comarques section and group performance section
This commit is contained in:
213
index.html
213
index.html
@@ -79,6 +79,8 @@
|
||||
.stats-avatar{font-size:4rem;display:block;margin-bottom:6px;}
|
||||
.stats-name{font-size:1.5rem;font-weight:800;}
|
||||
.stats-stars{font-size:1.1rem;margin-top:4px;opacity:.9;}
|
||||
.stats-streak{font-size:1.3rem;font-weight:800;margin-top:8px;background:rgba(0,0,0,.15);
|
||||
border-radius:50px;display:inline-block;padding:4px 16px;}
|
||||
.stats-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:18px;}
|
||||
.stat-box{background:#fff;border-radius:14px;padding:16px;text-align:center;box-shadow:var(--shadow);}
|
||||
.stat-box .stat-val{font-size:2rem;font-weight:800;color:var(--dark-orange);}
|
||||
@@ -100,6 +102,24 @@
|
||||
.ri-score{flex:1;font-size:.9rem;font-weight:600;}
|
||||
.ri-stars{font-size:.9rem;}
|
||||
.ri-date{font-size:.72rem;color:#bbb;}
|
||||
/* Hard comarques section */
|
||||
.hard-comarques-section{background:#fff;border-radius:14px;padding:18px;
|
||||
box-shadow:var(--shadow);margin-bottom:18px;}
|
||||
.hc-row{display:flex;align-items:center;gap:10px;margin-bottom:10px;}
|
||||
.hc-row:last-child{margin-bottom:0;}
|
||||
.hc-name{font-size:.85rem;font-weight:700;width:120px;flex-shrink:0;color:#444;}
|
||||
.hc-track{flex:1;background:#eee;border-radius:50px;height:12px;overflow:hidden;}
|
||||
.hc-fill{height:100%;border-radius:50px;background:var(--red);transition:width .6s ease;}
|
||||
.hc-pct{font-size:.78rem;font-weight:700;width:44px;text-align:right;flex-shrink:0;color:var(--red);}
|
||||
/* Group stats section */
|
||||
.group-stats-section{background:#fff;border-radius:14px;padding:18px;
|
||||
box-shadow:var(--shadow);margin-bottom:18px;}
|
||||
.gs-row{display:flex;align-items:center;gap:10px;margin-bottom:10px;}
|
||||
.gs-row:last-child{margin-bottom:0;}
|
||||
.gs-name{font-size:.85rem;font-weight:700;width:100px;flex-shrink:0;color:#444;}
|
||||
.gs-track{flex:1;background:#eee;border-radius:50px;height:12px;overflow:hidden;}
|
||||
.gs-fill{height:100%;border-radius:50px;transition:width .6s ease;}
|
||||
.gs-pct{font-size:.78rem;font-weight:700;width:36px;text-align:right;flex-shrink:0;}
|
||||
|
||||
/* ── ADMIN ── */
|
||||
.admin-pin-wrap{max-width:320px;margin:0 auto 24px;}
|
||||
@@ -936,10 +956,14 @@ const LEVEL_NAMES = {1:'Descobreix',2:'Tria',3:'Uneix',4:'Escriu',5:'El Mapa',6:
|
||||
/* ══════════════════════════════════════════════════════
|
||||
ESTAT
|
||||
══════════════════════════════════════════════════════ */
|
||||
let currentPlayer = null;
|
||||
let offlineMode = false;
|
||||
let totalStars = 0;
|
||||
let sessionStart = null;
|
||||
let currentPlayer = null;
|
||||
let offlineMode = false;
|
||||
let totalStars = 0;
|
||||
let sessionStart = null;
|
||||
// Per-question answer tracking — reset at startLevel(), pushed on each answer
|
||||
let sessionAnswers = [];
|
||||
// Timestamp for the current question start (set when a new question is displayed)
|
||||
let questionStartTime = null;
|
||||
|
||||
let currentLevel=1, currentQ=0, score=0, questions=[];
|
||||
let fcFlipped=false, fcIndex=0;
|
||||
@@ -1006,8 +1030,17 @@ function addStars(n) {
|
||||
|
||||
async function saveSession(level, score, total, stars) {
|
||||
if (offlineMode || !currentPlayer) return;
|
||||
const duration = sessionStart ? Math.round((Date.now()-sessionStart)/1000) : 0;
|
||||
await apiPost('/api/sessions', { player_id: currentPlayer.id, level, score, total, stars, duration_seconds: duration });
|
||||
const duration = sessionStart ? Math.round((Date.now() - sessionStart) / 1000) : 0;
|
||||
const filter_group = [...activeGroups].join(',') || 'all';
|
||||
await apiPost('/api/sessions', {
|
||||
player_id: currentPlayer.id,
|
||||
level, score, total, stars,
|
||||
duration_seconds: duration,
|
||||
filter_group,
|
||||
answers: sessionAnswers,
|
||||
});
|
||||
// Reset answers for the next session
|
||||
sessionAnswers = [];
|
||||
}
|
||||
|
||||
/* ══════════════════════════════════════════════════════
|
||||
@@ -1147,6 +1180,54 @@ function goToStats() {
|
||||
loadStats();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render an inline SVG sparkline for the last N sessions' percentages.
|
||||
* @param {number[]} evolution Array of 0-100 values (chronological order).
|
||||
* @returns {string} SVG markup or empty string if not enough data.
|
||||
*/
|
||||
function sparkline(evolution) {
|
||||
if (!evolution || evolution.length < 2) return '';
|
||||
const w = 80, h = 24;
|
||||
const pts = evolution.map((v, i) => {
|
||||
const x = (i / (evolution.length - 1)) * w;
|
||||
const y = h - (v / 100) * h;
|
||||
return `${x},${y}`;
|
||||
}).join(' ');
|
||||
const last = evolution[evolution.length - 1];
|
||||
const lastColor = last >= 80 ? '#4DBD6E' : last >= 50 ? '#F4A535' : '#F05C5C';
|
||||
const lx = w; // last point x = w (always)
|
||||
const ly = h - (last / 100) * h;
|
||||
return `<svg width="${w}" height="${h}" style="display:inline-block;vertical-align:middle;opacity:.85;flex-shrink:0;">
|
||||
<polyline points="${pts}" fill="none" stroke="${lastColor}" stroke-width="2" stroke-linejoin="round"/>
|
||||
<circle cx="${lx}" cy="${ly}" r="3" fill="${lastColor}"/>
|
||||
</svg>`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format seconds as "Xh Ym" or "Ym" if under an hour.
|
||||
* @param {number} secs
|
||||
* @returns {string}
|
||||
*/
|
||||
function formatTime(secs) {
|
||||
if (!secs) return '0m';
|
||||
const h = Math.floor(secs / 3600);
|
||||
const m = Math.floor((secs % 3600) / 60);
|
||||
if (h > 0) return `${h}h ${m}m`;
|
||||
return `${m}m`;
|
||||
}
|
||||
|
||||
/** Group label mapping for display */
|
||||
const GROUP_LABELS = {
|
||||
mountain: '⛰️ Muntanya',
|
||||
interior: '🌄 Interior',
|
||||
coastal: '🏖️ Litoral',
|
||||
B: '🏙️ Barcelona',
|
||||
G: '🌊 Girona',
|
||||
L: '🏔️ Lleida',
|
||||
T: '☀️ Tarragona',
|
||||
all: '🗺️ Totes',
|
||||
};
|
||||
|
||||
async function loadStats() {
|
||||
if (offlineMode || !currentPlayer) {
|
||||
document.getElementById('stats-content').innerHTML =
|
||||
@@ -1161,11 +1242,20 @@ async function loadStats() {
|
||||
return;
|
||||
}
|
||||
|
||||
const ls = data.levelStats || {};
|
||||
const ls = data.levelStats || {};
|
||||
const streak = data.currentStreak || 0;
|
||||
const totalS = data.totalSeconds || 0;
|
||||
|
||||
// ── Hero streak badge ──────────────────────────────────────────────────────
|
||||
const streakBadge = streak > 0
|
||||
? `<div class="stats-streak">🔥 ${streak} ${streak === 1 ? 'dia seguit' : 'dies seguits'}!</div>`
|
||||
: '';
|
||||
|
||||
// ── Recent rows ────────────────────────────────────────────────────────────
|
||||
const recentRows = (data.recent || []).map(s => {
|
||||
const d = new Date(s.date);
|
||||
const dateStr = `${d.getDate()}/${d.getMonth()+1} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`;
|
||||
const pct = Math.round(s.score/s.total*100);
|
||||
const pct = Math.round(s.score / s.total * 100);
|
||||
return `<div class="recent-item">
|
||||
<span class="ri-lvl">${LEVEL_ICONS[s.level]}</span>
|
||||
<span class="ri-score">${LEVEL_NAMES[s.level]} · ${pct}%</span>
|
||||
@@ -1174,26 +1264,68 @@ async function loadStats() {
|
||||
</div>`;
|
||||
}).join('') || '<div style="color:#aaa;font-size:.85rem;text-align:center;padding:12px;">Cap sessió registrada</div>';
|
||||
|
||||
const barRows = [1,2,3,4,5,6,7].map(lvl => {
|
||||
const s = ls[lvl];
|
||||
// ── Level bars with sparkline ──────────────────────────────────────────────
|
||||
const barRows = [1,2,3,4,5,6,7,8].map(lvl => {
|
||||
const s = ls[lvl];
|
||||
const pct = s?.bestPct ?? null;
|
||||
const color = pct===null ? '#ddd' : pct>=80 ? '#4DBD6E' : pct>=50 ? '#F4A535' : '#F05C5C';
|
||||
const pctStr = pct===null ? '—' : pct+'%';
|
||||
const color = pct === null ? '#ddd' : pct >= 80 ? '#4DBD6E' : pct >= 50 ? '#F4A535' : '#F05C5C';
|
||||
const pctStr = pct === null ? '—' : pct + '%';
|
||||
const spark = s?.evolution ? sparkline(s.evolution) : '';
|
||||
return `<div class="level-bar-row">
|
||||
<span class="lbr-icon">${LEVEL_ICONS[lvl]}</span>
|
||||
<span class="lbr-name">${LEVEL_NAMES[lvl]}</span>
|
||||
<div class="lbr-track">
|
||||
<div class="lbr-fill" style="width:${pct??0}%;background:${color};"></div>
|
||||
<div class="lbr-fill" style="width:${pct ?? 0}%;background:${color};"></div>
|
||||
</div>
|
||||
<span class="lbr-pct" style="color:${color};">${pctStr}</span>
|
||||
${spark}
|
||||
</div>`;
|
||||
}).join('');
|
||||
|
||||
// ── Hard comarques ─────────────────────────────────────────────────────────
|
||||
let hardSection = '';
|
||||
if (data.hardComarques && data.hardComarques.length > 0) {
|
||||
const hardRows = data.hardComarques.map(hc => `
|
||||
<div class="hc-row">
|
||||
<span class="hc-name">${hc.comarca}</span>
|
||||
<div class="hc-track"><div class="hc-fill" style="width:${hc.errorRate}%;"></div></div>
|
||||
<span class="hc-pct">${hc.errorRate}% error</span>
|
||||
</div>`).join('');
|
||||
hardSection = `
|
||||
<div class="hard-comarques-section">
|
||||
<div class="q-label" style="margin-bottom:12px;">LES TEVES COMARQUES MÉS DIFÍCILS</div>
|
||||
${hardRows}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
// ── Group stats ────────────────────────────────────────────────────────────
|
||||
let groupSection = '';
|
||||
const gs = data.groupStats || {};
|
||||
const gsKeys = Object.keys(gs);
|
||||
if (gsKeys.length > 0) {
|
||||
const gsRows = gsKeys.map(key => {
|
||||
const g = gs[key];
|
||||
const color = g.avgPct >= 80 ? '#4DBD6E' : g.avgPct >= 50 ? '#F4A535' : '#F05C5C';
|
||||
const label = GROUP_LABELS[key] || key;
|
||||
return `<div class="gs-row">
|
||||
<span class="gs-name">${label}</span>
|
||||
<div class="gs-track"><div class="gs-fill" style="width:${g.avgPct}%;background:${color};"></div></div>
|
||||
<span class="gs-pct" style="color:${color};">${g.avgPct}%</span>
|
||||
</div>`;
|
||||
}).join('');
|
||||
groupSection = `
|
||||
<div class="group-stats-section">
|
||||
<div class="q-label" style="margin-bottom:12px;">RENDIMENT PER GRUP</div>
|
||||
${gsRows}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
document.getElementById('stats-content').innerHTML = `
|
||||
<div class="stats-hero">
|
||||
<span class="stats-avatar">${data.player.avatar}</span>
|
||||
<div class="stats-name">${data.player.name}</div>
|
||||
<div class="stats-stars">⭐ ${data.totalStars} estreles acumulades</div>
|
||||
${streakBadge}
|
||||
</div>
|
||||
<div class="stats-grid">
|
||||
<div class="stat-box">
|
||||
@@ -1204,11 +1336,21 @@ async function loadStats() {
|
||||
<div class="stat-val">${data.totalStars}</div>
|
||||
<div class="stat-lbl">Estreles totals</div>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<div class="stat-val">${streak > 0 ? streak + '🔥' : '0'}</div>
|
||||
<div class="stat-lbl">Dies de ratxa</div>
|
||||
</div>
|
||||
<div class="stat-box">
|
||||
<div class="stat-val" style="font-size:1.5rem;">⏱️ ${formatTime(totalS)}</div>
|
||||
<div class="stat-lbl">Temps total</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="level-bars">
|
||||
<div class="q-label" style="margin-bottom:14px;">MILLOR RESULTAT PER NIVELL</div>
|
||||
${barRows}
|
||||
</div>
|
||||
${hardSection}
|
||||
${groupSection}
|
||||
${data.recent?.length ? `
|
||||
<div class="recent-list">
|
||||
<div class="recent-title">ÚLTIMES PARTIDES</div>
|
||||
@@ -1416,6 +1558,8 @@ function goHome(){ showScreen('screen-home'); }
|
||||
|
||||
function startLevel(n){
|
||||
currentLevel=n; currentQ=0; score=0;
|
||||
sessionAnswers = []; // reset per-question tracking for the new session
|
||||
questionStartTime = null;
|
||||
COMARQUES = getActiveComarques(); // refresh from current filter
|
||||
// For map levels (5 & 6), exclude comarques without SVG path (noMap:true)
|
||||
const mapComarques = COMARQUES.filter(c => !c.noMap && COMARCA_PATHS[c.name]);
|
||||
@@ -1472,13 +1616,19 @@ function renderL2(){
|
||||
const grid=document.getElementById('l2-opts');grid.innerHTML='';
|
||||
opts.forEach(opt=>{
|
||||
const btn=document.createElement('button');btn.className='opt-btn';btn.textContent=opt.capital;
|
||||
btn.onclick=()=>handleL2(btn,opt.capital===q.capital,q.capital);grid.appendChild(btn);});
|
||||
btn.onclick=()=>handleL2(btn,opt.capital===q.capital,q.capital,q.name);grid.appendChild(btn);});
|
||||
// Start timing for this question
|
||||
questionStartTime = Date.now();
|
||||
}
|
||||
function handleL2(btn,ok,right){
|
||||
function handleL2(btn,ok,right,comarcaName){
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
document.querySelectorAll('.opt-btn').forEach(b=>b.disabled=true);
|
||||
btn.classList.add(ok?'correct':'wrong');
|
||||
if(!ok)document.querySelectorAll('.opt-btn').forEach(b=>{if(b.textContent===right)b.classList.add('correct');});
|
||||
if(ok)score++;showFeedback(ok);
|
||||
if(ok)score++;
|
||||
// Record this answer
|
||||
sessionAnswers.push({ comarca: comarcaName, correct: ok, response_ms });
|
||||
showFeedback(ok);
|
||||
setTimeout(()=>{currentQ++;renderL2();},1400);
|
||||
}
|
||||
|
||||
@@ -1522,13 +1672,18 @@ function renderL4(){
|
||||
document.getElementById('l4-input').style.borderColor='#ddd';
|
||||
document.getElementById('l4-fb').textContent='';
|
||||
document.getElementById('l4-input').focus();
|
||||
// Start timing for this question
|
||||
questionStartTime = Date.now();
|
||||
}
|
||||
function checkL4(){
|
||||
const q=questions[currentQ],val=document.getElementById('l4-input').value;
|
||||
const ok=normalize(val)===normalize(q.capital)||normalize(val)===normalize(q.capital.replace(/^(el |la |l')/i,''));
|
||||
const inp=document.getElementById('l4-input'),fb=document.getElementById('l4-fb');
|
||||
if(!val.trim()){fb.style.color='#aaa';fb.textContent='Escriu alguna cosa!';return;}
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
// Record this answer regardless of correctness
|
||||
sessionAnswers.push({ comarca: q.name, correct: ok, response_ms });
|
||||
if(ok){inp.style.borderColor='#5BC97A';fb.style.color='#1a7a3c';fb.textContent='✅ Correcte! La capital és '+q.capital;score++;showFeedback(true);setTimeout(()=>{currentQ++;renderL4();},1400);}
|
||||
else if(!val.trim()){fb.style.color='#aaa';fb.textContent='Escriu alguna cosa!';}
|
||||
else{inp.style.borderColor='#F05C5C';fb.style.color='#a02020';fb.textContent='❌ La capital és '+q.capital;showFeedback(false);setTimeout(()=>{currentQ++;renderL4();},2000);}
|
||||
}
|
||||
function skipL4(){const q=questions[currentQ];document.getElementById('l4-fb').style.color='#999';document.getElementById('l4-fb').textContent='➡ '+q.name+' → '+q.capital;setTimeout(()=>{currentQ++;renderL4();},1900);}
|
||||
@@ -1679,7 +1834,7 @@ function mapZoomReset(){
|
||||
if(svg) svg.setAttribute('viewBox',`0 0 ${MAP_W} ${MAP_H}`);
|
||||
}
|
||||
function nextMapQ(){
|
||||
if(currentQ>=questions.length){showResult(5);return;}
|
||||
if(currentQ>=questions.length){showResult(currentLevel===6?6:5);return;}
|
||||
mapAnswered=false;mapTarget=questions[currentQ];
|
||||
document.getElementById('map-prog').style.width=(currentQ/questions.length*100)+'%';
|
||||
document.getElementById('map-ctr').textContent=`Pregunta ${currentQ+1} de ${questions.length}`;
|
||||
@@ -1687,10 +1842,15 @@ function nextMapQ(){
|
||||
if(mapMode==='name'){document.getElementById('map-qlabel').textContent='TOCA LA COMARCA...';document.getElementById('map-qtext').textContent=mapTarget.emoji+' '+mapTarget.name;}
|
||||
else{document.getElementById('map-qlabel').textContent='QUINA COMARCA TÉ LA CAPITAL...';document.getElementById('map-qtext').textContent='📍 '+mapTarget.capital;}
|
||||
document.getElementById('map-qhint').textContent='';resetMapPaths();
|
||||
// Start timing for this question
|
||||
questionStartTime = Date.now();
|
||||
}
|
||||
function handleMapClick(path){
|
||||
if(mapAnswered)return;
|
||||
const clicked=path.getAttribute('data-name');const ok=clicked===mapTarget.name;mapAnswered=true;
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
// Record this answer
|
||||
sessionAnswers.push({ comarca: mapTarget.name, correct: ok, response_ms });
|
||||
if(ok){
|
||||
path.style.fill='#4DBD6E';path.style.filter='drop-shadow(0 0 12px #4DBD6E)';
|
||||
score++;showFeedback(true);document.getElementById('map-qhint').textContent='✅ Capital: '+mapTarget.capital;
|
||||
@@ -1795,12 +1955,15 @@ function renderMill() {
|
||||
|
||||
// Hide the Next button until an answer is chosen
|
||||
document.getElementById('mill-next').style.display = 'none';
|
||||
// Start timing for this question
|
||||
questionStartTime = Date.now();
|
||||
}
|
||||
|
||||
/** Handle option click. Disables all options, colours correct/wrong, shows Next. */
|
||||
function millAnswer(btn) {
|
||||
const chosen = btn.dataset.opt;
|
||||
const correct = btn.dataset.correct;
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
|
||||
// Disable all option buttons
|
||||
document.querySelectorAll('.mill-opt').forEach(b => {
|
||||
@@ -1808,7 +1971,11 @@ function millAnswer(btn) {
|
||||
b.onclick = null;
|
||||
});
|
||||
|
||||
if (chosen === correct) {
|
||||
const ok = chosen === correct;
|
||||
// Record this answer (comarca is the current millionari question target)
|
||||
sessionAnswers.push({ comarca: millQuestions[millQ].name, correct: ok, response_ms });
|
||||
|
||||
if (ok) {
|
||||
btn.classList.add('correct');
|
||||
millScore++;
|
||||
score++; // global score used by showResult()
|
||||
@@ -1985,6 +2152,8 @@ function _buildPuzzleTray() {
|
||||
el.addEventListener('pointerdown', _puzzleDragStart, {passive:false});
|
||||
tray.appendChild(el);
|
||||
}
|
||||
// Set initial question time for the first piece
|
||||
questionStartTime = Date.now();
|
||||
}
|
||||
|
||||
/** Comença el drag en prémer una peça de la safata. */
|
||||
@@ -2047,11 +2216,17 @@ function _puzzleDragEnd(e) {
|
||||
hit = Math.hypot(svgX - info.cx, svgY - info.cy) < 65;
|
||||
}
|
||||
if (hit) {
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
sessionAnswers.push({ comarca: name, correct: true, response_ms });
|
||||
questionStartTime = Date.now(); // reset for the next piece
|
||||
_puzzlePlace(name);
|
||||
trayEl.remove();
|
||||
} else {
|
||||
// Deixada incorrecta — torna a la safata
|
||||
puzzleWrong++;
|
||||
const response_ms = questionStartTime ? Date.now() - questionStartTime : 0;
|
||||
sessionAnswers.push({ comarca: name, correct: false, response_ms });
|
||||
questionStartTime = Date.now(); // reset timer even on wrong drop
|
||||
trayEl.style.opacity = '1';
|
||||
trayEl.style.pointerEvents = '';
|
||||
trayEl.style.animation = 'wShake .4s ease';
|
||||
|
||||
Reference in New Issue
Block a user