Trò chơi ghép hình – Toán 4
by MagicBunny92391 lines19.9 KB
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Trò chơi ghép hình – Toán 4 | CLB Học Toán cùng Jenny</title>
<style>
:root{--ink:#1f2937;--muted:#6b7280;--bg:#f6f7fb;--card:#fff;--accent:#2563eb;--ok:#16a34a;--gold:#f59e0b}
*{box-sizing:border-box}
body{margin:0;font-family:"Segoe UI",Roboto,Arial,sans-serif;background:var(--bg);color:var(--ink)}
.wrap{max-width:980px;margin:0 auto;padding:12px}
header{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
h1{font-size:1.25rem;margin:0}
.brand{font-size:.85rem;color:var(--muted)}
.stars{font-size:1.7rem;letter-spacing:2px;line-height:1}
.star{color:#d1d5db;transition:transform .3s}.star.on{color:var(--gold);transform:scale(1.15)}
.tabs{display:flex;gap:8px;margin:10px 0;flex-wrap:wrap}
.tab{flex:1;min-width:140px;border:2px solid #d1d5db;background:var(--card);border-radius:12px;padding:6px 8px;cursor:pointer;display:flex;align-items:center;gap:8px;font:inherit;text-align:left;color:var(--ink)}
.tab.active{border-color:var(--accent);box-shadow:0 0 0 3px #dbeafe}
.tab.done{border-color:var(--ok)}
.tab svg{flex:none}
.tab b{display:block}
.tab small{color:var(--muted)}
.card{background:var(--card);border-radius:14px;padding:10px;box-shadow:0 1px 3px rgba(0,0,0,.08)}
.info{display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:6px;margin-bottom:6px}
.task{font-weight:700}
.tries{font-weight:600}
.tries span{display:inline-block;min-width:2.2ch;text-align:center;background:#eef2ff;color:var(--accent);border-radius:8px;padding:0 6px}
.tries.low span{background:#fee2e2;color:#b91c1c}
svg#board{width:100%;height:auto;touch-action:none;user-select:none;-webkit-user-select:none;background:#fff;border-radius:10px;border:1px solid #e5e7eb;display:block}
.controls{display:flex;gap:6px;flex-wrap:wrap;margin-top:8px}
button.btn{font:inherit;border:none;border-radius:10px;padding:9px 12px;cursor:pointer;background:#e5e7eb;color:var(--ink);font-weight:600}
button.btn.primary{background:var(--accent);color:#fff}
button.btn:disabled{opacity:.45;cursor:default}
.msg{margin-top:8px;padding:8px 10px;border-radius:10px;background:#f3f4f6;min-height:2.4em}
.msg.ok{background:#dcfce7;color:#14532d}.msg.bad{background:#fee2e2;color:#7f1d1d}.msg.info{background:#e0f2fe;color:#0c4a6e}
.shelf{display:flex;gap:10px;flex-wrap:wrap;min-height:90px;align-items:center}
.shelf .empty{color:var(--muted);font-size:.9rem}
.shelf .item{border:1px solid #bbf7d0;border-radius:10px;padding:4px 6px;text-align:center;font-size:.8rem;background:#f0fdf4}
.help{font-size:.9rem;color:#374151;margin:0;padding-left:18px}
.help li{margin:2px 0}
h2{font-size:1rem;margin:12px 0 6px}
.piece{cursor:grab}
.piece.sel polygon.body{stroke:#111827;stroke-width:3.5}
</style>
</head>
<body>
<div class="wrap">
<header>
<div>
<h1>🧩 Trò chơi ghép hình – Toán 4</h1>
<div class="brand">CLB Học Toán cùng Jenny · Ghép 4 tam giác vuông thành hình vuông, hình bình hành, hình thoi</div>
</div>
<div class="stars" id="stars" aria-label="Số sao"></div>
</header>
<div class="tabs" id="tabs"></div>
<div class="card">
<div class="info">
<div class="task" id="taskTitle"></div>
<div class="tries" id="triesBox">Còn <span id="tries">10</span> lượt thử</div>
</div>
<svg id="board" aria-label="Bảng ghép hình"></svg>
<div class="controls">
<button class="btn" id="btnCCW" title="Phím E">↺ Xoay trái</button>
<button class="btn" id="btnCW" title="Phím R">↻ Xoay phải</button>
<button class="btn" id="btnFlip" title="Phím F">⇋ Lật</button>
<button class="btn primary" id="btnCheck">✔ Kiểm tra</button>
<button class="btn" id="btnReset">⟲ Làm lại</button>
</div>
<div class="msg info" id="msg">Chạm vào một miếng để chọn, kéo thả để di chuyển. Miếng ghép tự hút vào chỗ gần nhất trên lưới.</div>
</div>
<h2>🏆 Sản phẩm đã ghép được</h2>
<div class="card shelf" id="shelf"><span class="empty">Chưa có sản phẩm nào. Hãy ghép hình đầu tiên nhé!</span></div>
<h2>📘 Cách chơi</h2>
<div class="card">
<ul class="help">
<li>Mỗi miếng là một tam giác vuông: <b>nét đậm</b> là cạnh góc vuông dài, <b>nét đứt</b> là cạnh góc vuông ngắn.</li>
<li>Dùng cả 4 miếng để ghép thành hình của nhiệm vụ A, B hoặc C. Có nhiều cách ghép đúng, cách nào đúng cũng được tính.</li>
<li>Đặt miếng gần đúng chỗ là được: miếng sẽ tự hút vào vị trí trên lưới. Ghép đúng thì trò chơi tự nhận kết quả.</li>
<li>Bấm <b>Kiểm tra</b> sẽ mất 1 lượt nếu chưa đúng. Mỗi hình có 10 lượt. Hết lượt, trò chơi sẽ hiện đáp án.</li>
<li>Có thể chuyển sang hình khác bất cứ lúc nào. Khi quay lại hình chưa xong, em làm lại từ đầu và có lại 10 lượt.</li>
</ul>
</div>
</div>
<script>
//CORE-START
const U=44, COLS=14, ROWS=9, TRAY_Y=6, MAX_TRIES=10;
// Tam giác vuông: đỉnh góc vuông, đầu cạnh dài (2), đầu cạnh ngắn (1)
const BASE=[[0,0],[-2,0],[0,-1]];
const TASKS=[
{key:'A',name:'hình vuông',title:'Hình vuông',type:'square',
sol:[[[0,0],[2,0],[0,1]],[[2,1],[0,1],[2,0]],[[0,1],[2,1],[0,2]],[[2,2],[0,2],[2,1]]]},
{key:'B',name:'hình bình hành',title:'Hình bình hành',type:'para',
sol:[[[1,2],[0,2],[1,0]],[[1,0],[2,0],[1,2]],[[2,2],[1,2],[2,0]],[[2,0],[3,0],[2,2]]]},
{key:'C',name:'hình thoi',title:'Hình thoi',type:'rhombus',
sol:[[[2,1],[0,1],[2,0]],[[2,1],[4,1],[2,0]],[[2,1],[0,1],[2,2]],[[2,1],[4,1],[2,2]]]}
];
function orient(pt,r,f){let [x,y]=pt; if(f) x=-x; for(let i=0;i<r;i++){[x,y]=[-y,x];} return [x+0,y+0];}
function verts(p){return BASE.map(b=>{const [x,y]=orient(b,p.r,p.f);return [p.x+x,p.y+y];});}
function centroid(v){return [(v[0][0]+v[1][0]+v[2][0])/3,(v[0][1]+v[1][1]+v[2][1])/3];}
function cross(o,a,b){return (a[0]-o[0])*(b[1]-o[1])-(a[1]-o[1])*(b[0]-o[0]);}
function hull(pts){
const P=[...new Map(pts.map(p=>[p.join(','),p])).values()].sort((a,b)=>a[0]-b[0]||a[1]-b[1]);
if(P.length<3) return P;
const lo=[],up=[];
for(const p of P){while(lo.length>=2&&cross(lo[lo.length-2],lo[lo.length-1],p)<=0)lo.pop();lo.push(p);}
for(const p of P.slice().reverse()){while(up.length>=2&&cross(up[up.length-2],up[up.length-1],p)<=0)up.pop();up.push(p);}
return lo.slice(0,-1).concat(up.slice(0,-1));
}
function area2(poly){let s=0;for(let i=0;i<poly.length;i++){const a=poly[i],b=poly[(i+1)%poly.length];s+=a[0]*b[1]-b[0]*a[1];}return Math.abs(s);}
function inTri(p,t){const d1=cross(t[0],t[1],p),d2=cross(t[1],t[2],p),d3=cross(t[2],t[0],p);return (d1>0&&d2>0&&d3>0)||(d1<0&&d2<0&&d3<0);}
function classify(H){
const n=H.length;
if(n===3) return 'tri';
if(n!==4) return 'poly'+n;
const v=[0,1,2,3].map(i=>[H[(i+1)%4][0]-H[i][0],H[(i+1)%4][1]-H[i][1]]);
const par=(a,b)=>a[0]*b[1]-a[1]*b[0]===0;
const isPara=v[0][0]+v[2][0]===0&&v[0][1]+v[2][1]===0&&v[1][0]+v[3][0]===0&&v[1][1]+v[3][1]===0;
const right=v[0][0]*v[1][0]+v[0][1]*v[1][1]===0;
const eq=v[0][0]**2+v[0][1]**2===v[1][0]**2+v[1][1]**2;
if(isPara&&right&&eq) return 'square';
if(isPara&&right) return 'rect';
if(isPara&&eq) return 'rhombus';
if(isPara) return 'para';
if(par(v[0],v[2])||par(v[1],v[3])) return 'trap';
return 'quad';
}
// Kiểm tra: không chồng lấn + bao lồi có diện tích đúng bằng tổng 4 miếng => 4 miếng ghép khít thành 1 hình lồi
function analyze(pieces){
const tris=pieces.map(verts), all=tris.flat();
const xs=all.map(p=>p[0]), ys=all.map(p=>p[1]);
const x0=Math.min(...xs)*8, x1=Math.max(...xs)*8, y0=Math.min(...ys)*8, y1=Math.max(...ys)*8;
for(let gx=x0;gx<x1;gx++)for(let gy=y0;gy<y1;gy++){
const p=[(2*gx+1)/16,(2*gy+1)/16]; let c=0;
for(const t of tris){if(inTri(p,t)&&++c>1) return {ok:false,reason:'overlap',tris};}
}
const H=hull(all);
if(area2(H)!==2*tris.length) return {ok:false,reason:'gap',tris};
return {ok:true,shape:classify(H),tris};
}
function accepts(type,shape){
if(type==='square') return shape==='square';
if(type==='para') return shape==='para'||shape==='rhombus';
if(type==='rhombus') return shape==='rhombus';
return false;
}
function fitOrient(tri){
const key=s=>s.map(p=>p.join(',')).sort().join('|'), K=key(tri);
for(let i=0;i<3;i++){
const v=tri[i],a=tri[(i+1)%3],b=tri[(i+2)%3];
if((a[0]-v[0])*(b[0]-v[0])+(a[1]-v[1])*(b[1]-v[1])!==0) continue;
for(let r=0;r<4;r++)for(let f=0;f<2;f++){const p={x:v[0],y:v[1],r,f}; if(key(verts(p))===K) return p;}
}
return null;
}
//CORE-END
const SHAPE_NAME={square:'hình vuông',rect:'hình chữ nhật',rhombus:'hình thoi',para:'hình bình hành',trap:'hình thang',quad:'hình tứ giác',tri:'hình tam giác'};
const COLORS=['#93c5fd','#f9a8d4','#fcd34d','#6ee7b7'];
const NS='http://www.w3.org/2000/svg';
const $=id=>document.getElementById(id);
function el(tag,attrs,parent){const e=document.createElementNS(NS,tag);for(const k in attrs)e.setAttribute(k,attrs[k]);if(parent)parent.appendChild(e);return e;}
// ----- Âm thanh -----
let ac=null;
function tone(freq,t0,dur,type,vol){
try{
ac=ac||new (window.AudioContext||window.webkitAudioContext)();
const o=ac.createOscillator(),g=ac.createGain(),t=ac.currentTime+t0;
o.type=type||'sine';o.frequency.value=freq;
g.gain.setValueAtTime(vol||.2,t);g.gain.exponentialRampToValueAtTime(.001,t+dur);
o.connect(g).connect(ac.destination);o.start(t);o.stop(t+dur+.05);
}catch(e){}
}
const sfx={
tick:()=>tone(700,0,.06,'triangle',.07),
ok:()=>[523,659,784,1047].forEach((f,i)=>tone(f,i*.12,.28,'triangle',.22)),
bad:()=>{tone(320,0,.18,'square',.06);tone(230,.18,.28,'square',.06);},
win:()=>[523,659,784,1047,784,1047,1319].forEach((f,i)=>tone(f,i*.13,.32,'triangle',.22)),
reveal:()=>[440,392,349,392].forEach((f,i)=>tone(f,i*.15,.25,'sine',.15))
};
// ----- Trạng thái -----
function freshPieces(){return [0,1,2,3].map(i=>({id:i,x:3+3*i,y:8,r:0,f:0}));}
const S=TASKS.map(()=>({tries:MAX_TRIES,done:false,revealed:false,starred:false,pieces:freshPieces()}));
let cur=0, sel=null, drag=null;
// ----- Bảng -----
const svg=$('board');
svg.setAttribute('viewBox',`0 0 ${COLS*U} ${ROWS*U}`);
const gGrid=el('g',{},svg), gPieces=el('g',{},svg);
el('rect',{x:0,y:TRAY_Y*U+U/2,width:COLS*U,height:(ROWS-TRAY_Y)*U-U/2,fill:'#f1f5f9'},gGrid);
el('text',{x:8,y:TRAY_Y*U+U/2+16,'font-size':13,fill:'#64748b'},gGrid).textContent='Khay miếng ghép';
el('text',{x:8,y:16,'font-size':13,fill:'#64748b'},gGrid).textContent='Khu vực ghép hình';
for(let x=0;x<=COLS;x++)for(let y=0;y<=ROWS;y++)el('circle',{cx:x*U,cy:y*U,r:2,fill:'#cbd5e1'},gGrid);
function miniSVG(polys,size,fill,stroke,label){
const all=polys.flat(), xs=all.map(p=>p[0]), ys=all.map(p=>p[1]);
const mnx=Math.min(...xs),mny=Math.min(...ys),w=Math.max(...xs)-mnx,h=Math.max(...ys)-mny;
const s=(size-8)/Math.max(w,h,1), ox=(size-w*s)/2, oy=(size-h*s)/2;
let out=`<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">`;
polys.forEach(t=>{out+=`<polygon points="${t.map(([x,y])=>`${ox+(x-mnx)*s},${oy+(y-mny)*s}`).join(' ')}" fill="${fill}" stroke="${stroke}" stroke-width="1.3" stroke-linejoin="round"/>`;});
if(label) out+=`<text x="${size/2}" y="${size/2+5}" text-anchor="middle" font-size="14" font-weight="700" fill="#fff">${label}</text>`;
return out+'</svg>';
}
function renderTabs(){
$('tabs').innerHTML='';
TASKS.forEach((T,i)=>{
const st=S[i], b=document.createElement('button');
b.className='tab'+(i===cur?' active':'')+(st.starred?' done':'');
b.innerHTML=miniSVG([hull(T.sol.flat())],46,'#3b82f6','#1d4ed8',T.key)+
`<span><b>Hình ${T.key} ${st.starred?'⭐':''}</b><small>${T.title}</small></span>`;
b.onclick=()=>goTask(i);
$('tabs').appendChild(b);
});
}
function render(){
const st=S[cur];
gPieces.innerHTML='';
st.pieces.forEach(p=>{
const px=p.px!=null?p.px:p.x*U, py=p.py!=null?p.py:p.y*U;
const g=el('g',{class:'piece'+(p.id===sel?' sel':''),transform:`translate(${px},${py})`},gPieces);
g.dataset.id=p.id;
const rel=BASE.map(b=>orient(b,p.r,p.f).map(v=>v*U));
const fill=st.done?'#4ade80':st.revealed?'#fde68a':COLORS[p.id];
el('polygon',{class:'body',points:rel.map(v=>v.join(',')).join(' '),fill,stroke:'#334155','stroke-width':1.5,'stroke-linejoin':'round'},g);
el('line',{x1:rel[0][0],y1:rel[0][1],x2:rel[1][0],y2:rel[1][1],stroke:'#1e293b','stroke-width':5,'stroke-linecap':'round'},g);
el('line',{x1:rel[0][0],y1:rel[0][1],x2:rel[2][0],y2:rel[2][1],stroke:'#1e293b','stroke-width':2.5,'stroke-dasharray':'5 4'},g);
const u1=[rel[1][0]/(2*U),rel[1][1]/(2*U)], u2=[rel[2][0]/U,rel[2][1]/U], m=0.22*U;
el('path',{d:`M${u1[0]*m},${u1[1]*m} L${(u1[0]+u2[0])*m},${(u1[1]+u2[1])*m} L${u2[0]*m},${u2[1]*m}`,fill:'none',stroke:'#1e293b','stroke-width':1.5},g);
const c=[(rel[1][0]+rel[2][0])/3,(rel[1][1]+rel[2][1])/3];
el('text',{x:c[0],y:c[1]+5,'text-anchor':'middle','font-size':15,'font-weight':700,fill:'#0f172a','pointer-events':'none'},g).textContent=p.id+1;
});
updateUI();
}
function updateUI(){
const st=S[cur], T=TASKS[cur];
$('taskTitle').textContent=`Nhiệm vụ ${T.key}: ghép 4 miếng thành ${T.name}`+(st.done?' ✅':'');
$('tries').textContent=st.tries;
$('triesBox').classList.toggle('low',st.tries<=3);
const n=S.filter(s=>s.starred).length;
$('stars').innerHTML=[0,1,2].map(i=>`<span class="star${i<n?' on':''}">★</span>`).join('');
const lock=st.done||st.revealed;
['btnCCW','btnCW','btnFlip','btnCheck'].forEach(id=>$(id).disabled=lock);
renderTabs();
}
function msg(text,kind){const m=$('msg');m.textContent=text;m.className='msg '+(kind||'');}
// ----- Kéo thả -----
function svgPt(e){const pt=svg.createSVGPoint();pt.x=e.clientX;pt.y=e.clientY;return pt.matrixTransform(svg.getScreenCTM().inverse());}
function clampP(p){
const v=verts(p), xs=v.map(a=>a[0]), ys=v.map(a=>a[1]);
if(Math.min(...xs)<0)p.x-=Math.min(...xs); if(Math.max(...xs)>COLS)p.x-=Math.max(...xs)-COLS;
if(Math.min(...ys)<0)p.y-=Math.min(...ys); if(Math.max(...ys)>ROWS)p.y-=Math.max(...ys)-ROWS;
}
gPieces.addEventListener('pointerdown',e=>{
const g=e.target.closest('.piece'); if(!g) return;
const st=S[cur], p=st.pieces.find(q=>q.id==g.dataset.id);
if(st.done||st.revealed) return;
sel=p.id; st.pieces=st.pieces.filter(q=>q!==p).concat(p);
const m=svgPt(e); drag={p,dx:m.x-p.x*U,dy:m.y-p.y*U,moved:false};
try{svg.setPointerCapture(e.pointerId);}catch(_){}
render(); e.preventDefault();
});
svg.addEventListener('pointermove',e=>{
if(!drag) return;
const m=svgPt(e), p=drag.p;
p.px=m.x-drag.dx; p.py=m.y-drag.dy;
if(Math.abs(p.px-p.x*U)+Math.abs(p.py-p.y*U)>4) drag.moved=true;
const g=gPieces.querySelector(`[data-id="${p.id}"]`);
if(g) g.setAttribute('transform',`translate(${p.px},${p.py})`);
});
function endDrag(){
if(!drag) return;
const p=drag.p, moved=drag.moved;
if(moved&&p.px!=null){p.x=Math.round(p.px/U);p.y=Math.round(p.py/U);}
delete p.px; delete p.py; clampP(p); drag=null; render();
if(moved){sfx.tick(); autoCheck();}
}
svg.addEventListener('pointerup',endDrag);
svg.addEventListener('pointercancel',endDrag);
gPieces.addEventListener('dblclick',e=>{if(e.target.closest('.piece')) transformSel(p=>{p.r=(p.r+1)%4;});});
function transformSel(fn){
const st=S[cur]; if(st.done||st.revealed) return;
const p=st.pieces.find(q=>q.id===sel);
if(!p){msg('Hãy chạm chọn một miếng ghép trước nhé.','info');return;}
const c0=centroid(verts(p)); fn(p); const c1=centroid(verts(p));
p.x+=Math.round(c0[0]-c1[0]); p.y+=Math.round(c0[1]-c1[1]);
clampP(p); sfx.tick(); render(); autoCheck();
}
const rotCW=()=>transformSel(p=>{p.r=(p.r+1)%4;});
const rotCCW=()=>transformSel(p=>{p.r=(p.r+3)%4;});
const flip=()=>transformSel(p=>{p.f^=1;p.r=(4-p.r)%4;});
$('btnCW').onclick=rotCW; $('btnCCW').onclick=rotCCW; $('btnFlip').onclick=flip;
document.addEventListener('keydown',e=>{
const k=e.key.toLowerCase();
if(k==='r')rotCW(); else if(k==='e')rotCCW(); else if(k==='f')flip();
});
// ----- Luật chơi -----
function autoCheck(){
const st=S[cur]; if(st.done||st.revealed) return;
const res=analyze(st.pieces);
if(res.ok&&accepts(TASKS[cur].type,res.shape)) win(res);
}
function failText(res){
const T=TASKS[cur];
if(res.reason==='overlap') return 'Các miếng ghép đang chồng lên nhau. Hãy đặt các miếng sát cạnh nhau, không đè lên nhau.';
if(res.reason==='gap') return 'Các miếng chưa ghép khít: còn khe hở hoặc có miếng nằm rời. Cả 4 miếng phải ghép sát thành một hình.';
const got=SHAPE_NAME[res.shape]||'một hình nhiều cạnh';
let t=`Em đã ghép được ${got}, nhưng nhiệm vụ cần ${T.name}.`;
if(T.type==='para'&&(res.shape==='rect'||res.shape==='square')) t+=' Hãy thử ghép để có cạnh bên nghiêng.';
if(T.type==='rhombus'&&res.shape==='square') t+=' Hình thoi có 4 cạnh bằng nhau nhưng không có góc vuông.';
if(T.type==='rhombus'&&res.shape==='para') t+=' Gợi ý: hình thoi có 4 cạnh bằng nhau. Thử đặt 4 góc vuông chụm vào giữa.';
return t;
}
function check(){
const st=S[cur]; if(st.done||st.revealed) return;
const res=analyze(st.pieces);
if(res.ok&&accepts(TASKS[cur].type,res.shape)){win(res);return;}
st.tries--; sfx.bad();
if(st.tries<=0){st.tries=0; reveal(); return;}
msg(failText(res)+` Em còn ${st.tries} lượt.`,'bad'); updateUI();
}
$('btnCheck').onclick=check;
function win(res){
const st=S[cur], T=TASKS[cur], first=!st.starred;
st.done=true; st.starred=true; sel=null;
if(first){
const shelf=$('shelf'); const e=shelf.querySelector('.empty'); if(e) e.remove();
const d=document.createElement('div'); d.className='item';
d.innerHTML=miniSVG(res.tris,72,'#86efac','#166534')+`<div>Hình ${T.key}: ${T.title}</div>`;
shelf.appendChild(d);
}
render();
const n=S.filter(s=>s.starred).length;
if(n===3&&first){sfx.win(); msg(`🎉 Xuất sắc! Em đã ghép được ${T.name} và chinh phục cả 3 thử thách!`,'ok');}
else{sfx.ok(); msg(`✅ Đúng rồi! Em đã ghép được ${T.name}.`+(first?' Em được thưởng 1 ⭐.':' (Hình này em đã có sao rồi.)')+(n<3?' Hãy chọn hình tiếp theo nhé!':''),'ok');}
}
function reveal(){
const st=S[cur], T=TASKS[cur]; st.revealed=true; sel=null; sfx.reveal();
const all=T.sol.flat(), w=Math.max(...all.map(p=>p[0])), h=Math.max(...all.map(p=>p[1]));
const ox=Math.floor((COLS-w)/2), oy=Math.max(1,Math.floor((TRAY_Y-h)/2));
st.pieces.forEach(p=>{
const t=fitOrient(T.sol[p.id].map(([x,y])=>[x+ox,y+oy]));
p.r=t.r; p.f=t.f; p.sx=p.x; p.sy=p.y; p.tx=t.x; p.ty=t.y;
});
msg(`Hết lượt rồi! Đây là một cách ghép ${T.name} đúng. Em quan sát kỹ rồi bấm "Làm lại" để tự ghép nhé. (Còn nhiều cách ghép đúng khác.)`,'info');
const t0=performance.now();
(function step(now){
if(S[cur]!==st) return;
let k=Math.min(1,(now-t0)/900); const e=k<.5?2*k*k:1-Math.pow(-2*k+2,2)/2;
st.pieces.forEach(p=>{p.px=(p.sx+(p.tx-p.sx)*e)*U; p.py=(p.sy+(p.ty-p.sy)*e)*U;});
if(k<1){render(); requestAnimationFrame(step);}
else{st.pieces.forEach(p=>{p.x=p.tx;p.y=p.ty;delete p.px;delete p.py;}); render();}
})(t0);
}
function resetTask(i){const st=S[i]; st.tries=MAX_TRIES; st.done=false; st.revealed=false; st.pieces=freshPieces();}
function goTask(i){
if(i===cur) return;
if(drag) endDrag();
cur=i; sel=null;
const st=S[i];
if(!st.done) resetTask(i);
render();
msg(st.done?`Em đã hoàn thành ${TASKS[i].name}. Bấm "Làm lại" nếu muốn ghép thêm cách khác.`
:`Nhiệm vụ ${TASKS[i].key}: dùng cả 4 miếng ghép thành ${TASKS[i].name}. Em có ${MAX_TRIES} lượt thử.`,'info');
}
$('btnReset').onclick=()=>{
resetTask(cur); sel=null; render();
msg(`Bắt đầu lại! Em có ${MAX_TRIES} lượt để ghép ${TASKS[cur].name}.`,'info');
};
render();
</script>
</body>
</html>
Game Source: Trò chơi ghép hình – Toán 4
Creator: MagicBunny92
Libraries: none
Complexity: complex (391 lines, 19.9 KB)
The full source code is displayed above on this page.
Remix Instructions
To remix this game, copy the source code above and modify it. Add a ARCADELAB header at the top with "remix_of: tr-ch-i-gh-p-h-nh-to-n-4-magicbunny92" to link back to the original. Then publish at arcadelab.ai/publish.