Iniciación a las matemáticas - 2 - La isla de los números Obtener enlace Facebook X Pinterest Correo electrónico Otras aplicaciones <!doctype html> <html lang="es"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>La isla de los números · Infantil</title> <style> :root{font-family:"Trebuchet MS",system-ui,sans-serif;color:#192d30;background:#f8f7ed;--ink:#192d30;--muted:#476163;--paper:#fffef8;--teal:#00635a;--rule:#d4ded4} *{box-sizing:border-box} [hidden]{display:none!important} body{margin:0} button,input{font:inherit} button{color:inherit;cursor:pointer} button:disabled{cursor:default} button:focus-visible,input:focus-visible,summary:focus-visible{outline:3px solid #6351bb;outline-offset:3px} button,.button{min-height:46px;border:1px solid #9aada8;border-radius:14px;background:#fff;padding:.65rem 1rem;font-weight:750} button:hover:not(:disabled){filter:brightness(.96)} button.primary{background:var(--teal);color:#fff;border-color:var(--teal)} main{max-width:1010px;margin:auto;padding:0 clamp(12px,4vw,44px) 3rem} .top{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:18px 0;flex-wrap:wrap} .brand{display:flex;align-items:center;gap:10px;font-size:1.05rem;font-weight:800} .brand span{display:grid;place-items:center;background:#d6ed89;width:38px;height:38px;border-radius:12px} .hero{position:relative;overflow:hidden;background:#d7ede3;min-height:295px;border-radius:26px;padding:clamp(22px,6vw,52px);display:flex;align-items:center;isolation:isolate} .hero-copy{position:relative;z-index:1;max-width:510px} .tag{font-weight:800;color:#23574e;margin:0 0 10px} h1,h2,h3,p{margin-top:0} h1{font-size:clamp(2.6rem,7.3vw,5.25rem);line-height:.96;margin-bottom:18px;letter-spacing:-.07em} h2{font-size:clamp(1.45rem,4vw,2rem);line-height:1.12;margin-bottom:.6rem} h3{font-size:1.14rem;margin-bottom:.4rem} p{line-height:1.48} .hero p:last-child{margin-bottom:0;font-size:1.11rem} .landscape{width:36%;height:100%;position:absolute;right:0;bottom:0;overflow:hidden;z-index:-1;background:linear-gradient(130deg,transparent 45%,#b8e1d5)} .landscape::before{content:"";position:absolute;left:-25%;right:-25%;bottom:-28%;height:57%;background:#76ba97;border-radius:50% 46% 0 0;transform:rotate(-12deg)} .landscape::after{content:"";position:absolute;left:-28%;right:-20%;bottom:-47%;height:63%;background:#4c9d7e;border-radius:50%;transform:rotate(12deg)} .tile{position:absolute;display:grid;place-items:center;width:clamp(50px,8vw,84px);aspect-ratio:1;border:2px solid #192d30;border-radius:21%;font-size:clamp(2rem,6vw,4rem);font-weight:900;box-shadow:0 7px 0 #192d30;line-height:1} .t1{background:#ffe394;top:38%;left:5%;transform:rotate(-13deg)}.t2{background:#ffc7ba;top:23%;left:33%;transform:rotate(9deg)}.t3{background:#ddd4ff;top:47%;left:59%;transform:rotate(12deg)} .sun{position:absolute;background:#ffe6a1;width:56px;height:56px;top:10%;right:12%;border-radius:50%} .card{background:var(--paper);border:1px solid var(--rule);border-radius:23px;margin-top:18px;padding:clamp(16px,4vw,30px);box-shadow:0 4px 0 #e2e7da} .row{display:flex;align-items:center;flex-wrap:wrap;gap:10px} .between{justify-content:space-between} .muted,small{color:var(--muted)} .alias{display:flex;gap:10px;align-items:flex-end;flex-wrap:wrap} .alias label{display:grid;gap:5px;font-weight:700;flex:1;min-width:150px;max-width:330px} .alias input{min-height:48px;width:100%;background:#fff;border:1px solid #819992;border-radius:12px;padding:0 12px} #notice{margin:10px 0 0} .mapgrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:14px} .zone{text-align:left;background:var(--zone);min-height:100px;border-color:#48615870;display:grid;align-content:center;gap:3px;line-height:1.2} .zone-icon{font-size:1.56rem}.zone strong{font-size:1.03rem} .zone[aria-pressed=true]{box-shadow:inset 0 0 0 2px var(--ink);border-color:var(--ink)} #skillList{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin-top:15px} #skillList button{text-align:left}.skill-meta{display:block;font-size:.78rem;color:var(--muted);margin-top:3px} .progress{width:100%;height:12px;accent-color:var(--teal);margin-top:9px} #play{scroll-margin-top:12px} .playtop{padding-bottom:12px;border-bottom:1px solid var(--rule);margin-bottom:14px} .playtop p{margin:0;font-weight:800} #prompt{margin:14px 0 2px} #hint{min-height:1.4em;margin:0;color:var(--muted)} .stage{margin:15px 0;padding:clamp(10px,3vw,22px);background:#f0f5eb;border-radius:19px;min-height:90px;display:grid;place-items:center;gap:12px} .objects,.ords,.groups,.seq,.bundles,.unitbox{display:flex;gap:8px;flex-wrap:wrap;align-items:center;justify-content:center} .obj,.group,.ords button{min-width:47px;min-height:49px;border-radius:12px;display:grid;place-items:center;font-size:clamp(1.55rem,5.25vw,2.5rem);padding:2px;background:#fff;border:1px solid #b3c8bb} .obj.marked{background:#cce7aa;border-color:#326a3b} .obj i{font-size:.84rem;font-style:normal;line-height:1;color:#234e20;font-weight:800} .ords{width:min(100%,440px);display:grid;gap:4px}.ords button{min-width:0;min-height:46px;font-size:clamp(1.1rem,5.2vw,2.5rem)} .objects.mixed{max-width:480px;gap:11px} .mixed .obj:nth-child(3n+1){transform:translateY(4px) rotate(-6deg)} .mixed .obj:nth-child(3n+2){transform:translateY(-4px) rotate(6deg)} .seq span,.line-cell{font-size:clamp(1rem,4vw,1.5rem);font-weight:800;min-width:38px;padding:7px 4px;text-align:center} .seq span{background:#fff;border:1px solid #abbeb4;border-radius:10px} .blank{background:#ffde8b!important;color:#292121;border-radius:8px} .line{width:min(100%, 580px);display:grid;position:relative;padding-top:18px;isolation:isolate;align-items:start} .line::before{content:"";position:absolute;top:7px;left:5%;right:5%;height:3px;background:#335951;z-index:-1} .line-cell{min-width:0;position:relative} .line-cell::before{content:"";position:absolute;top:-14px;left:calc(50% - 4px);width:8px;height:8px;border-radius:50%;background:#335951} .line-cell.current{background:#c6e9d8;border-radius:8px} .line-cell.current::before,.line-cell.blank::before{background:#865516;box-shadow:0 0 0 3px #ffe299} .grid100{display:grid;grid-template-columns:repeat(10,minmax(0,1fr));gap:2px;width:min(100%,430px)} .grid100 span{background:#fff;text-align:center;padding:4px 0;font-size:clamp(.72rem,2.7vw,1rem);font-variant-numeric:tabular-nums;border-radius:4px} .frame{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:5px;width:min(100%,325px);padding:5px;background:#a7c4b4;border-radius:10px} .frame button{display:grid;place-items:center;min-width:0;min-height:38px;padding:0;border-radius:6px;border:1px solid #749789;background:#fff;aspect-ratio:1.35} .frame .filled::before{content:"";width:64%;max-width:28px;aspect-ratio:1;border-radius:50%;background:#00786c} .rod{height:65px;display:grid;grid-template-rows:repeat(10,1fr);gap:1px;width:14px;border:1px solid #1e5c76;background:#e5f4f4} .rod i{background:#508fac}.cube{width:15px;aspect-ratio:1;background:#ef994f;border:1px solid #994f13;border-radius:3px} .group{padding:4px 8px;min-width:52px}.group b{font-size:.85rem;color:#315d54} .options{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin:14px 0} .options button{font-size:1.35rem;min-width:58px;min-height:53px} #feedback{border-radius:15px;padding:13px 15px;background:#fff0cd;border:1px solid #c98b32;margin:13px 0} #feedback.good{background:#e3f3d5;border-color:#5e8552} #feedback p{margin:4px 0 0} #next{width:100%} details summary{cursor:pointer;font-weight:800} details p{margin:10px 0} .tablewrap{overflow:auto} table{width:100%;border-collapse:collapse;font-size:.88rem;margin:10px 0} td,th{text-align:left;padding:7px;border-bottom:1px solid var(--rule);white-space:nowrap} @media(max-width:620px){.mapgrid{grid-template-columns:repeat(2,minmax(0,1fr))}.hero{min-height:230px}.hero-copy{max-width:70%}.hero-copy p{font-size:.93rem!important}.landscape{width:39%}.t1{left:0;top:35%}.t2{left:39%;top:24%}.t3{left:24%;top:62%}.sun{width:38px;height:38px}#skillList{grid-template-columns:1fr}} </style> </head> <body> <main> <header class="top"><div class="brand"><span aria-hidden="true">✦</span> Matemáticas · Infantil</div><button id="headerMap" hidden>🗺 Mapa</button></header> <section class="hero" id="hero"> <div class="hero-copy"><p class="tag">Toca, cuenta y salta</p><h1>La isla de<br>los números</h1><p>Explora seis zonas. Empieza con el 1, el 2 y el 3 y aprende a contar hasta el 100.</p></div> <div class="landscape" aria-hidden="true"><i class="sun"></i><span class="tile t1">1</span><span class="tile t2">2</span><span class="tile t3">3</span></div> </section> <section class="card" id="welcome"> <h2>¿Quién va a jugar?</h2> <form class="alias" id="startForm"><label for="alias">Apodo o código de clase<input id="alias" required maxlength="24" placeholder="Ej. Luna o INF-07" autocomplete="off"></label><button class="primary" type="submit" id="start">Empezar</button><button type="button" id="resume" hidden>Continuar</button></form> <p class="muted" id="notice">Usa un apodo sin apellidos. Cada acierto a la primera suma un punto.</p> </section> <section class="card" id="map" hidden> <div class="row between"><h2>Elige una zona</h2><strong id="score"></strong></div> <progress class="progress" id="progress" aria-label="Ejercicios respondidos"></progress> <p class="muted" id="mapStatus"></p> <div class="mapgrid" id="zones"></div> <div id="skillList"></div> <div class="row" style="margin-top:16px"><button class="primary" id="recommended">Seguir el recorrido</button><button id="switchPlayer">Cambiar de jugador</button></div> </section> <section class="card" id="play" hidden> <div class="playtop row between"><p id="breadcrumb"></p><button id="listen" type="button">🔊 Escuchar</button></div> <div class="row between"><small id="level"></small><small id="playScore"></small></div> <h2 tabindex="-1" id="prompt"></h2><p id="hint"></p> <div id="stage" class="stage"></div> <div id="options" class="options"></div> <div id="feedback" role="status" aria-live="polite" hidden></div> <button class="primary" id="next" hidden></button> </section> <details class="card" id="historyPanel"> <summary>Registro de sesiones</summary> <p class="muted" id="tracking"></p> <div class="tablewrap" id="history"></div> <div class="row"><button id="export">Descargar CSV de este navegador</button></div> </details> <p class="muted" id="syncStatus" aria-live="polite"></p> <button id="remoteRetry" hidden>Reintentar envío</button> </main> <script> const groups = [ ['A','Hasta el 3','🐣','#fff0b2'], ['B','Hasta el 5','🐸','#d8f3c0'], ['C','Hasta el 10','🐙','#dfe4ff'], ['D','Hasta el 20','🦊','#ffddc7'], ['E','Del 20 al 100','🐢','#c4edeb'], ['F','De tanto en tanto','🚂','#f8ddf1'] ]; const skills = []; const add = (id, title, ...questions) => skills.push({id,title,questions}); const range = (n,start=0,step=1) => Array.from({length:n},(_,i)=>start+i*step); const series = (a, sep=', ') => a.join(sep); const countText = (n) => series(range(n,1)); const question = (type, prompt, answer, explanation, details={}) => ({type,prompt,answer,explanation,...details}); const touch = (n, icon, mixed=false) => question('touch','Toca cada dibujo una sola vez. ¿Cuántos hay?',n, `Cuenta un dibujo cada vez: ${countText(n)}. El último número es el total: ${n}.`,{n,icon,mixed}); const count = (n, icon, mixed=false) => question('count','¿Cuántos dibujos ves?',n, `Señala los dibujos mientras cuentas: ${countText(n)}. Hay ${n} en total.`,{n,icon,mixed}); const frame = (n,limit) => { const tens = Math.floor(n/10); const units = n%10; const explanation = !tens ? `Pon una ficha en cada casilla hasta contar ${n}. Quedan ${10-n} casillas vacías en el marco.` : units ? `Llena un marco con 10 fichas y coloca ${units} en el siguiente. 10 más ${units} son ${n}.` : `Cada marco lleno tiene 10 fichas. ${tens===2?'10 y 10 son 20.':'Un marco lleno muestra 10.'}`; return question('frame',`Coloca ${n} ${n===1?'ficha':'fichas'}.`,n,explanation,{frames:limit>10?2:1}); }; const animalNames = {'🐱':'gato','🐶':'perro','🐭':'ratón','🐸':'rana','🐙':'pulpo','🐢':'tortuga','🐰':'conejo','🦊':'zorro','🐼':'panda'}; const ordinal = (index, icons) => { const names = ['primer','segundo','tercer','cuarto','quinto','sexto','séptimo','octavo','noveno','décimo']; return question('ordinal',`Toca el ${names[index-1]} animal desde la izquierda.`,index, `Empieza en la flecha. Cuenta ${countText(index)}. El ${names[index-1]} animal es ${animalNames[icons[index-1]]} ${icons[index-1]}.`,{icons}); }; const sequence = (values, blank, type='sequence', prompt='¿Qué número falta?') => { const step = values[1]-values[0]; const direction = step<0?'hacia atrás':'hacia delante'; const stepText = Math.abs(step)===1?`de uno en uno ${direction}`:`de ${Math.abs(step)} en ${Math.abs(step)} ${direction}`; return question(type,prompt,values[blank],`Cuenta ${stepText}: ${series(values)}. En el hueco va el ${values[blank]}.`, {values,blank,step:Math.abs(step)}); }; const tens = (bundles, units) => question('tens','¿Cuántos cubitos hay en total?',10*bundles+units, `Cada barra tiene 10 cubitos. ${bundles} ${bundles===1?'decena vale':'decenas valen'} ${10*bundles}. Añade ${units} ${units===1?'unidad':'unidades'} y tendrás ${10*bundles+units}.`,{bundles,units}); const table = (n) => question('table','¿Qué número falta en la casilla marcada?',n, n%10===1?`En la tabla, al bajar una fila sumas 10. Debajo del ${n-10} va el ${n}.` :`En cada fila cuenta de uno en uno. Después del ${n-1} va el ${n}.`); const grouped = (step,n) => { const icons={2:'🧦',5:'🖐️',10:'▦'}; return question('grouped',`Cada grupo vale ${step}. ¿Cuántos hay en total?`,step*n, `Cuenta un grupo cada vez y suma ${step} en cada salto: ${series(range(n,step,step))}. El total es ${step*n}.`, {step,n,icon:icons[step]}); }; const line = (start,n,blank,step=1) => sequence(range(n,start,step),blank,'line','¿Qué número va en el punto marcado?'); const move = (start,steps,dir,step=1) => { const values=range(steps+1,start,dir*step); const verb=dir>0?'Avanza':'Retrocede'; return question('move',`Desde el ${start}, ${verb.toLowerCase()} ${steps} ${steps===1?'salto':'saltos'}${step===1?'':` de ${step}`}. ¿Adónde llegas?`, values.at(-1),`Empieza en ${start}. ${verb} ${steps} ${steps===1?'salto':'saltos'} ${dir>0?'hacia la derecha':'hacia la izquierda'}: ${series(values,' → ')}. Llegas al ${values.at(-1)}.`, {start,steps,dir,step}); }; const next = (n,step) => sequence(range(4,n,step),3,'sequence',step>0?'Sigue contando hacia delante.':'Sigue contando hacia atrás.'); add('A.1','Aprender a contar hasta 3',touch(1,'🐣'),touch(2,'🍎'),touch(3,'🐝',true)); add('A.2','Contar hasta 3',count(1,'🐞'),count(2,'🍓'),count(3,'⭐',true)); add('A.3','Marco de diez hasta 3',frame(1,3),frame(2,3),frame(3,3)); add('B.1','Aprender a contar hasta 5',touch(3,'🐸'),touch(4,'🐚'),touch(5,'🐠',true)); add('B.2','Contar hasta 5',count(3,'🌻'),count(5,'🍊'),count(4,'🐢',true)); add('B.3','Marco de diez hasta 5',frame(3,5),frame(4,5),frame(5,5)); add('C.1','Aprender a contar hasta 10',touch(6,'🐙'),touch(8,'🐬'),touch(10,'🌸',true)); add('C.2','Contar hasta 10',count(6,'🍉'),count(8,'🦀',true),count(9,'🐟',true)); add('C.3','Marco de diez hasta 10',frame(6,10),frame(8,10),frame(10,10)); add('C.4','Recta numérica hasta 10',line(1,5,1),line(4,6,3),line(5,6,5)); add('C.5','Números ordinales',ordinal(1,['🐱','🐶','🐭']), ordinal(3,['🐸','🐙','🐱','🐢']),ordinal(5,['🐭','🐸','🐶','🐰','🦊','🐼'])); add('D.1','Marcos de diez hasta 20',frame(11,20),frame(16,20),frame(20,20)); add('D.2','Recta numérica hasta 20',line(8,5,2),line(13,6,4),line(15,6,5)); add('D.3','Completar secuencias hasta 20',sequence([8,9,10,11,12],2),sequence([12,13,14,15,16],1),sequence([18,19,20],0)); add('D.4','Contar hacia delante hasta 20',next(6,1),next(9,1),next(17,1)); add('D.5','Contar hacia atrás desde 20',next(8,-1),next(12,-1),next(20,-1)); add('D.6','Decenas y unidades hasta 20',tens(1,2),tens(1,8),tens(2,0)); add('E.1','Tabla de centenas',table(25),table(61),table(100)); add('E.2','Contar con rectas numéricas',move(23,1,1),move(38,2,1),move(62,3,-1)); add('E.3','Completar la recta numérica',line(27,6,3),line(40,5,2,2),line(60,5,2,10)); add('E.4','Contar hacia delante y hacia atrás',next(27,1),next(51,-1), question('move','Desde el 69, avanza 2 y retrocede 3. ¿Adónde llegas?',68, 'Avanza: 69 → 70 → 71. Después retrocede: 71 → 70 → 69 → 68. Llegas al 68.',{start:69,steps:2,dir:1,step:1,back:3})); add('E.5','Completar secuencias',sequence([37,38,39,40,41],3),sequence([64,63,62,61,60],2),sequence([94,95,96,97,98],0)); add('E.6','Contar decenas y unidades',tens(2,3),tens(4,0),tens(7,6)); add('F.1','Aprender a contar de dos en dos',grouped(2,2),grouped(2,3),grouped(2,5)); add('F.2','Contar de dos en dos',next(2,2),sequence([10,12,14,16,18],2),line(18,5,3,2)); add('F.3','Aprender a contar de cinco en cinco',grouped(5,2),grouped(5,3),grouped(5,5)); add('F.4','Contar de cinco en cinco',next(5,5),sequence([15,20,25,30,35],2),line(35,5,3,5)); add('F.5','Aprender a contar de diez en diez',grouped(10,2),grouped(10,4),grouped(10,6)); add('F.6','Contar de diez en diez',next(10,10),sequence([30,40,50,60,70],2),line(60,5,3,10)); add('F.7','Mezclar saltos de 2, 5 y 10', sequence([4,6,8,10,12],3,'sequence','Da saltos de 2. ¿Qué número falta?'), sequence([35,40,45,50,55],2,'sequence','Da saltos de 5. ¿Qué número falta?'), sequence([60,70,80,90,100],4,'sequence','Da saltos de 10. ¿Qué número falta?')); const $ = (id) => document.getElementById(id); const total = skills.reduce((sum, skill) => sum + skill.questions.length, 0); const storageKey = 'isla-de-los-numeros-v1'; const aliasPattern = /^[A-Za-zÀ-ÿ0-9][A-Za-zÀ-ÿ0-9 ._-]{0,23}$/; const remote = Boolean(window.google?.script?.run); const levels = ['Para empezar', 'Un paso más', 'Reto']; const skillById = Object.fromEntries(skills.map(skill => [skill.id, skill])); let archive = readArchive(); let active = null; let zone = 'A'; let current = null; let inFlight = false; let storageFailed = false; let feedbackText = ''; function readArchive() { try { return JSON.parse(localStorage.getItem(storageKey)) || {sessions:[], last:null}; } catch { return {sessions:[], last:null}; } } function persist() { try { localStorage.setItem(storageKey, JSON.stringify(archive)); storageFailed = false; } catch { storageFailed = true; } renderHistory(); } function stats(record) { const answers = Object.values(record.answers); return {score:answers.filter(Boolean).length, attempted:answers.length}; } function snapshot(record) { const blocks = groups.map(([key]) => { const answers = Object.entries(record.answers).filter(([id]) => id.startsWith(key)).map(([,v])=>v); return `${answers.filter(Boolean).length}/${answers.length}`; }); return {id:record.id, alias:record.alias, started:record.started, updated:record.updated, ...stats(record), blocks}; } function saveProgress() { active.updated = Date.now(); active.needsSync = remote; persist(); if (remote) flush(); } function flush() { if (inFlight) return; const record = archive.sessions.find(entry => entry.needsSync); if (!record) return; const data = snapshot(record); const fail = () => { inFlight = false; $('syncStatus').textContent = 'Envío pendiente. Vuelve a intentarlo.'; $('remoteRetry').hidden = false; }; inFlight = true; $('remoteRetry').hidden = true; $('syncStatus').textContent = 'Guardando en el registro de clase…'; window.google.script.run.withSuccessHandler(() => { inFlight = false; if (record.updated === data.updated && stats(record).attempted === data.attempted) { record.needsSync = false; persist(); } $('syncStatus').textContent = 'Registro de clase actualizado.'; flush(); }).withFailureHandler(fail).guardarSesion(data); } function renderHistory() { if (remote) { $('historyPanel').hidden = true; return; } $('tracking').textContent = storageFailed ? 'Este navegador ha bloqueado el guardado. Descarga el CSV antes de cerrar.' : 'Los resultados de esta copia se guardan en este navegador. Para reunir los de toda la clase, conecta la ficha a una hoja de cálculo.'; const host = $('history'); host.replaceChildren(); if (!archive.sessions.length) { host.append(node('p','muted','Aún no hay sesiones.')); return; } const table = node('table'); const head = table.createTHead().insertRow(); ['Apodo','Inicio','Puntos','Respondidos','Estado'].forEach(label => head.append(node('th','',label))); const body = table.createTBody(); [...archive.sessions].reverse().forEach(record => { const {score,attempted} = stats(record); const row = body.insertRow(); [record.alias,new Date(record.started).toLocaleString('es-ES'),`${score}/${total}`, `${attempted}/${total}`,attempted===total?'Ficha respondida':'En curso'].forEach(s=>row.append(node('td','',s))); }); host.append(table); } function exportHistory() { const rows = [['Apodo','Inicio','Última actividad','Aciertos a la primera','Respondidos','Total', ...groups.map(([key])=>`Bloque ${key} aciertos/respondidos`)]]; archive.sessions.forEach(record => { const data=snapshot(record); rows.push([data.alias,new Date(data.started).toLocaleString('es-ES'),new Date(data.updated).toLocaleString('es-ES'), data.score,data.attempted,total,...data.blocks]); }); const csv = rows.map(row => row.map(value => `"${String(value).replaceAll('"','""')}"`).join(';')).join('\r\n'); const url = URL.createObjectURL(new Blob(['\ufeff',csv],{type:'text/csv;charset=utf-8'})); const link = document.createElement('a'); link.href=url; link.download='Resultados_isla_de_los_numeros.csv'; link.click(); setTimeout(()=>URL.revokeObjectURL(url),1000); } function node(tag, className='', value='') { const el=document.createElement(tag); el.className=className; el.textContent=value; return el; } function btn(label, onClick, className='') { const el=node('button',className,label); el.type='button'; el.addEventListener('click',onClick); return el; } function stopVoice() { if ('speechSynthesis' in window) window.speechSynthesis.cancel(); } function show(view) { stopVoice(); for (const id of ['welcome','map','play']) $(id).hidden=id!==view; $('hero').hidden=view==='play'; $('headerMap').hidden=view!=='play'; if (view==='play') { $('play').scrollIntoView({block:'start'}); $('prompt').focus({preventScroll:true}); } else if (view==='map') { const heading=$('map').querySelector('h2'); heading.tabIndex=-1; heading.focus({preventScroll:true}); $('map').scrollIntoView({block:'start'}); } } const keyFor = (skill,index) => `${skill.id}:${index}`; const answered = (skill,index) => Object.hasOwn(active.answers,keyFor(skill,index)); const findUnanswered = skill => skill.questions.findIndex((_,i)=>!answered(skill,i)); function renderMap() { const {score,attempted}=stats(active); $('score').textContent=`★ ${score} / ${total} puntos`; $('progress').max=total; $('progress').value=attempted; $('mapStatus').textContent=`${active.alias} · ${attempted} de ${total} respondidos${attempted===total?' · ¡Recorrido completo!':''}`; $('recommended').hidden=attempted===total; const zones=$('zones'); zones.replaceChildren(); groups.forEach(([letter,title,icon,color]) => { const list=skills.filter(skill=>skill.id.startsWith(letter)); const done=list.filter(skill=>findUnanswered(skill)===-1).length; const zoneButton=btn('',()=>{ zone=letter; renderMap(); $('zones').querySelector('[aria-pressed="true"]').focus(); },'zone'); zoneButton.style.setProperty('--zone',color); zoneButton.setAttribute('aria-pressed',String(zone===letter)); const symbol=node('span','zone-icon',icon); symbol.setAttribute('aria-hidden','true'); zoneButton.append(symbol,node('strong','',title),node('small','',`${done}/${list.length} actividades`)); zones.append(zoneButton); }); const list=$('skillList'); list.replaceChildren(); skills.filter(skill=>skill.id.startsWith(zone)).forEach(skill => { const count=skill.questions.filter((_,index)=>answered(skill,index)).length; const button=btn(`${skill.id} · ${skill.title}`,()=>{ const next=findUnanswered(skill); openQuestion(skill,next===-1?0:next); }); button.append(node('span','skill-meta',count===3?'✓ 3/3 · Repasar':`${count}/3 respondidos`)); list.append(button); }); } function openQuestion(skill,index) { zone=skill.id[0]; current={skill,index,q:skill.questions[index],marks:new Set(),locked:false}; feedbackText=''; $('feedback').hidden=true; $('next').hidden=true; $('breadcrumb').textContent=`${skill.id} · ${skill.title}`; $('level').textContent=`${index+1}/${skill.questions.length} · ${levels[index]}`; $('prompt').textContent=current.q.prompt; $('listen').hidden=!('speechSynthesis' in window); updatePlayScore(); drawQuestion(); show('play'); } function updatePlayScore() { $('playScore').textContent=`★ ${stats(active).score} / ${total}`; } function choices(q, index) { const minimum=q.type==='frame'?0:1; const step=q.step || 1; const maximum=current.skill.id[0]==='A'?3:current.skill.id[0]==='B'?5:current.skill.id[0]==='C'?10: current.skill.id[0]==='D'?20:100; const values=[q.answer]; const offsets=[-step,step,-1,1,-2,2,-step*2,step*2]; for (const offset of offsets) { if (values.length===3) break; const v=q.answer+offset; if (v>=minimum && v<=maximum && !values.includes(v)) values.push(v); } for (let i=0;i<((index+q.answer+current.skill.id.charCodeAt(0))%3);i++) values.push(values.shift()); return values; } function drawLine(values,blank=-1,start=-1) { const line=node('div','line'); line.style.gridTemplateColumns=`repeat(${values.length},minmax(0,1fr))`; line.setAttribute('aria-label','Recta numérica'); values.forEach((v,i)=>line.append(node('span',`line-cell${i===blank?' blank':''}${i===start?' current':''}`,i===blank?'?':v))); return line; } function drawQuestion() { const {q,index,marks}=current; const stage=$('stage'); const opts=$('options'); stage.replaceChildren(); opts.replaceChildren(); $('hint').textContent=''; if (q.type==='touch' || q.type==='count') { const objectBox=node('div',`objects${q.mixed?' mixed':''}`); if (q.type==='touch') $('hint').textContent='Toca los dibujos y luego elige el número.'; range(q.n).forEach(i=>{ if (q.type==='count') { objectBox.append(node('span','obj',q.icon)); return; } const object=btn(q.icon,()=>{ if (marks.has(i)) return; marks.add(i); object.classList.add('marked'); object.setAttribute('aria-label',`Dibujo contado: ${marks.size}`); object.setAttribute('aria-pressed','true'); object.append(node('i','',marks.size)); },'obj'); object.setAttribute('aria-label',`Dibujo ${i+1} sin contar`); object.setAttribute('aria-pressed','false'); objectBox.append(object); }); stage.append(objectBox); } else if (q.type==='frame') { $('hint').textContent='Toca una casilla para poner o quitar una ficha.'; for (const f of range(q.frames)) { const board=node('div','frame'); board.setAttribute('role','group'); board.setAttribute('aria-label',`Marco ${f+1}`); for (const i of range(10)) { const cell=btn('',()=>{ const id=f*10+i; if (marks.has(id)) marks.delete(id); else marks.add(id); cell.classList.toggle('filled',marks.has(id)); cell.setAttribute('aria-pressed',String(marks.has(id))); }); cell.setAttribute('aria-label',`Marco ${f+1}, casilla ${i+1}`); cell.setAttribute('aria-pressed','false'); board.append(cell); } stage.append(board); } opts.append(btn('Comprobar',()=>check(marks.size),'primary')); } else if (q.type==='ordinal') { $('hint').textContent='La flecha marca por dónde empezar.'; const line=node('div','ords'); line.style.gridTemplateColumns = `auto repeat(${q.icons.length},minmax(0,1fr))`; line.append(node('b','','→')); q.icons.forEach((icon,i)=>{ const animal=btn(icon,()=>check(i+1)); animal.setAttribute('aria-label',animalNames[icon]); line.append(animal); }); stage.append(line); } else if (q.type==='sequence') { const sequence=node('div','seq'); q.values.forEach((v,i)=>sequence.append(node('span',i===q.blank?'blank':'',i===q.blank?'?':v))); stage.append(sequence); } else if (q.type==='line') { if (q.step>1) $('hint').textContent=`Cada salto suma ${q.step}.`; stage.append(drawLine(q.values,q.blank)); } else if (q.type==='move') { const width=q.back?5:Math.max(4,q.steps); $('hint').textContent='La casilla verde marca la salida.'; stage.append(drawLine(range(width*2+1,q.start-width*q.step,q.step),-1,width)); } else if (q.type==='table') { $('hint').textContent='Cada fila tiene diez casillas.'; const grid=node('div','grid100'); range(100,1).forEach(v=>grid.append(node('span',v===q.answer?'blank':'',v===q.answer?'?':v))); stage.append(grid); } else if (q.type==='tens') { $('hint').textContent='Cada barra vale 10. Cada cubito suelto vale 1.'; const bundles=node('div','bundles'); for (const b of range(q.bundles)) { const rod=node('span','rod'); rod.setAttribute('role','img'); rod.setAttribute('aria-label',`Barra ${b+1} de diez cubitos`); for (const ignored of range(10)) rod.append(node('i')); bundles.append(rod); } const unitbox=node('div','unitbox'); for (const u of range(q.units)) { const cube=node('i','cube'); cube.setAttribute('role','img'); cube.setAttribute('aria-label',`Cubito suelto ${u+1}`); unitbox.append(cube); } stage.append(bundles,unitbox); } else if (q.type==='grouped') { const groupLine=node('div','groups'); range(q.n).forEach(i=>{ const group=node('span','group',q.step===2?q.icon+q.icon:q.icon); group.setAttribute('aria-label',`Grupo ${i+1} de ${q.step}`); group.append(node('b','',q.step)); groupLine.append(group); }); stage.append(groupLine); } if (q.type!=='frame' && q.type!=='ordinal') choices(q,index).forEach(v=>opts.append(btn(v,()=>check(v)))); } function check(value) { if (current.locked) return; const {skill,index,q} = current; const correct = q.answer===value; if (!answered(skill,index)) { active.answers[keyFor(skill,index)]=correct; saveProgress(); updatePlayScore(); } $('feedback').hidden=false; $('feedback').classList.toggle('good',correct); const heading=correct?'⭐ ¡Muy bien!':'💡 Vamos a verlo'; feedbackText=q.explanation; $('feedback').replaceChildren(node('strong','',heading),node('p','',feedbackText)); $('next').hidden=false; current.locked=correct; if (correct) { $('stage').querySelectorAll('button').forEach(button=>button.disabled=true); $('options').querySelectorAll('button').forEach(button=>button.disabled=true); } $('next').textContent=index===skill.questions.length-1?'Volver al mapa':correct?'Siguiente ejercicio':'Siguiente ejercicio ↗'; } $('listen').addEventListener('click',()=>{ stopVoice(); const utterance=new SpeechSynthesisUtterance(feedbackText || `${current.q.prompt} ${$('hint').textContent}`); utterance.lang='es-ES'; utterance.rate=.85; window.speechSynthesis.speak(utterance); }); $('startForm').addEventListener('submit',event=>{ event.preventDefault(); const alias=$('alias').value.trim(); if (!aliasPattern.test(alias)) { $('alias').setCustomValidity('Escribe un apodo corto, como Luna o INF-07.'); $('alias').reportValidity(); return; } const now=Date.now(); active={id:`${now}-${Array.from(crypto.getRandomValues(new Uint8Array(12)),v=>v.toString(16).padStart(2,'0')).join('')}`, alias,started:now,updated:now,answers:{},needsSync:false}; archive.sessions.push(active); archive.last=active.id; zone='A'; saveProgress(); renderMap(); show('map'); }); $('alias').addEventListener('input',()=> $('alias').setCustomValidity('')); function setResume() { const prior=archive.sessions.find(entry=>entry.id===archive.last); $('resume').hidden=!prior; if (prior) $('resume').textContent=`Continuar como ${prior.alias}`; } $('resume').addEventListener('click',()=>{ active=archive.sessions.find(entry=>entry.id===archive.last); zone=skills.find(skill=>findUnanswered(skill)!==-1)?.id[0] || 'A'; renderMap(); show('map'); }); $('switchPlayer').addEventListener('click',()=>{ active=null; $('alias').value=''; setResume(); show('welcome'); $('alias').focus(); }); $('headerMap').addEventListener('click',()=>{ renderMap(); show('map'); }); $('next').addEventListener('click',()=>{ const {skill,index}=current; if (index+1<skill.questions.length) openQuestion(skill,index+1); else { renderMap(); show('map'); } }); $('recommended').addEventListener('click',()=>{ const skill=skills.find(item=>findUnanswered(item)!==-1); if (skill) openQuestion(skill,findUnanswered(skill)); }); $('export').addEventListener('click',exportHistory); $('remoteRetry').addEventListener('click',flush); window.addEventListener('online',()=>{if(remote)flush()}); if (remote) { $('notice').textContent='Usa un apodo sin apellidos. Al empezar, tu apodo y tu progreso se guardan en el registro de clase.'; flush(); } setResume(); renderHistory(); </script> </body> </html> Comentarios
Comentarios
Publicar un comentario