Skip to content
VibeCodeBench
Back to the app

The code

Notebook Mini-Golf by Claude Opus 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

Try 1 · index.html

worksshown54.5 KB · 743 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no,viewport-fit=cover">
<title>Notebook Mini Golf</title>
<style>
:root{--ink:#1f3f9a;--red:#d23a3a;--paper:#fbf8ee;--hand:"Segoe Print","Bradley Hand","Chalkboard SE","Comic Sans MS","Marker Felt",cursive}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:var(--paper);overscroll-behavior:none}
body{touch-action:none;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;font-family:var(--hand);color:var(--ink)}
#c{position:fixed;left:0;top:0;width:100%;height:100%;display:block;touch-action:none;cursor:crosshair}
#hud{position:fixed;top:0;left:0;right:0;display:flex;justify-content:space-between;align-items:flex-start;gap:6px;padding:6px 8px;padding-top:max(6px,env(safe-area-inset-top));pointer-events:none;z-index:2}
.card{background:rgba(251,248,238,.9);border:2px solid var(--ink);border-radius:255px 15px 225px 15px/15px 225px 15px 255px;padding:4px 14px;line-height:1.3;font-size:15px;box-shadow:2px 3px 0 rgba(31,63,154,.18);white-space:nowrap}
#l1{font-weight:bold}
#btns{display:flex;gap:6px;flex-wrap:wrap;justify-content:flex-end}
.btn{pointer-events:auto;font-family:var(--hand);font-size:15px;color:var(--ink);background:rgba(255,253,240,.94);border:2px solid var(--ink);border-radius:15px 225px 15px 255px/255px 15px 225px 15px;min-width:44px;min-height:44px;padding:4px 12px;cursor:pointer;box-shadow:2px 3px 0 rgba(31,63,154,.25);touch-action:manipulation}
.btn:active{transform:translate(2px,2px);box-shadow:none}
.btn:focus-visible{outline:3px dashed var(--red);outline-offset:2px}
#note{position:fixed;left:14px;bottom:max(10px,env(safe-area-inset-bottom));max-width:min(54vw,420px);font-size:19px;line-height:1.2;color:var(--red);transform:rotate(-3deg) translateY(10px);opacity:0;transition:opacity .35s,transform .35s;pointer-events:none;z-index:2;text-shadow:0 0 4px var(--paper),0 0 3px var(--paper),0 0 2px var(--paper)}
#note.show{opacity:1;transform:rotate(-3deg) translateY(0)}
#note.good{color:#1f7a3a}
#note.meh{color:var(--ink)}
#note::before{content:"\270E  "}
#banner{position:fixed;left:50%;top:24%;transform:translate(-50%,0) rotate(-1.5deg);opacity:0;pointer-events:none;z-index:3;text-align:center;background:rgba(255,240,110,.82);padding:10px 20px;max-width:90vw;border-radius:6px 18px 8px 22px;box-shadow:3px 4px 0 rgba(0,0,0,.08)}
#banner .t{font-size:24px;font-weight:bold;color:var(--ink)}
#banner .s{font-size:16px;color:#333;margin-top:2px}
#banner.show{animation:ban 3s ease forwards}
@keyframes ban{0%{opacity:0;transform:translate(-50%,12px) rotate(-1.5deg)}10%{opacity:1;transform:translate(-50%,0) rotate(-1.5deg)}78%{opacity:1;transform:translate(-50%,0) rotate(-1.5deg)}100%{opacity:0;transform:translate(-50%,-8px) rotate(-1.5deg)}}
#demoTag{position:fixed;left:50%;bottom:max(12px,env(safe-area-inset-bottom));transform:translateX(-50%) rotate(1deg);display:none;z-index:3;pointer-events:none;background:rgba(255,120,180,.35);color:#7a1440;padding:4px 14px;font-size:15px;border-radius:12px 4px 14px 5px}
#demoTag.show{display:block}
#over{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(40,40,70,.28);z-index:5;padding:12px}
#over[hidden]{display:none}
.sheet{background-color:var(--paper);background-image:linear-gradient(90deg,transparent 30px,rgba(225,80,90,.5) 30px,rgba(225,80,90,.5) 32px,transparent 32px),repeating-linear-gradient(transparent 0 27px,rgba(90,150,215,.42) 27px 28px);border:2px solid var(--ink);border-radius:15px 225px 15px 255px/255px 15px 225px 15px;padding:14px 18px 18px 40px;max-width:min(580px,95vw);max-height:92vh;overflow:auto;transform:rotate(-1deg);box-shadow:5px 7px 0 rgba(31,63,154,.2);text-align:center}
.sheet h2{margin:2px 0 6px;font-size:28px;color:var(--red)}
table{border-collapse:collapse;margin:6px auto;font-size:15px}
td,th{padding:3px 3px;text-align:center;min-width:22px}
th{color:var(--red);font-weight:bold}
td.lab,th.lab{text-align:left;padding-right:8px}
.under{display:inline-block;border:2px solid var(--red);border-radius:50%;min-width:24px;padding:0 3px}
.overp{display:inline-block;border:2px solid var(--ink);min-width:22px;padding:0 3px}
#verdict{font-size:19px;margin:8px 0 4px}
#best{font-size:15px;color:#555;margin:0 0 6px}
.big{font-size:20px;padding:8px 26px;margin-top:6px}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud">
  <div class="card" id="info"><div id="l1">Hole 1/9 · Par 2</div><div id="l2">Strokes 0 · Total E</div></div>
  <div id="btns">
    <button class="btn" id="bSnd" type="button" aria-label="Toggle sound">&#9834; on</button>
    <button class="btn" id="bRetry" type="button" aria-label="Retry this hole">&#8634; hole</button>
    <button class="btn" id="bRestart" type="button" aria-label="Restart the round">restart</button>
  </div>
</div>
<div id="banner"><div class="t"></div><div class="s"></div></div>
<div id="note"></div>
<div id="demoTag">demo &middot; tap anywhere to play</div>
<div id="over" hidden>
  <div class="sheet">
    <h2>Scorecard</h2>
    <table id="tbl"></table>
    <p id="verdict"></p>
    <p id="best"></p>
    <button class="btn big" id="bAgain" type="button">Play again</button>
  </div>
</div>
<script>
(function(){
'use strict';
const $=id=>document.getElementById(id);
const cv=$('c'), ctx=cv.getContext('2d');
const st=document.createElement('canvas'), sctx=st.getContext('2d');
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}
const rng=mulberry32(20260930), arng=mulberry32(777);
const pick=a=>a[Math.floor(rng()*a.length)];
const clamp=(v,a,b)=>v<a?a:v>b?b:v;
const ease=t=>t<0.5?2*t*t:1-Math.pow(-2*t+2,2)/2;
const TAU=Math.PI*2;
const DT=1/120,R=9,CUPR=15,MAXV=1100,SINKV=300,GRAV=1400,MAXSTROKES=10,TUNT=0.55;
const FIT={x:60,y:85,w:880,h:470};
const INK='#1f3f9a',RED='#d23a3a';
const HAND='"Segoe Print","Bradley Hand","Chalkboard SE","Comic Sans MS","Marker Felt",cursive';

/* ---------- geometry helpers ---------- */
const rect=(x,y,w,h)=>[[x,y],[x+w,y],[x+w,y+h],[x,y+h]];
function blob(cx,cy,rx,ry,s){const p=[];for(let i=0;i<36;i++){const a=i/36*TAU;const k=1+0.13*Math.sin(3*a+s)+0.08*Math.sin(5*a+s*2.3)+0.05*Math.sin(8*a+s*1.7);p.push([cx+Math.cos(a)*rx*k,cy+Math.sin(a)*ry*k]);}return p;}
function river(x0,x1,y0,y1,s){const L=[],Rr=[];const n=16;for(let i=0;i<=n;i++){const y=y0+(y1-y0)*i/n;L.push([x0+10*Math.sin(i*1.3+s)+6*Math.sin(i*2.7+s*2),y]);}for(let i=n;i>=0;i--){const y=y0+(y1-y0)*i/n;Rr.push([x1+10*Math.sin(i*1.1+s*1.5)+6*Math.sin(i*2.3+s),y]);}return L.concat(Rr);}
function bbox(p){let a=1e9,b=1e9,c=-1e9,d=-1e9;for(const q of p){a=Math.min(a,q[0]);b=Math.min(b,q[1]);c=Math.max(c,q[0]);d=Math.max(d,q[1]);}return{x:a,y:b,w:c-a,h:d-b};}
function pip(x,y,p){let ins=false;for(let i=0,j=p.length-1;i<p.length;j=i++){const xi=p[i][0],yi=p[i][1],xj=p[j][0],yj=p[j][1];if(((yi>y)!==(yj>y))&&(x<(xj-xi)*(y-yi)/(yj-yi)+xi))ins=!ins;}return ins;}
const inR=(x,y,s)=>x>=s.x&&x<=s.x+s.w&&y>=s.y&&y<=s.y+s.h;

/* ---------- holes ---------- */
const HOLE_DEFS=[
 {name:'Paper Clip Pass',idea:'New: paper-clip bumpers fling the ball back.',par:2,tee:[170,310],cup:[830,310],bounds:rect(80,170,840,280),clips:[{a:[500,228],b:[500,338]}]},
 {name:'Eraser Alley',idea:'New: the eraser block soaks up bounces.',par:3,tee:[160,200],cup:[810,470],bounds:[[80,100],[920,100],[920,540],[700,540],[700,300],[80,300]],erasers:[{x:430,y:160,w:90,h:80}]},
 {name:'Slippery Slope',idea:'New: shaded slopes curve the ball downhill.',par:3,tee:[160,310],cup:[840,310],bounds:rect(80,140,840,340),slopes:[{x:360,y:140,w:280,h:340,ax:0,ay:340}]},
 {name:'Ink Blot Lake',idea:'New: ink is water. +1 stroke and back you go.',par:3,tee:[160,310],cup:[840,310],bounds:rect(80,120,840,380),waters:[blob(500,310,150,105,1.3)]},
 {name:'Sticky Tape Bridge',idea:'New: cross the ink on the (slightly sticky) tape.',par:3,tee:[160,420],cup:[840,200],bounds:rect(80,120,840,380),waters:[river(420,580,90,530,2.1)],bridges:[{x:395,y:278,w:210,h:66}]},
 {name:'Ruler Gate',idea:'New: time your putt past the sliding ruler.',par:3,tee:[160,310],cup:[840,310],bounds:rect(80,120,840,380),walls:[[500,120,500,250],[500,370,500,500]],rulers:[{cx:500,cy:310,w:26,h:150,axis:'y',amp:95,period:3.2}]},
 {name:'Staple Jump',idea:'New: hit the staple ramp hard to jump the ink river.',par:3,tee:[160,310],cup:[830,310],bounds:rect(80,140,840,340),waters:[river(590,690,110,510,0.7)],ramps:[{x:450,y:255,w:80,h:110,dx:1,dy:0}]},
 {name:'Spiral Tunnel',idea:'New: roll into the binding tunnel, pop out the other side.',par:3,tee:[160,420],cup:[830,250],bounds:rect(80,110,840,400),walls:[[460,110,460,510],[540,110,540,510]],tunnels:[{a:[449,185],ad:[-1,0],b:[551,435],bd:[1,0]}],band:{x:460,y:110,w:80,h:400}},
 {name:'Final Exam',idea:'Everything at once: slope, ruler, ink and clip.',par:4,tee:[150,450],cup:[860,170],bounds:rect(80,100,840,420),slopes:[{x:220,y:100,w:190,h:420,ax:0,ay:-300}],walls:[[560,100,560,300],[560,420,560,520]],rulers:[{cx:560,cy:360,w:26,h:140,axis:'y',amp:80,period:2.6}],waters:[blob(735,255,70,62,4.2)],clips:[{a:[680,470],b:[790,470]}]}
];
function buildHole(def){
  const H=Object.assign({walls:[],clips:[],erasers:[],slopes:[],waters:[],bridges:[],rulers:[],ramps:[],tunnels:[],band:null},def);
  H.segs=[];
  const addPoly=(pts,e,kind)=>{for(let i=0;i<pts.length;i++){const a=pts[i],b=pts[(i+1)%pts.length];H.segs.push({ax:a[0],ay:a[1],bx:b[0],by:b[1],e,kind,r:0});}};
  addPoly(H.bounds,0.72,'wall');
  for(const w of H.walls)H.segs.push({ax:w[0],ay:w[1],bx:w[2],by:w[3],e:0.72,kind:'wall',r:0});
  for(const er of H.erasers)addPoly(rect(er.x,er.y,er.w,er.h),0.22,'eraser');
  for(const c of H.clips)H.segs.push({ax:c.a[0],ay:c.a[1],bx:c.b[0],by:c.b[1],e:1.0,kind:'clip',r:12});
  H.wbb=H.waters.map(bbox);
  return H;
}
const HOLES=HOLE_DEFS.map(buildHole);

/* ---------- physics ---------- */
function newBall(x,y){return{x,y,vx:0,vy:0,z:0,vz:0,air:false,tun:0,tunT:null,tunToB:false,ts:0,tcool:0,cool:0,rest:0,time:0,hidden:false,done:null,bounces:0,lipped:false,jumped:false,tunneled:false,sx:x,sy:y};}
function launch(b,a,p){const v=p*MAXV;b.vx=Math.cos(a)*v;b.vy=Math.sin(a)*v;b.done=null;b.rest=0;b.time=0;b.bounces=0;b.lipped=false;b.jumped=false;b.tunneled=false;b.cool=0;}
function rulerState(r,t){const w=TAU/r.period;const off=r.amp*Math.sin(w*t);const v=r.amp*w*Math.cos(w*t);return r.axis==='y'?{x:r.cx-r.w/2,y:r.cy+off-r.h/2,w:r.w,h:r.h,vx:0,vy:v}:{x:r.cx+off-r.w/2,y:r.cy-r.h/2,w:r.w,h:r.h,vx:v,vy:0};}
function inWater(x,y,H){
  for(let i=0;i<H.waters.length;i++){const bb=H.wbb[i];if(x<bb.x||x>bb.x+bb.w||y<bb.y||y>bb.y+bb.h)continue;if(pip(x,y,H.waters[i])){for(const br of H.bridges)if(inR(x,y,br))return false;return true;}}
  return false;
}
function collide(b,H,t,ev){
  const segs=H.segs;
  for(let i=0;i<segs.length;i++){const s=segs[i];
    const ex=s.bx-s.ax,ey=s.by-s.ay,L2=ex*ex+ey*ey;
    let u=((b.x-s.ax)*ex+(b.y-s.ay)*ey)/L2;u=u<0?0:u>1?1:u;
    const px=s.ax+ex*u,py=s.ay+ey*u;let dx=b.x-px,dy=b.y-py;const rr=R+s.r;const d2=dx*dx+dy*dy;
    if(d2>=rr*rr)continue;
    let d=Math.sqrt(d2);if(d<1e-6){dx=-ey;dy=ex;d=Math.sqrt(L2);}
    const nx=dx/d,ny=dy/d;b.x=px+nx*rr;b.y=py+ny*rr;
    const vn=b.vx*nx+b.vy*ny;
    if(vn<0){b.vx-=(1+s.e)*vn*nx;b.vy-=(1+s.e)*vn*ny;
      const tx=-ny,ty=nx,vt=b.vx*tx+b.vy*ty;b.vx-=vt*0.05*tx;b.vy-=vt*0.05*ty;
      if(-vn>40){if(s.kind==='clip'){b.vx+=nx*70;b.vy+=ny*70;}b.bounces++;}
      if(ev&&-vn>30)ev(s.kind,-vn);}
  }
  for(const ru of H.rulers){const q=rulerState(ru,t);
    const cx=clamp(b.x,q.x,q.x+q.w),cy=clamp(b.y,q.y,q.y+q.h);const dx=b.x-cx,dy=b.y-cy;const d2=dx*dx+dy*dy;let nx,ny,pen;
    if(d2>0){if(d2>=R*R)continue;const d=Math.sqrt(d2);nx=dx/d;ny=dy/d;pen=R-d;}
    else{const l=b.x-q.x,rr=q.x+q.w-b.x,tp=b.y-q.y,bt=q.y+q.h-b.y;const m=Math.min(l,rr,tp,bt);
      if(m===l){nx=-1;ny=0;pen=l+R;}else if(m===rr){nx=1;ny=0;pen=rr+R;}else if(m===tp){nx=0;ny=-1;pen=tp+R;}else{nx=0;ny=1;pen=bt+R;}}
    b.x+=nx*pen;b.y+=ny*pen;
    const rvx=b.vx-q.vx,rvy=b.vy-q.vy,vn=rvx*nx+rvy*ny;
    if(vn<0){b.vx-=1.55*vn*nx;b.vy-=1.55*vn*ny;if(-vn>40)b.bounces++;if(ev&&-vn>30)ev('ruler',-vn);}
  }
}
function stepBall(b,H,t,dt,ev){
  if(b.done)return;
  b.time+=dt;
  if(b.time>30){b.vx=b.vy=0;b.done='stopped';return;}
  if(b.tun>0){
    b.tun-=dt;
    if(b.tun<=0){const T=b.tunT;const p=b.tunToB?T.b:T.a,d=b.tunToB?T.bd:T.ad;b.x=p[0]+d[0]*8;b.y=p[1]+d[1]*8;b.vx=d[0]*b.ts;b.vy=d[1]*b.ts;b.hidden=false;b.tcool=0.5;b.tun=0;ev&&ev('tunout',b.ts);}
    return;
  }
  let sp;
  if(b.air){b.z+=b.vz*dt;b.vz-=GRAV*dt;if(b.z<=0){b.z=0;b.vz=0;b.air=false;b.vx*=0.85;b.vy*=0.85;ev&&ev('land',200);}}
  else{
    for(const s of H.slopes)if(inR(b.x,b.y,s)){b.vx+=s.ax*dt;b.vy+=s.ay*dt;}
    for(const rp of H.ramps)if(inR(b.x,b.y,rp)){const vd=b.vx*rp.dx+b.vy*rp.dy;if(vd>300){b.air=true;b.vz=vd*0.5;b.z=0.001;b.jumped=true;ev&&ev('jump',vd);}else{b.vx-=rp.dx*450*dt;b.vy-=rp.dy*450*dt;}break;}
    sp=Math.hypot(b.vx,b.vy);
    if(!b.air&&sp>0){let f=160+0.55*sp;for(const br of H.bridges)if(inR(b.x,b.y,br)){f+=1.3*sp;break;}const ns=Math.max(0,sp-f*dt);b.vx*=ns/sp;b.vy*=ns/sp;}
  }
  sp=Math.hypot(b.vx,b.vy);
  const n=Math.max(1,Math.ceil(sp*dt/3)),h=dt/n;
  for(let i=0;i<n;i++){b.x+=b.vx*h;b.y+=b.vy*h;collide(b,H,t,ev);}
  if(!b.air){
    if(b.tcool>0)b.tcool-=dt;
    else for(const T of H.tunnels){
      const da=Math.hypot(b.x-T.a[0],b.y-T.a[1]),db=Math.hypot(b.x-T.b[0],b.y-T.b[1]);
      if(da<28||db<28){b.tunT=T;b.tunToB=da<28;b.tun=TUNT;b.ts=Math.min(700,Math.max(260,Math.hypot(b.vx,b.vy)*0.9));b.hidden=true;b.tunneled=true;b.vx=b.vy=0;ev&&ev('tunnel',b.ts);return;}
    }
    if(inWater(b.x,b.y,H)){b.done='water';b.vx=b.vy=0;ev&&ev('splash',1);return;}
    const cx=H.cup[0]-b.x,cy=H.cup[1]-b.y,d=Math.hypot(cx,cy);sp=Math.hypot(b.vx,b.vy);
    if(b.cool>0)b.cool-=dt;
    else if(d<CUPR){
      const perp=sp>1?(cx*b.vy-cy*b.vx)/sp:0;
      if(sp<SINKV||(Math.abs(perp)<4&&sp<SINKV*1.35)){b.done='sunk';b.sx=b.x;b.sy=b.y;b.x=H.cup[0];b.y=H.cup[1];b.vx=b.vy=0;ev&&ev('cup',sp);return;}
      const ang=(perp>=0?-1:1)*(0.45+0.8*Math.min(1,Math.abs(perp)/CUPR));
      const co=Math.cos(ang),si=Math.sin(ang);const vx=(b.vx*co-b.vy*si)*0.72,vy=(b.vx*si+b.vy*co)*0.72;b.vx=vx;b.vy=vy;b.cool=0.3;b.lipped=true;ev&&ev('lip',sp);
    }
    if(b.cool<=0&&d<CUPR+10&&d>0.01&&sp<SINKV){const pull=520*(1-d/(CUPR+10));b.vx+=cx/d*pull*dt;b.vy+=cy/d*pull*dt;}
    sp=Math.hypot(b.vx,b.vy);
    if(sp<7){b.rest+=dt;b.vx*=0.85;b.vy*=0.85;if(b.rest>0.3){b.vx=b.vy=0;b.done='stopped';}}else b.rest=0;
  }
}

/* ---------- state ---------- */
const G={hi:0,H:null,ball:null,strokes:0,scores:new Array(9).fill(null),state:'aim',stateT:0,step:0,aim:null,trail:[],lastShot:null,shot:null,spin:0,prevX:null,prevY:null,dir:0};
let parts=[],demo=null,demoStopT=0,lastWord=0;
let SW=0,SH=0,dpr=1,quality=1,M=null,Minv=null,scale=1,maxDrag=180;

function resize(){
  SW=window.innerWidth;SH=window.innerHeight;
  dpr=Math.max(0.6,Math.min(window.devicePixelRatio||1,2)*quality);
  cv.width=Math.max(1,Math.round(SW*dpr));cv.height=Math.max(1,Math.round(SH*dpr));
  const small=SH<520;
  const top=small?46:68,bot=small?6:36,side=10;
  const aw=SW-side*2,ah=SH-top-bot;
  const portrait=ah>aw*1.1;
  const fw=portrait?FIT.h:FIT.w,fh=portrait?FIT.w:FIT.h;
  scale=Math.max(0.1,Math.min(aw/fw,ah/fh));
  M=new DOMMatrix().translate(SW/2,top+ah/2).rotate(portrait?90:0).scale(scale,scale).translate(-(FIT.x+FIT.w/2),-(FIT.y+FIT.h/2));
  Minv=M.inverse();
  maxDrag=clamp(Math.min(SW,SH)*0.32,110,260);
  renderStatic();
}
function toWorld(cx,cy){return{x:Minv.a*cx+Minv.c*cy+Minv.e,y:Minv.b*cx+Minv.d*cy+Minv.f};}
function toScreen(x,y){return{x:M.a*x+M.c*y+M.e,y:M.b*x+M.d*y+M.f};}
function setWorld(c){c.setTransform(M.a*dpr,M.b*dpr,M.c*dpr,M.d*dpr,M.e*dpr,M.f*dpr);}

/* ---------- hand-drawn primitives ---------- */
function wobEdges(r,pts,closed,amp,seg){
  seg=seg||22;const out=[];const n=pts.length,E=closed?n:n-1;
  for(let i=0;i<E;i++){const a=pts[i],b=pts[(i+1)%n];const dx=b[0]-a[0],dy=b[1]-a[1];const L=Math.hypot(dx,dy)||1;const k=Math.max(1,Math.round(L/seg));const nx=-dy/L,ny=dx/L;const e=[[a[0],a[1]]];
    for(let j=1;j<k;j++){const o=(r()-0.5)*2*amp;e.push([a[0]+dx*j/k+nx*o,a[1]+dy*j/k+ny*o]);}e.push([b[0],b[1]]);out.push(e);}
  return out;
}
function tracePen(c,r,pts,closed,amp){
  const edges=wobEdges(r,pts,closed,amp);c.beginPath();
  const j0=(r()-0.5)*amp;c.moveTo(edges[0][0][0]+j0,edges[0][0][1]-j0);
  for(const e of edges){
    if(e.length===2){c.lineTo(e[1][0],e[1][1]);continue;}
    for(let j=1;j<e.length-1;j++){const p=e[j],q=e[j+1];const last=j===e.length-2;c.quadraticCurveTo(p[0],p[1],last?q[0]:(p[0]+q[0])/2,last?q[1]:(p[1]+q[1])/2);}
  }
  if(closed){const e=edges[0];const a=e[0],b=e[1];const dx=b[0]-a[0],dy=b[1]-a[1],L=Math.hypot(dx,dy)||1;const os=Math.min(12,L*0.4);c.lineTo(a[0]+dx/L*os+(r()-0.5)*amp*2,a[1]+dy/L*os+(r()-0.5)*amp*2);}
}
function pen(c,r,pts,closed,color,lw,amp){amp=amp==null?1.5:amp;c.strokeStyle=color;c.lineWidth=lw;tracePen(c,r,pts,closed,amp);c.stroke();c.save();c.globalAlpha*=0.45;c.lineWidth=lw*0.55;tracePen(c,r,pts,closed,amp*1.4);c.stroke();c.restore();}
function smoothOpen(c,p){c.beginPath();c.moveTo(p[0][0],p[0][1]);for(let i=1;i<p.length-1;i++){c.quadraticCurveTo(p[i][0],p[i][1],(p[i][0]+p[i+1][0])/2,(p[i][1]+p[i+1][1])/2);}const l=p[p.length-1];c.lineTo(l[0],l[1]);}
function smoothClosed(c,p){const n=p.length;c.beginPath();c.moveTo((p[n-1][0]+p[0][0])/2,(p[n-1][1]+p[0][1])/2);for(let i=0;i<n;i++){const a=p[i],b=p[(i+1)%n];c.quadraticCurveTo(a[0],a[1],(a[0]+b[0])/2,(a[1]+b[1])/2);}c.closePath();}
function penCircle(c,r,cx,cy,rad,color,lw,amp){const n=Math.max(10,Math.round(rad*TAU/8));const a0=r()*TAU;const p=[];const extra=Math.max(1,Math.round(n*0.08));for(let i=0;i<=n+extra;i++){const a=a0+i/n*TAU;const rr=rad+(r()-0.5)*2*(amp==null?1:amp)*0.6;p.push([cx+Math.cos(a)*rr,cy+Math.sin(a)*rr]);}c.strokeStyle=color;c.lineWidth=lw;smoothOpen(c,p);c.stroke();}
function pathPoly(c,p){c.beginPath();c.moveTo(p[0][0],p[0][1]);for(let i=1;i<p.length;i++)c.lineTo(p[i][0],p[i][1]);c.closePath();}
function rr(c,x,y,w,h,r){c.beginPath();c.moveTo(x+r,y);c.lineTo(x+w-r,y);c.quadraticCurveTo(x+w,y,x+w,y+r);c.lineTo(x+w,y+h-r);c.quadraticCurveTo(x+w,y+h,x+w-r,y+h);c.lineTo(x+r,y+h);c.quadraticCurveTo(x,y+h,x,y+h-r);c.lineTo(x,y+r);c.quadraticCurveTo(x,y,x+r,y);c.closePath();}
function hatch(c,r,bb,ang,sp,color,lw){c.strokeStyle=color;c.lineWidth=lw;c.lineCap='round';const cx=bb.x+bb.w/2,cy=bb.y+bb.h/2,D=Math.hypot(bb.w,bb.h)/2+lw;const dx=Math.cos(ang),dy=Math.sin(ang),px=-dy,py=dx;
  for(let k=-D;k<=D;k+=sp){const j=(r()-0.5)*sp*0.35;const ox=cx+px*(k+j),oy=cy+py*(k+j);c.beginPath();c.moveTo(ox-dx*D+(r()-0.5)*6,oy-dy*D+(r()-0.5)*6);c.quadraticCurveTo(ox+(r()-0.5)*5,oy+(r()-0.5)*5,ox+dx*D,oy+dy*D);c.stroke();}}
function arrow(c,r,x,y,ang,len,color,lw){const dx=Math.cos(ang),dy=Math.sin(ang);const x2=x+dx*len/2,y2=y+dy*len/2;pen(c,r,[[x-dx*len/2,y-dy*len/2],[x2,y2]],false,color,lw,0.8);const h=len*0.32;pen(c,r,[[x2-dx*h-dy*h*0.6,y2-dy*h+dx*h*0.6],[x2,y2],[x2-dx*h+dy*h*0.6,y2-dy*h-dx*h*0.6]],false,color,lw,0.4);}
function starPts(cx,cy,r1,r2,rot){const p=[];for(let i=0;i<10;i++){const a=rot+i/10*TAU-Math.PI/2;const rad=i%2?r2:r1;p.push([cx+Math.cos(a)*rad,cy+Math.sin(a)*rad]);}return p;}
function bez(s,e,u){const sg=e[0]>s[0]?1:-1;const c1=[s[0]+sg*45,s[1]],c2=[e[0]-sg*45,e[1]];const v=1-u;return[v*v*v*s[0]+3*v*v*u*c1[0]+3*v*u*u*c2[0]+u*u*u*e[0],v*v*v*s[1]+3*v*v*u*c1[1]+3*v*u*u*c2[1]+u*u*u*e[1]];}

/* ---------- course drawing (static, seeded) ---------- */
function renderStatic(){
  st.width=cv.width;st.height=cv.height;
  const c=sctx;c.setTransform(1,0,0,1,0,0);c.globalAlpha=1;c.globalCompositeOperation='source-over';
  const w=st.width,h=st.height;
  c.fillStyle='#fbf8ee';c.fillRect(0,0,w,h);
  const pr=mulberry32(99);
  c.fillStyle='rgba(120,100,60,0.06)';
  const n=Math.min(4000,(w*h)/6000|0);for(let i=0;i<n;i++)c.fillRect(pr()*w,pr()*h,1.5*dpr,1.5*dpr);
  const gap=30*dpr;c.strokeStyle='rgba(90,150,215,0.42)';c.lineWidth=Math.max(1,dpr*0.9);c.beginPath();
  for(let y=gap*2.4;y<h;y+=gap){const yy=Math.round(y)+0.5;c.moveTo(0,yy);c.lineTo(w,yy);}c.stroke();
  c.strokeStyle='rgba(225,80,90,0.55)';c.lineWidth=Math.max(1,dpr*1.2);const mx=Math.round(56*dpr)+0.5;c.beginPath();c.moveTo(mx,0);c.lineTo(mx,h);c.moveTo(mx+3*dpr,0);c.lineTo(mx+3*dpr,h);c.stroke();
  for(const f of [0.2,0.5,0.8]){c.fillStyle='#ece6d4';c.beginPath();c.arc(24*dpr,h*f,9*dpr,0,TAU);c.fill();c.strokeStyle='rgba(0,0,0,0.12)';c.lineWidth=dpr;c.stroke();}
  if(!G.H||!M)return;
  setWorld(c);
  drawCourse(c,G.H,G.hi);
}
function doodles(c,r,H){
  const bb=bbox(H.bounds);let i=0;
  for(let tries=0;i<6&&tries<120;tries++){
    const x=FIT.x-30+r()*(FIT.w+60),y=FIT.y-20+r()*(FIT.h+40);
    if(x>bb.x-34&&x<bb.x+bb.w+34&&y>bb.y-34&&y<bb.y+bb.h+34)continue;
    i++;const k=Math.floor(r()*4);c.save();c.globalAlpha=0.42;const col='#4d5866';
    if(k===0){const p=[];for(let a=0;a<TAU*2.6;a+=0.3){const rad=1.5+a*2.1;p.push([x+Math.cos(a)*rad,y+Math.sin(a)*rad]);}c.strokeStyle=col;c.lineWidth=1.4;smoothOpen(c,p);c.stroke();}
    else if(k===1){pen(c,r,starPts(x,y,13,6,r()),true,col,1.4,0.6);}
    else if(k===2){penCircle(c,r,x,y,12,col,1.4,1);c.fillStyle=col;c.beginPath();c.arc(x-4,y-3,1.5,0,TAU);c.arc(x+4,y-3,1.5,0,TAU);c.fill();c.beginPath();c.arc(x,y+1,6,0.3,Math.PI-0.3);c.stroke();}
    else{const s=11;pen(c,r,rect(x-s,y-s,s*1.6,s*1.6),true,col,1.3,0.5);pen(c,r,rect(x-s*0.4,y-s*1.6,s*1.6,s*1.6),true,col,1.3,0.5);for(const o of [[0,0],[s*1.6,0],[0,s*1.6],[s*1.6,s*1.6]])pen(c,r,[[x-s+o[0],y-s+o[1]],[x-s*0.4+o[0],y-s*1.6+o[1]]],false,col,1.2,0.3);}
    c.restore();
  }
}
function drawInk(c,r,poly){
  const bb=bbox(poly);
  c.fillStyle='rgba(26,38,104,0.95)';smoothClosed(c,poly);c.fill();
  c.strokeStyle='#0e1440';c.lineWidth=2.2;c.stroke();
  for(let i=0;i<12;i++){const x=bb.x-16+r()*(bb.w+32),y=bb.y-16+r()*(bb.h+32);if(pip(x,y,poly))continue;c.fillStyle='rgba(26,38,104,0.85)';c.beginPath();c.arc(x,y,1.2+r()*2.6,0,TAU);c.fill();}
  c.strokeStyle='rgba(255,255,255,0.38)';c.lineWidth=3;
  for(let i=0,t=0;i<3&&t<40;t++){const x=bb.x+r()*bb.w,y=bb.y+r()*bb.h;if(!pip(x,y,poly)||!pip(x+16,y+16,poly)||!pip(x-16,y-16,poly))continue;i++;c.beginPath();c.arc(x,y,6+r()*10,Math.PI*1.05,Math.PI*1.5);c.stroke();}
}
function drawTape(c,r,bt){
  c.save();
  const zig=(x,y0,y1,dir)=>{const p=[];const n=8;for(let i=0;i<=n;i++)p.push([x+(i%2?dir*5:0)+(r()-0.5)*2,y0+(y1-y0)*i/n]);return p;};
  c.beginPath();c.moveTo(bt.x,bt.y);c.lineTo(bt.x+bt.w,bt.y);
  for(const p of zig(bt.x+bt.w,bt.y,bt.y+bt.h,-1))c.lineTo(p[0],p[1]);
  c.lineTo(bt.x,bt.y+bt.h);
  for(const p of zig(bt.x,bt.y+bt.h,bt.y,1))c.lineTo(p[0],p[1]);
  c.closePath();
  c.fillStyle='rgba(0,0,0,0.12)';c.save();c.translate(3,4);c.fill();c.restore();
  c.fillStyle='rgba(240,232,198,0.93)';c.fill();c.strokeStyle='rgba(140,128,90,0.7)';c.lineWidth=1.2;c.stroke();
  c.save();c.clip();c.strokeStyle='rgba(255,255,255,0.6)';c.lineWidth=6;for(let x=bt.x-30;x<bt.x+bt.w;x+=46){c.beginPath();c.moveTo(x,bt.y+bt.h);c.lineTo(x+28,bt.y);c.stroke();}c.restore();
  c.strokeStyle='rgba(150,135,90,0.5)';c.lineWidth=1;c.beginPath();c.moveTo(bt.x+6,bt.y+4);c.lineTo(bt.x+bt.w-6,bt.y+4);c.moveTo(bt.x+6,bt.y+bt.h-4);c.lineTo(bt.x+bt.w-6,bt.y+bt.h-4);c.stroke();
  c.restore();
}
function drawRamp(c,r,rp){
  const horiz=Math.abs(rp.dx)>0;const L=horiz?rp.w:rp.h,A=horiz?rp.h:rp.w;
  c.save();c.translate(rp.x+rp.w/2,rp.y+rp.h/2);c.rotate(Math.atan2(rp.dy,rp.dx));
  c.fillStyle='rgba(120,120,150,0.12)';c.fillRect(-L/2,-A/2,L,A);
  for(let k=0;k<=12;k++){const u=k/12;const x=-L/2+u*L;pen(c,r,[[x,-A/2+4],[x,A/2-4]],false,'rgba(70,70,95,'+(0.08+0.5*u).toFixed(2)+')',1.6,0.8);}
  pen(c,r,rect(-L/2,-A/2,L,A),true,'rgba(60,60,80,0.6)',1.5,1);
  const hx=L/2-6;
  const sp=[[hx-16,-A/2+8],[hx,-A/2+8],[hx,A/2-8],[hx-16,A/2-8]];
  c.strokeStyle='rgba(0,0,0,0.18)';c.lineWidth=6;c.beginPath();sp.forEach((p,i)=>i?c.lineTo(p[0]+2,p[1]+3):c.moveTo(p[0]+2,p[1]+3));c.stroke();
  c.strokeStyle='#7d8693';c.lineWidth=5;c.beginPath();sp.forEach((p,i)=>i?c.lineTo(p[0],p[1]):c.moveTo(p[0],p[1]));c.stroke();
  c.strokeStyle='#e6eaef';c.lineWidth=1.6;c.beginPath();sp.forEach((p,i)=>i?c.lineTo(p[0]-1,p[1]):c.moveTo(p[0]-1,p[1]));c.stroke();
  for(const x of [-L/4,0]){pen(c,r,[[x-6,-12],[x+6,0],[x-6,12]],false,INK,2,0.4);}
  c.restore();
}
function drawEraser(c,r,e){
  c.save();
  c.fillStyle='rgba(0,0,0,0.13)';rr(c,e.x+4,e.y+5,e.w,e.h,9);c.fill();
  c.fillStyle='#f5a3b5';rr(c,e.x,e.y,e.w,e.h,9);c.fill();
  c.save();rr(c,e.x,e.y,e.w,e.h,9);c.clip();c.fillStyle='rgba(60,110,210,0.88)';c.fillRect(e.x+e.w*0.52,e.y,e.w*0.48,e.h);
  c.strokeStyle='rgba(255,255,255,0.75)';c.lineWidth=2;for(let k=1;k<4;k++){const yy=e.y+e.h*k/4;c.beginPath();c.moveTo(e.x+e.w*0.52+5,yy);c.lineTo(e.x+e.w-5,yy);c.stroke();}
  c.fillStyle='rgba(255,255,255,0.3)';c.fillRect(e.x+4,e.y+4,e.w*0.45,6);c.restore();
  pen(c,r,rect(e.x,e.y,e.w,e.h),true,'#8c2f49',2,1.1);
  c.fillStyle='rgba(205,110,135,0.75)';for(let i=0;i<8;i++){c.beginPath();c.arc(e.x-6-r()*18,e.y+r()*e.h,1+r()*1.8,0,TAU);c.fill();}
  c.strokeStyle='rgba(90,90,100,0.25)';c.lineWidth=5;for(let i=0;i<3;i++){c.beginPath();const yy=e.y+12+i*26;c.moveTo(e.x-60,yy);c.quadraticCurveTo(e.x-40,yy-8,e.x-14,yy+3);c.stroke();}
  c.restore();
}
function drawClip(c,cl){
  const ax=cl.a[0],ay=cl.a[1],bx=cl.b[0],by=cl.b[1];const L=Math.hypot(bx-ax,by-ay),ang=Math.atan2(by-ay,bx-ax);
  const P=[];const arcp=(cx,cy,rad,a0,a1,n)=>{for(let i=0;i<=n;i++){const a=a0+(a1-a0)*i/n;P.push([cx+Math.cos(a)*rad,cy+Math.sin(a)*rad]);}};
  P.push([L*0.72,-11]);P.push([0,-11]);arcp(0,0,11,-Math.PI/2,-Math.PI*1.5,12);
  P.push([L+1,11]);arcp(L+1,2,9,Math.PI/2,-Math.PI/2,12);
  P.push([8,-7]);arcp(8,0,7,-Math.PI/2,-Math.PI*1.5,8);P.push([L*0.55,7]);
  c.save();c.translate(ax,ay);c.rotate(ang);c.lineJoin='round';c.lineCap='round';
  const line=(col,lw,ox,oy)=>{c.strokeStyle=col;c.lineWidth=lw;c.beginPath();P.forEach((p,i)=>i?c.lineTo(p[0]+ox,p[1]+oy):c.moveTo(p[0]+ox,p[1]+oy));c.stroke();};
  line('rgba(0,0,0,0.16)',4,2,3);line('#5f6874',3.6,0,0);line('#dfe4ea',1.3,-0.6,-0.6);
  c.restore();
}
function drawBand(c,r,H){
  const B=H.band;
  c.fillStyle='rgba(120,120,150,0.13)';c.fillRect(B.x,B.y,B.w,B.h);
  c.setLineDash([6,7]);c.strokeStyle='rgba(60,60,90,0.4)';c.lineWidth=2;
  for(const T of H.tunnels){c.beginPath();for(let i=0;i<=24;i++){const p=bez(T.a,T.b,i/24);i?c.lineTo(p[0],p[1]):c.moveTo(p[0],p[1]);}c.stroke();}
  c.setLineDash([]);
  for(let y=B.y+20;y<B.y+B.h;y+=34){
    c.fillStyle='#e7e1cf';c.beginPath();c.arc(B.x+B.w/2,y,7,0,TAU);c.fill();c.strokeStyle='rgba(0,0,0,0.25)';c.lineWidth=1;c.stroke();
    c.strokeStyle='rgba(0,0,0,0.2)';c.lineWidth=4;c.beginPath();c.ellipse(B.x+B.w/2+2,y+3,B.w/2+10,8,-0.15,Math.PI*0.95,Math.PI*2.05);c.stroke();
    c.strokeStyle='#454b58';c.lineWidth=3.2;c.beginPath();c.ellipse(B.x+B.w/2,y,B.w/2+10,8,-0.15,Math.PI*0.95,Math.PI*2.05);c.stroke();
    c.strokeStyle='#c3c7d0';c.lineWidth=1;c.beginPath();c.ellipse(B.x+B.w/2,y-1,B.w/2+9,7,-0.15,Math.PI*1.1,Math.PI*1.7);c.stroke();
  }
  for(const T of H.tunnels){for(const [p,d] of [[T.a,T.ad],[T.b,T.bd]]){
    const fx=p[0]-d[0]*11,fy=p[1]-d[1]*11;c.save();c.translate(fx,fy);c.rotate(Math.atan2(d[1],d[0]));
    c.fillStyle='#141826';c.beginPath();c.ellipse(0,0,9,21,0,-Math.PI/2,Math.PI/2);c.fill();
    c.strokeStyle=INK;c.lineWidth=2.4;c.beginPath();c.ellipse(0,0,12,24,0,-Math.PI/2,Math.PI/2);c.stroke();
    c.restore();
    arrow(c,r,p[0]+d[0]*30,p[1]+d[1]*30,Math.atan2(-d[1],-d[0]),20,'rgba(31,63,154,0.55)',1.6);
  }}
}
function drawCourse(c,H,idx){
  const r=mulberry32(4242+idx*101);
  c.lineCap='round';c.lineJoin='round';
  doodles(c,r,H);
  c.save();c.translate(4,5);c.fillStyle='rgba(60,60,90,0.08)';pathPoly(c,H.bounds);c.fill();c.restore();
  c.save();pathPoly(c,H.bounds);c.fillStyle='rgba(255,255,250,0.55)';c.fill();c.clip();
  const bb=bbox(H.bounds);
  c.globalCompositeOperation='multiply';
  hatch(c,r,bb,-0.42,15,'rgba(150,228,120,0.30)',14);
  for(const s of H.slopes){c.save();c.beginPath();c.rect(s.x,s.y,s.w,s.h);c.clip();hatch(c,r,s,0.75,8,'rgba(255,180,50,0.30)',8);c.restore();}
  c.globalCompositeOperation='source-over';
  for(const s of H.slopes){const a=Math.atan2(s.ay,s.ax);for(let x=s.x+40;x<s.x+s.w-20;x+=70)for(let y=s.y+40;y<s.y+s.h-20;y+=72)arrow(c,r,x+(r()-0.5)*8,y+(r()-0.5)*8,a,26,'rgba(185,105,0,0.8)',2);pen(c,r,rect(s.x,s.y,s.w,s.h),true,'rgba(210,140,20,0.55)',1.4,1.5);}
  for(const w of H.waters)drawInk(c,r,w);
  for(const bt of H.bridges)drawTape(c,r,bt);
  for(const rp of H.ramps)drawRamp(c,r,rp);
  if(H.band)drawBand(c,r,H);
  for(const e of H.erasers)drawEraser(c,r,e);
  c.restore();
  for(const cl of H.clips)drawClip(c,cl);
  for(const ru of H.rulers){c.save();c.setLineDash([4,6]);c.strokeStyle='rgba(130,95,20,0.4)';c.lineWidth=1.4;
    if(ru.axis==='y')c.strokeRect(ru.cx-ru.w/2-4,ru.cy-ru.amp-ru.h/2-4,ru.w+8,2*ru.amp+ru.h+8);else c.strokeRect(ru.cx-ru.amp-ru.w/2-4,ru.cy-ru.h/2-4,2*ru.amp+ru.w+8,ru.h+8);c.restore();}
  for(const w of H.walls){c.save();c.translate(2,3);pen(c,r,[[w[0],w[1]],[w[2],w[3]]],false,'rgba(0,0,0,0.12)',4,1);c.restore();pen(c,r,[[w[0],w[1]],[w[2],w[3]]],false,INK,3.4,1.4);}
  pen(c,r,H.bounds,true,INK,2.8,1.6);
  const tx=H.tee[0],ty=H.tee[1];
  c.save();c.globalCompositeOperation='multiply';c.fillStyle='rgba(120,215,95,0.45)';c.fillRect(tx-17,ty-17,34,34);c.restore();
  pen(c,r,rect(tx-17,ty-17,34,34),true,'#2f7a3a',1.5,1);
  const cx=H.cup[0],cy=H.cup[1];
  penCircle(c,r,cx,cy,CUPR+10,'rgba(31,63,154,0.35)',1.2,1.5);
  c.fillStyle='#161a2c';c.beginPath();c.arc(cx,cy,CUPR,0,TAU);c.fill();
  c.strokeStyle='rgba(255,255,255,0.12)';c.lineWidth=1;c.save();c.beginPath();c.arc(cx,cy,CUPR,0,TAU);c.clip();for(let k=-CUPR;k<CUPR;k+=4){c.beginPath();c.moveTo(cx+k,cy-CUPR);c.lineTo(cx+k+10,cy+CUPR);c.stroke();}c.restore();
  penCircle(c,r,cx,cy,CUPR+1.5,'#111',2,1);
}

/* ---------- audio ---------- */
let AC=null,master=null,muted=false,nbuf=null;const lastSnd={};
try{muted=localStorage.getItem('nbmg-muted')==='1';}catch(e){}
function initAudio(){
  if(!AC){try{const A=window.AudioContext||window.webkitAudioContext;if(!A)return;AC=new A();master=AC.createGain();master.gain.value=muted?0:0.55;master.connect(AC.destination);
    nbuf=AC.createBuffer(1,AC.sampleRate,AC.sampleRate);const d=nbuf.getChannelData(0);const nr=mulberry32(5);for(let i=0;i<d.length;i++)d[i]=nr()*2-1;}catch(e){AC=null;return;}}
  if(AC.state==='suspended'){try{AC.resume();}catch(e){}}
}
function tone(f,d,type,vol,f2,delay){if(!AC||muted)return;const t0=AC.currentTime+(delay||0);const o=AC.createOscillator(),g=AC.createGain();o.type=type||'sine';o.frequency.setValueAtTime(f,t0);if(f2)o.frequency.exponentialRampToValueAtTime(f2,t0+d);g.gain.setValueAtTime(0.0001,t0);g.gain.exponentialRampToValueAtTime(Math.max(0.0002,vol),t0+0.008);g.gain.exponentialRampToValueAtTime(0.0001,t0+d);o.connect(g);g.connect(master);o.start(t0);o.stop(t0+d+0.05);}
function noise(d,vol,f1,f2,type,delay){if(!AC||muted||!nbuf)return;const t0=AC.currentTime+(delay||0);const s=AC.createBufferSource();s.buffer=nbuf;const fl=AC.createBiquadFilter();fl.type=type||'lowpass';fl.frequency.setValueAtTime(f1,t0);if(f2)fl.frequency.exponentialRampToValueAtTime(f2,t0+d);const g=AC.createGain();g.gain.setValueAtTime(0.0001,t0);g.gain.exponentialRampToValueAtTime(Math.max(0.0002,vol),t0+0.01);g.gain.exponentialRampToValueAtTime(0.0001,t0+d);s.connect(fl);fl.connect(g);g.connect(master);s.start(t0,arng()*0.4);s.stop(t0+d+0.05);}
function sfx(n,v){
  if(!AC||muted)return;const now=AC.currentTime;if(lastSnd[n]&&now-lastSnd[n]<0.05)return;lastSnd[n]=now;const k=clamp((v||0)/700,0.05,1);
  switch(n){
    case 'putt':tone(190,0.09,'triangle',0.3*k+0.1,90);noise(0.05,0.2*k+0.05,3000,800,'bandpass');break;
    case 'wall':tone(250,0.07,'triangle',0.28*k,150);noise(0.03,0.12*k,2000,500);break;
    case 'clip':tone(520,0.25,'sine',0.25,1100);tone(780,0.16,'square',0.04,1500,0.02);break;
    case 'eraser':tone(110,0.13,'sine',0.35*k+0.05,70);break;
    case 'ruler':tone(620,0.05,'square',0.07);tone(300,0.08,'triangle',0.2*k+0.05,200);break;
    case 'jump':tone(300,0.3,'triangle',0.2,900);break;
    case 'land':tone(160,0.08,'triangle',0.18,100);break;
    case 'tunnel':noise(0.5,0.25,400,2500,'bandpass');break;
    case 'tunout':tone(500,0.1,'sine',0.2,900);break;
    case 'lip':tone(900,0.06,'triangle',0.2);tone(700,0.06,'triangle',0.2,null,0.07);tone(820,0.08,'triangle',0.15,null,0.14);break;
    case 'splash':noise(0.6,0.4,1800,250,'lowpass');tone(200,0.3,'sine',0.15,60);break;
    case 'cup':tone(1300,0.08,'triangle',0.22);tone(900,0.1,'triangle',0.2,null,0.06);noise(0.15,0.15,1500,600,'bandpass',0.02);tone(140,0.15,'sine',0.3,80,0.1);break;
    case 'cheer':[523,659,784,1047].forEach((f,i)=>tone(f,0.22,'triangle',0.17,null,0.18+i*0.09));break;
    case 'ace':[523,659,784,1047,1319,1568].forEach((f,i)=>tone(f,0.3,'triangle',0.17,null,0.18+i*0.08));break;
    case 'sad':tone(400,0.25,'triangle',0.14,300);tone(300,0.35,'triangle',0.14,200,0.22);break;
    case 'ui':tone(700,0.05,'sine',0.12);break;
  }
}
function setMuted(m){muted=m;if(master)master.gain.value=m?0:0.55;$('bSnd').innerHTML=m?'&#9834; off':'&#9834; on';try{localStorage.setItem('nbmg-muted',m?'1':'0');}catch(e){}}

/* ---------- notes ---------- */
const NOTES={
 ACE:['HOLE IN ONE!! framing this page.','ACE! no eraser needed.','one stroke?! teacher\'s pet.'],
 LONG:['from DOWNTOWN!','long-distance call... answered!','did you measure that with a ruler?'],
 BANK:['bank shot! geometry homework paid off.','off the wall and IN. smooth.','calculated. (probably.)'],
 EAGLE:['eagle! show-off.','two under. gold star!'],
 BIRDIE:['birdie! gold star.','under par, nice wrist.','tweet tweet, birdie.'],
 PAR:['par. a solid B+.','par. neat and tidy.','right on schedule.'],
 BOGEY:['bogey. we move on.','+1, the paper forgives you.'],
 WORSE:['...maybe erase this one.','let\'s never speak of this hole.','this page needs correction fluid.'],
 WATER:['glub glub.','that ink was NOT a pond.','swim lessons?','splash! the ink wins.'],
 LIP:['lipped out!! rude.','the cup spat it out!','sooo close. too fast!'],
 TAP:['tap... tap... more oomph?','a breeze would have moved it more.'],
 PINBALL:['pinball wizard!','ricochet city!'],
 CLOSE:['tap-in left. breathe.','almost! knock it in.'],
 WRONG:['wrong way, champ.','the cup is THAT way →']
};
const noteEl=$('note');let noteTimer=0;
function note(txt,mood){noteEl.textContent=txt;noteEl.className='';void noteEl.offsetWidth;noteEl.className='show '+(mood||'');clearTimeout(noteTimer);noteTimer=setTimeout(()=>{noteEl.className=mood||'';},3400);}

/* ---------- particles ---------- */
function addP(p){if(parts.length<240)parts.push(p);}
function celebrate(x,y,label,big){
  const cols=[RED,INK,'#d09a00','#d8408c','#2f8a44'];
  const n=big?22:14;
  for(let i=0;i<n;i++){const a=i/n*TAU+rng()*0.25;addP({k:'ray',x,y,a,life:0,max:0.7+rng()*0.4,col:pick(cols),l:16+rng()*24});}
  for(let i=0;i<(big?16:8);i++){const a=rng()*TAU,s=70+rng()*170;addP({k:'star',x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s,rot:rng()*TAU,vr:(rng()-0.5)*6,life:0,max:1.2+rng()*0.6,col:pick(cols),sz:5+rng()*6,hl:pick(['rgba(255,225,60,0.75)','rgba(255,120,190,0.6)','rgba(140,230,110,0.65)'])});}
  for(let i=0;i<(big?6:3);i++){const a=rng()*TAU;addP({k:'spiral',x:x+Math.cos(a)*55,y:y+Math.sin(a)*55,life:0,max:1.4,col:pick(cols),rot:rng()*TAU});}
  addP({k:'text',x,y,txt:label,life:0,max:big?2.4:1.8,col:RED,sz:big?34:26});
}
function splashFx(x,y){for(let i=0;i<3;i++)addP({k:'ring',x,y,life:-i*0.15,max:0.9});for(let i=0;i<12;i++){const a=rng()*TAU,s=60+rng()*130;addP({k:'drop',x,y,vx:Math.cos(a)*s,vy:Math.sin(a)*s,life:0,max:0.6+rng()*0.3,sz:2+rng()*3});}addP({k:'text',x,y,txt:'SPLOOSH',life:0,max:1.3,col:'#1c2a6b',sz:22});}
function word(x,y,txt,col){const now=performance.now();if(now-lastWord<350)return;lastWord=now;addP({k:'text',x,y,txt,life:0,max:0.9,col:col||INK,sz:16,small:true});}
function updParts(dt){for(const p of parts){p.life+=dt;if(p.vx!=null){p.x+=p.vx*dt;p.y+=p.vy*dt;const f=Math.max(0,1-2.2*dt);p.vx*=f;p.vy*=f;}if(p.vr)p.rot+=p.vr*dt;}parts=parts.filter(p=>p.life<p.max);}

/* ---------- game flow ---------- */
function setState(s){G.state=s;G.stateT=0;}
function relStr(n){return n===0?'E':(n>0?'+'+n:''+n);}
function updateHUD(){
  const H=G.H;$('l1').textContent='Hole '+(G.hi+1)+'/9 · Par '+H.par;
  let tot=0,par=0;for(let i=0;i<9;i++)if(G.scores[i]!=null){tot+=G.scores[i];par+=HOLES[i].par;}
  $('l2').textContent='Strokes '+G.strokes+' · Total '+relStr(tot-par);
}
function banner(i){const H=HOLES[i];const el=$('banner');el.querySelector('.t').textContent='Hole '+(i+1)+': '+H.name;el.querySelector('.s').textContent='Par '+H.par+' · '+H.idea;el.classList.remove('show');void el.offsetWidth;el.classList.add('show');}
function loadHole(i){
  G.hi=i;G.H=HOLES[i];G.ball=newBall(G.H.tee[0],G.H.tee[1]);G.strokes=0;G.step=0;G.aim=null;G.trail=[];
  G.lastShot={x:G.H.tee[0],y:G.H.tee[1]};G.shot=null;G.prevX=null;parts=[];G.scores[i]=null;
  setState('aim');renderStatic();updateHUD();banner(i);
}
function newGame(){G.scores=new Array(9).fill(null);$('over').hidden=true;loadHole(0);}
function nextHole(){if(G.hi<8)loadHole(G.hi+1);else showScorecard();}
function scoreName(s,par){if(s===1)return'HOLE IN ONE!';const d=s-par;return d<=-3?'ALBATROSS!':d===-2?'EAGLE!':d===-1?'BIRDIE!':d===0?'PAR':d===1?'BOGEY':d===2?'DOUBLE BOGEY':'+'+d;}
function shoot(a,p){
  const b=G.ball;G.strokes++;G.lastShot={x:b.x,y:b.y};
  G.shot={x0:b.x,y0:b.y,d0:Math.hypot(b.x-G.H.cup[0],b.y-G.H.cup[1]),p};
  launch(b,a,p);G.trail=[[b.x,b.y]];setState('roll');sfx('putt',p*MAXV);updateHUD();
}
function onEv(n,v){
  const b=G.ball;
  switch(n){
    case 'wall':sfx('wall',v);break;
    case 'clip':sfx('clip',v);if(v>120)word(b.x,b.y,'boing!',INK);break;
    case 'eraser':sfx('eraser',v);if(v>150)word(b.x,b.y,'thup','#8c2f49');break;
    case 'ruler':sfx('ruler',v);if(v>120)word(b.x,b.y,'clack!','#7a5a12');break;
    case 'jump':sfx('jump',v);word(b.x,b.y,'whee!',RED);break;
    case 'land':sfx('land',v);break;
    case 'tunnel':sfx('tunnel',v);word(b.x,b.y,'whoosh',INK);break;
    case 'tunout':sfx('tunout',v);lastWord=0;word(b.x,b.y,'pop!',RED);break;
    case 'lip':sfx('lip',v);lastWord=0;word(b.x,b.y,'rattle!',RED);if(!demo)note(pick(NOTES.LIP),'bad');break;
    case 'splash':sfx('splash',v);break;
  }
}
function sunkNote(){
  const H=G.H,diff=G.strokes-H.par,s=G.shot,b=G.ball;let txt,mood='good';
  if(G.strokes===1)txt=pick(NOTES.ACE);
  else if(s&&s.d0>380)txt=pick(NOTES.LONG);
  else if(b.bounces>=2)txt=pick(NOTES.BANK);
  else if(b.lipped)txt='rattled around... and IN!';
  else if(diff<=-2)txt=pick(NOTES.EAGLE);else if(diff===-1)txt=pick(NOTES.BIRDIE);else if(diff===0){txt=pick(NOTES.PAR);mood='meh';}
  else if(diff===1){txt=pick(NOTES.BOGEY);mood='meh';}else{txt=pick(NOTES.WORSE);mood='bad';}
  note(txt,mood);
}
function stopNote(){
  const s=G.shot,b=G.ball,H=G.H;if(!s||b.lipped)return;
  const d=Math.hypot(b.x-H.cup[0],b.y-H.cup[1]),moved=Math.hypot(b.x-s.x0,b.y-s.y0);
  if(moved<25)note(pick(NOTES.TAP),'bad');
  else if(b.bounces>=5)note(pick(NOTES.PINBALL),'good');
  else if(d<35)note(pick(NOTES.CLOSE),'good');
  else if(d>s.d0+150)note(pick(NOTES.WRONG),'bad');
}
function ballDone(kind){
  const b=G.ball,H=G.H;
  if(kind==='sunk'){
    G.scores[G.hi]=G.strokes;setState('sunk');
    const big=G.strokes===1;celebrate(H.cup[0],H.cup[1],scoreName(G.strokes,H.par),big);
    sfx('cup');sfx(big?'ace':(G.strokes<=H.par?'cheer':'cup'));
    if(!demo)sunkNote();updateHUD();
  }else if(kind==='water'){
    G.strokes++;setState('splash');splashFx(b.x,b.y);b.hidden=true;if(!demo)note(pick(NOTES.WATER)+' (+1)','bad');updateHUD();
  }else{
    if(G.strokes>=MAXSTROKES){G.scores[G.hi]=MAXSTROKES;setState('pickup');note('10 strokes. pick it up, new page!','bad');sfx('sad');updateHUD();return;}
    setState('aim');if(!demo)stopNote();
  }
}
function fixedStep(){
  G.step++;G.stateT+=DT;
  const t=G.step*DT;
  if(demo)demoStep();
  if(G.state==='roll'){
    const b=G.ball;stepBall(b,G.H,t,DT,onEv);
    if(!b.hidden&&(G.step&3)===0){G.trail.push([b.x,b.y]);if(G.trail.length>70)G.trail.shift();}
    if(b.done)ballDone(b.done);
  }else if(G.state==='splash'){
    if(G.stateT>1.0){
      if(G.strokes>=MAXSTROKES){G.scores[G.hi]=MAXSTROKES;setState('pickup');note('10 strokes. pick it up, new page!','bad');updateHUD();}
      else{G.ball=newBall(G.lastShot.x,G.lastShot.y);G.prevX=null;setState('aim');}
    }
  }else if(G.state==='sunk'||G.state==='pickup'){
    if(!demo&&G.stateT>(G.state==='sunk'?2.6:1.8))nextHole();
  }
}
function showScorecard(){
  setState('over');
  let tot=0,par=0;
  let h='<tr><th class="lab">Hole</th>';for(let i=0;i<9;i++)h+='<th>'+(i+1)+'</th>';h+='<th>Tot</th></tr>';
  h+='<tr><td class="lab">Par</td>';for(let i=0;i<9;i++){h+='<td>'+HOLES[i].par+'</td>';par+=HOLES[i].par;}h+='<td>'+par+'</td></tr>';
  h+='<tr><td class="lab">You</td>';for(let i=0;i<9;i++){const s=G.scores[i]==null?MAXSTROKES:G.scores[i];tot+=s;const cls=s<HOLES[i].par?'under':s>HOLES[i].par?'overp':'';h+='<td>'+(cls?'<span class="'+cls+'">'+s+'</span>':s)+'</td>';}h+='<td><b>'+tot+'</b></td></tr>';
  $('tbl').innerHTML=h;
  const d=tot-par;
  $('verdict').textContent=(d<=-3?'Ace student! ':d<0?'Under par. Gold star! ':d===0?'Even par. Very respectable. ':d<=5?'Not bad for notebook golf. ':'Plenty of doodling practice. ')+'('+relStr(d)+')';
  let best=null;try{best=parseInt(localStorage.getItem('nbmg-best'),10);if(isNaN(best))best=null;if(best==null||tot<best){localStorage.setItem('nbmg-best',String(tot));}}catch(e){}
  $('best').textContent=best==null?'First round on this page!':(tot<best?'New best! (old best '+best+')':'Best so far: '+best);
  $('over').hidden=false;sfx(d<=0?'ace':'cheer');
  try{$('bAgain').focus({preventScroll:true});}catch(e){}
}

/* ---------- aiming ---------- */
function aimInfo(){
  const A=G.aim;if(!A)return null;let px,py;
  if(A.mode==='ball'){px=G.ball.x-A.cx;py=G.ball.y-A.cy;}else{px=A.sx-A.cx;py=A.sy-A.cy;}
  const L=Math.hypot(px,py);if(L<0.001)return{ang:0,power:0,dx:1,dy:0,L:0};
  return{ang:Math.atan2(py,px),power:Math.min(1,L*scale/maxDrag),dx:px/L,dy:py/L,L:Math.min(L,maxDrag/scale)};
}
cv.addEventListener('pointerdown',e=>{
  if(performance.now()-demoStopT<120)return;
  initAudio();
  if(G.state!=='aim'||!$('over').hidden)return;
  const p=toWorld(e.clientX,e.clientY);const d=Math.hypot(p.x-G.ball.x,p.y-G.ball.y);
  G.aim={id:e.pointerId,mode:d*scale<70?'ball':'free',sx:p.x,sy:p.y,cx:p.x,cy:p.y};
  try{cv.setPointerCapture(e.pointerId);}catch(_){}
  e.preventDefault();
});
cv.addEventListener('pointermove',e=>{if(G.aim&&e.pointerId===G.aim.id){const p=toWorld(e.clientX,e.clientY);G.aim.cx=p.x;G.aim.cy=p.y;e.preventDefault();}});
cv.addEventListener('pointerup',e=>{if(G.aim&&e.pointerId===G.aim.id){const p=toWorld(e.clientX,e.clientY);G.aim.cx=p.x;G.aim.cy=p.y;const a=aimInfo();G.aim=null;if(a&&a.power>=0.04&&G.state==='aim')shoot(a.ang,a.power);}});
cv.addEventListener('pointercancel',e=>{if(G.aim&&e.pointerId===G.aim.id)G.aim=null;});
cv.addEventListener('contextmenu',e=>e.preventDefault());

/* ---------- buttons & keys ---------- */
function retryHole(){if(G.state==='over')return;sfx('ui');loadHole(G.hi);}
function restart(){sfx('ui');newGame();}
$('bSnd').addEventListener('click',()=>{initAudio();setMuted(!muted);sfx('ui');});
$('bRetry').addEventListener('click',retryHole);
$('bRestart').addEventListener('click',restart);
$('bAgain').addEventListener('click',()=>{initAudio();restart();});
window.addEventListener('pointerdown',e=>{if(demo&&e.isTrusted)stopDemo();},true);
window.addEventListener('keydown',e=>{
  if(demo&&e.isTrusted){stopDemo();return;}
  initAudio();
  const k=e.key.toLowerCase();
  if(k==='m'){setMuted(!muted);}
  else if(k==='r'){retryHole();}
  else if(k==='enter'&&G.state==='over'){e.preventDefault();restart();}
});

/* ---------- demo mode ---------- */
const DEMO=[{h:0,goal:'sink'},{h:2,goal:'sink'},{h:3,goal:'water'},{h:5,goal:'sink'},{h:6,goal:'sink'},{h:7,goal:'sink'}];
function* searchShot(H,b0,startStep){
  let best={a:0,p:0.6},bs=-Infinity,cnt=0;
  const ev=(a,p)=>{const b=Object.assign({},b0);launch(b,a,p);let k=startStep;while(!b.done&&b.time<7){stepBall(b,H,k*DT,DT,null);k++;}
    const d=Math.hypot(b.x-H.cup[0],b.y-H.cup[1]);
    const s=b.done==='sunk'?10000-b.time*300:b.done==='water'?-5000-d:-d-b.time*3;
    if(s>bs){bs=s;best={a,p};}};
  for(let j=0;j<8;j++)for(let i=0;i<80;i++){ev(i/80*TAU,0.3+j*0.1);if(++cnt%10===0)yield;}
  const c0=best;for(let i=-4;i<=4;i++)for(let j=-3;j<=3;j++){ev(c0.a+i*0.01,clamp(c0.p+j*0.03,0.08,1));if(++cnt%10===0)yield;}
  return best;
}
function startDemo(){demo={i:0,phase:'load',t:0,ptr:{x:FIT.x+FIT.w*0.5,y:FIT.y+FIT.h,down:false},plan:null,gen:null,from:null,relStep:0};G.scores=new Array(9).fill(null);$('demoTag').classList.add('show');}
function stopDemo(){if(!demo)return;demo=null;demoStopT=performance.now();$('demoTag').classList.remove('show');G.aim=null;newGame();note('your turn! drag back from the ball, let go to putt','good');}
function demoStep(){
  const D=demo;D.t+=DT;const shot=DEMO[D.i%DEMO.length];
  if(D.phase==='load'){
    loadHole(shot.h);D.phase='approach';D.t=0;D.from={x:D.ptr.x,y:D.ptr.y};D.relStep=G.step+Math.round(1.35*120);D.plan=null;D.gen=null;
    if(shot.goal==='water'){const b=G.ball,cu=G.H.cup;D.plan={a:Math.atan2(cu[1]-b.y,cu[0]-b.x),p:0.55};}
    else D.gen=searchShot(G.H,G.ball,D.relStep);
    return;
  }
  if(D.gen){const r=D.gen.next();if(r.done){D.plan=r.value;D.gen=null;}}
  const b=G.ball;
  if(D.phase==='approach'){
    const k=ease(Math.min(1,D.t/0.6));D.ptr.x=D.from.x+(b.x-D.from.x)*k;D.ptr.y=D.from.y+(b.y-D.from.y)*k;
    if(D.t>=0.6){while(!D.plan&&D.gen){const r=D.gen.next();if(r.done){D.plan=r.value;D.gen=null;}}
      D.phase='drag';D.t=0;D.ptr.down=true;G.aim={id:-1,mode:'ball',sx:b.x,sy:b.y,cx:b.x,cy:b.y};}
  }else if(D.phase==='drag'){
    const pl=D.plan;const lenW=pl.p*maxDrag/scale;const k=ease(Math.min(1,D.t/0.65));
    if(!G.aim)G.aim={id:-1,mode:'ball',sx:b.x,sy:b.y,cx:b.x,cy:b.y};
    G.aim.cx=b.x-Math.cos(pl.a)*lenW*k;G.aim.cy=b.y-Math.sin(pl.a)*lenW*k;D.ptr.x=G.aim.cx;D.ptr.y=G.aim.cy;
    if(G.step>=D.relStep){G.aim=null;D.ptr.down=false;shoot(pl.a,pl.p);D.phase='roll';D.t=0;D.from={x:D.ptr.x,y:D.ptr.y};}
  }else if(D.phase==='roll'){
    const k=ease(Math.min(1,D.t/0.8));D.ptr.x=D.from.x+(-40)*k;D.ptr.y=D.from.y+60*k;
    if(G.state!=='roll'&&G.state!=='splash'){D.phase='post';D.t=0;}
    else if(D.t>4){D.phase='post';D.t=0;}
  }else if(D.phase==='post'){
    if(D.t>(G.state==='sunk'?1.3:0.6)){D.i=(D.i+1)%DEMO.length;D.phase='load';}
  }
}

/* ---------- rendering ---------- */
function drawRuler(c,ru,t){
  const q=rulerState(ru,t);c.save();
  c.fillStyle='rgba(0,0,0,0.13)';c.fillRect(q.x+3,q.y+4,q.w,q.h);
  c.fillStyle='#f4d46a';c.strokeStyle='#7a5a12';c.lineWidth=2;c.beginPath();c.rect(q.x,q.y,q.w,q.h);c.fill();c.stroke();
  c.strokeStyle='#5a4310';c.lineWidth=1.1;c.beginPath();
  if(ru.axis==='y'){let k=0;for(let yy=q.y+5;yy<q.y+q.h-3;yy+=7.5,k++){c.moveTo(q.x,yy);c.lineTo(q.x+(k%4===0?12:6),yy);}}
  else{let k=0;for(let xx=q.x+5;xx<q.x+q.w-3;xx+=7.5,k++){c.moveTo(xx,q.y);c.lineTo(xx,q.y+(k%4===0?12:6));}}
  c.stroke();c.fillStyle='rgba(255,255,255,0.4)';if(ru.axis==='y')c.fillRect(q.x+q.w-7,q.y+3,3,q.h-6);else c.fillRect(q.x+3,q.y+q.h-7,q.w-6,3);
  c.restore();
}
function drawFlag(c,H,tm){const x=H.cup[0],y=H.cup[1];c.strokeStyle='rgba(0,0,0,0.15)';c.lineWidth=2.4;c.beginPath();c.moveTo(x+2,y+2);c.lineTo(x+14,y-44);c.stroke();
  c.strokeStyle='#222';c.lineWidth=2.2;c.beginPath();c.moveTo(x,y);c.lineTo(x+3,y-52);c.stroke();const w=Math.sin(tm*4)*3;
  c.fillStyle='rgba(235,50,70,0.75)';c.strokeStyle='#9a1f2c';c.lineWidth=1.6;c.beginPath();c.moveTo(x+3,y-52);c.quadraticCurveTo(x+18,y-50+w,x+32,y-45+w*0.6);c.quadraticCurveTo(x+18,y-40-w*0.5,x+3,y-36);c.closePath();c.fill();c.stroke();}
function drawBall(c,b,sc,ox,oy){
  const z=b.z||0;const x=ox,y=oy;const rad=R*(1+z/90)*sc;const sh=1-Math.min(0.4,z/250);
  c.fillStyle='rgba(30,30,50,0.2)';c.beginPath();c.ellipse(x+2+z*0.4,y+3+z*0.6,R*sc*sh,R*sc*0.8*sh,0,0,TAU);c.fill();
  c.fillStyle='#fff';c.beginPath();c.arc(x,y,rad,0,TAU);c.fill();
  c.strokeStyle='rgba(31,63,154,0.22)';c.lineWidth=2.5;c.beginPath();c.arc(x,y,Math.max(0.5,rad-2.2),0.2,1.7);c.stroke();
  const dx=Math.cos(G.dir),dy=Math.sin(G.dir);c.fillStyle='rgba(40,50,90,0.45)';
  for(const k of [0,2.1,4.2]){const ph=G.spin+k;if(Math.cos(ph)<0)continue;const o=Math.sin(ph)*rad*0.6;const side=(k-2.1)*0.18*rad;c.beginPath();c.arc(x+dx*o-dy*side,y+dy*o+dx*side,1.1*sc,0,TAU);c.fill();}
  c.strokeStyle='#1b2650';c.lineWidth=1.8;c.beginPath();c.arc(x,y,rad,0,TAU);c.stroke();
}
function render(now){
  const c=ctx;c.setTransform(1,0,0,1,0,0);c.globalAlpha=1;c.drawImage(st,0,0);
  if(!G.H)return;
  setWorld(c);c.lineCap='round';c.lineJoin='round';
  const H=G.H,t=G.step*DT,tm=now/1000,b=G.ball;
  for(const ru of H.rulers)drawRuler(c,ru,t);
  if(G.trail.length>1){c.fillStyle='rgba(60,60,90,1)';for(let i=0;i<G.trail.length;i++){const p=G.trail[i];c.globalAlpha=0.08+0.32*i/G.trail.length;c.beginPath();c.arc(p[0],p[1],1.7,0,TAU);c.fill();}c.globalAlpha=1;}
  drawFlag(c,H,tm);
  if(G.prevX!=null){const mv=Math.hypot(b.x-G.prevX,b.y-G.prevY);if(mv>0.01&&mv<60){G.spin+=mv/R;G.dir=Math.atan2(b.y-G.prevY,b.x-G.prevX);}}
  G.prevX=b.x;G.prevY=b.y;
  if(b.hidden&&b.tun>0&&b.tunT){const T=b.tunT;const u=1-b.tun/TUNT;const p=b.tunToB?bez(T.a,T.b,u):bez(T.b,T.a,u);c.setLineDash([3,3]);c.strokeStyle='rgba(31,63,154,0.7)';c.lineWidth=1.6;c.beginPath();c.arc(p[0],p[1],R,0,TAU);c.stroke();c.setLineDash([]);}
  if(G.state==='aim'&&!G.aim&&!demo){const pr=R+9+Math.sin(tm*4)*2.5;c.setLineDash([4,5]);c.strokeStyle='rgba(210,58,58,0.55)';c.lineWidth=1.6;c.beginPath();c.arc(b.x,b.y,pr,0,TAU);c.stroke();c.setLineDash([]);}
  if(G.state==='sunk'){
    const k=clamp(G.stateT/0.22,0,1);const sc=Math.max(0,1-k)*0.95;
    if(sc>0.02){c.save();c.beginPath();c.arc(H.cup[0],H.cup[1],CUPR+2,0,TAU);c.clip();drawBall(c,b,sc,b.sx+(H.cup[0]-b.sx)*k,b.sy+(H.cup[1]-b.sy)*k);c.restore();}
  }else if(!b.hidden&&G.state!=='pickup'){drawBall(c,b,1,b.x,b.y);}
  let ai=null;
  if(G.aim&&G.state==='aim'){ai=aimInfo();
    if(ai&&ai.power>0.01){
      const len=30+ai.power*260;
      c.strokeStyle='rgba(80,80,90,0.6)';c.lineWidth=1.6;c.setLineDash([5,5]);c.beginPath();c.moveTo(b.x,b.y);c.lineTo(b.x-ai.dx*ai.L,b.y-ai.dy*ai.L);c.stroke();c.setLineDash([]);
      c.strokeStyle='rgba(80,80,90,0.7)';c.beginPath();c.arc(b.x-ai.dx*ai.L,b.y-ai.dy*ai.L,6,0,TAU);c.stroke();
      c.fillStyle=ai.power>0.85?RED:INK;for(let d=R+7;d<len;d+=11){c.beginPath();c.arc(b.x+ai.dx*d,b.y+ai.dy*d,2.1,0,TAU);c.fill();}
      const ex=b.x+ai.dx*(len+4),ey=b.y+ai.dy*(len+4),h=10;c.strokeStyle=c.fillStyle;c.lineWidth=2.4;c.beginPath();c.moveTo(ex-ai.dx*h-ai.dy*h*0.6,ey-ai.dy*h+ai.dx*h*0.6);c.lineTo(ex,ey);c.lineTo(ex-ai.dx*h+ai.dy*h*0.6,ey-ai.dy*h-ai.dx*h*0.6);c.stroke();
    }
  }
  const cols=null;
  for(const p of parts){
    if(p.life<0||p.k==='text')continue;const e=clamp(p.life/p.max,0,1);
    if(p.k==='ray'){const r1=CUPR+4+e*34,r2=r1+p.l*(1-e*0.5);c.globalAlpha=1-e;c.strokeStyle=p.col;c.lineWidth=2.2;c.beginPath();c.moveTo(p.x+Math.cos(p.a)*r1,p.y+Math.sin(p.a)*r1);c.lineTo(p.x+Math.cos(p.a)*r2,p.y+Math.sin(p.a)*r2);c.stroke();}
    else if(p.k==='star'){c.globalAlpha=1-e*e;const pts=starPts(p.x,p.y,p.sz,p.sz*0.45,p.rot);c.beginPath();pts.forEach((q,i)=>i?c.lineTo(q[0],q[1]):c.moveTo(q[0],q[1]));c.closePath();c.fillStyle=p.hl;c.fill();c.strokeStyle=p.col;c.lineWidth=1.5;c.stroke();}
    else if(p.k==='spiral'){c.globalAlpha=e>0.7?(1-e)/0.3:1;c.strokeStyle=p.col;c.lineWidth=1.8;c.beginPath();const amax=Math.min(1,e*1.8)*TAU*2.4;for(let a=0;a<=amax;a+=0.25){const rad=1+a*1.6;const x=p.x+Math.cos(a+p.rot)*rad,y=p.y+Math.sin(a+p.rot)*rad;a?c.lineTo(x,y):c.moveTo(x,y);}c.stroke();}
    else if(p.k==='ring'){c.globalAlpha=1-e;c.strokeStyle='#1c2a6b';c.lineWidth=2;c.beginPath();c.arc(p.x,p.y,6+e*38,0,TAU);c.stroke();}
    else if(p.k==='drop'){c.globalAlpha=1-e;c.fillStyle='#1c2a6b';c.beginPath();c.arc(p.x,p.y,p.sz,0,TAU);c.fill();}
  }
  c.globalAlpha=1;
  /* screen space */
  c.setTransform(dpr,0,0,dpr,0,0);
  for(const p of parts){
    if(p.k!=='text'||p.life<0)continue;const e=clamp(p.life/p.max,0,1);const s=toScreen(p.x,p.y);
    const pop=e<0.12?0.6+e/0.12*0.6:1.2-Math.min(0.2,(e-0.12)*0.5);
    c.save();c.globalAlpha=e>0.75?(1-e)/0.25:1;c.translate(clamp(s.x,90,SW-90),clamp(s.y-(p.small?16:36)-e*(p.small?16:26),60,SH-30));c.rotate(-0.08);c.scale(pop,pop);
    c.font='bold '+p.sz+'px '+HAND;c.textAlign='center';c.textBaseline='middle';c.lineJoin='round';c.lineWidth=5;c.strokeStyle='rgba(251,248,238,0.92)';c.strokeText(p.txt,0,0);c.fillStyle=p.col;c.fillText(p.txt,0,0);c.restore();
  }
  if(ai&&ai.power>0.01){
    const mw=Math.min(200,SW*0.4),mh=18,mx=SW-mw-16,my=SH-mh-18;
    c.fillStyle='rgba(251,248,238,0.85)';c.fillRect(mx-4,my-24,mw+8,mh+28);
    c.save();c.globalCompositeOperation='multiply';c.fillStyle=ai.power<0.5?'rgba(120,220,90,0.8)':ai.power<0.8?'rgba(255,215,40,0.85)':'rgba(255,90,150,0.85)';c.fillRect(mx+2,my+2,(mw-4)*ai.power,mh-4);c.restore();
    const r=mulberry32(5);pen(c,r,[[mx,my],[mx+mw,my],[mx+mw,my+mh],[mx,my+mh]],true,INK,2,0.8);
    c.strokeStyle=INK;c.lineWidth=1;c.beginPath();for(let i=1;i<10;i++){const x=mx+mw*i/10;c.moveTo(x,my+mh);c.lineTo(x,my+mh-(i%5===0?9:5));}c.stroke();
    c.font='bold 14px '+HAND;c.fillStyle=INK;c.textAlign='left';c.textBaseline='alphabetic';c.fillText('power',mx,my-6);c.textAlign='right';c.fillText(Math.round(ai.power*100)+'%',mx+mw,my-6);
  }
  if(demo){
    const p=toScreen(demo.ptr.x,demo.ptr.y);c.save();c.translate(p.x,p.y);
    if(demo.ptr.down){c.strokeStyle=RED;c.lineWidth=2;c.beginPath();c.arc(0,0,15,0,TAU);c.stroke();}
    c.rotate(-0.25);c.beginPath();c.moveTo(0,0);c.lineTo(0,24);c.lineTo(6,18);c.lineTo(11,28);c.lineTo(15,26);c.lineTo(10,16);c.lineTo(18,16);c.closePath();
    c.fillStyle='#fff';c.fill();c.strokeStyle='#111';c.lineWidth=2;c.lineJoin='round';c.stroke();c.restore();
  }
}

/* ---------- loop & quality ---------- */
let last=performance.now(),acc=0,ema=1/60,slowT=0,warm=0,readySent=false;
function perf(dt){warm++;ema=ema*0.95+dt*0.05;if(warm<120)return;if(ema>1/38){slowT+=dt;if(slowT>2&&quality>0.5){quality-=0.25;slowT=0;warm=0;resize();}}else slowT=Math.max(0,slowT-dt);}
function frame(now){
  let dt=(now-last)/1000;last=now;if(dt>0.1)dt=0.1;if(dt<0)dt=0;
  acc+=dt;let n=0;while(acc>=DT&&n<14){fixedStep();acc-=DT;n++;}if(n>=14)acc=0;
  updParts(dt);render(now);
  if(!readySent){readySent=true;try{parent.postMessage({vcb:'ready'},'*');}catch(e){}}
  perf(dt);
  requestAnimationFrame(frame);
}
let rt=0;
window.addEventListener('resize',()=>{clearTimeout(rt);rt=setTimeout(resize,60);});
window.addEventListener('orientationchange',()=>{clearTimeout(rt);rt=setTimeout(resize,120);});
window.addEventListener('hashchange',()=>{if(location.hash==='#demo'&&!demo)startDemo();});

setMuted(muted);
resize();
newGame();
if(location.hash==='#demo')startDemo();
else setTimeout(()=>{if(!demo&&G.strokes===0&&G.hi===0)note('drag back from the ball, let go to putt →','good');},2600);
requestAnimationFrame(frame);
})();
</script>
</body>
</html>

Try 2 · index.html

works36.6 KB · 489 lines · no libraries
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Notebook Mini-Golf</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#fbf8ec;font-family:"Segoe Print","Bradley Hand","Comic Sans MS","Chalkboard SE","Marker Felt",cursive;color:#1d3fb8;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent}
canvas{position:fixed;inset:0;width:100%;height:100%;touch-action:none;display:block;z-index:0}
#hud{position:fixed;left:0;right:0;top:0;display:flex;align-items:center;gap:6px;padding:6px 8px;padding-top:max(6px,env(safe-area-inset-top));pointer-events:none;flex-wrap:wrap;z-index:2}
#info{flex:1;min-width:150px;font-size:15px;line-height:1.25}
#info b{font-size:17px}
button{pointer-events:auto;min-width:44px;min-height:44px;font:inherit;font-size:14px;color:#1d3fb8;background:rgba(255,255,255,.75);border:2px solid #1d3fb8;border-radius:12px 9px 13px 8px/9px 13px 8px 12px;padding:4px 10px;cursor:pointer;touch-action:manipulation}
button:active{background:rgba(255,240,0,.55)}
#note{position:fixed;left:14px;bottom:12px;max-width:calc(100% - 200px);font-size:18px;color:#d0262f;line-height:1.15;transform:rotate(var(--r,-3deg)) translateY(10px);opacity:0;transition:opacity .35s,transform .35s;pointer-events:none;z-index:3;text-decoration:underline wavy rgba(208,38,47,.45);text-underline-offset:4px}
#note.show{opacity:1;transform:rotate(var(--r,-3deg))}
#card{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(250,248,236,.65);z-index:5}
#card.hide{display:none}
.sheet{background:#fffef6 repeating-linear-gradient(transparent 0 27px,#b9d3f0 27px 28px);border:2px solid #1d3fb8;border-radius:6px 14px 8px 12px;padding:16px 16px 18px 36px;max-width:94vw;box-sizing:border-box;box-shadow:3px 4px 0 rgba(29,63,184,.25);transform:rotate(-1deg);position:relative;text-align:center}
.sheet:before{content:"";position:absolute;left:24px;top:0;bottom:0;border-left:2px solid #e88}
.sheet h2{margin:0 0 8px;font-size:26px;background:linear-gradient(transparent 55%,rgba(255,240,0,.6) 55%);display:inline-block}
table{border-collapse:collapse;font-size:15px;margin:0 auto}
td,th{padding:3px 5px;text-align:center;border-bottom:1px dashed #9ab;min-width:18px}
td.g{border-radius:50%;box-shadow:0 0 0 2px #2a9d3a inset;color:#2a7d3a}
td.b{color:#d0262f}
#verdict{color:#d0262f;font-size:18px;margin:10px 0}
#again{font-size:20px;padding:8px 22px;background:rgba(255,240,0,.6)}
</style>
</head>
<body>
<canvas id="c"></canvas>
<div id="hud">
  <div id="info"><b id="hHole">Hole 1/9</b><br><span id="hStr"></span></div>
  <button id="bMute" aria-label="Toggle sound (M)">Mute</button>
  <button id="bRetry" aria-label="Retry hole (R)">Retry</button>
  <button id="bNew" aria-label="New game (N)">New</button>
</div>
<div id="note"></div>
<div id="card" class="hide"><div class="sheet"><h2>Scorecard</h2><table id="tbl"></table><p id="verdict"></p><button id="again">Play again</button></div></div>
<script>
(()=>{
"use strict";
const cv=document.getElementById('c'),ctx=cv.getContext('2d');
const layer=document.createElement('canvas'),lctx=layer.getContext('2d');
const hud=document.getElementById('hud'),elHole=document.getElementById('hHole'),elStr=document.getElementById('hStr');
const noteEl=document.getElementById('note'),card=document.getElementById('card'),tbl=document.getElementById('tbl'),verdict=document.getElementById('verdict');
const bMute=document.getElementById('bMute');
const HAND='"Segoe Print","Bradley Hand","Comic Sans MS","Chalkboard SE","Marker Felt",cursive';
const INK='#1d3fb8',RED='#d0262f',BLOT='#151a52',COLS=['#1d3fb8','#d0262f','#e0409a','#2a9d3a','#f08a00','#7a3fd0'];
const WW=360,WH=560,BR=5,CUPR=9,MAXV=680,MAXPULL=110,STEP=1/120;
let W=0,H=0,dpr=1,q=1,S=1,OX=0,OY=0,lowFx=false;

function mulberry(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}
let rng=mulberry(90210);
const pick=a=>a[Math.floor(rng()*a.length)];
function hn(a,b){const s=Math.sin(a*12.9898+b*78.233)*43758.5453;return(s-Math.floor(s))*2-1}

// ---------- holes ----------
const R=(x,y,w,h)=>({x,y,w,h});
const HOLES=[
 {name:"Paper-clip bumper",par:2,tee:[180,470],cup:[180,100],clips:[[110,285,250,285]],tip:"drag back from the ball & let go! (new: paper-clip bumper)"},
 {name:"Eraser block",par:2,tee:[90,470],cup:[270,95],erasers:[R(100,235,160,56),R(230,150,90,26)],tip:"new: eraser blocks - soft, dead bounces"},
 {name:"Shaded slope",par:2,tee:[180,480],cup:[180,95],slopes:[{r:R(40,190,280,170),f:[320,0]}],tip:"new: shaded slope - it curves the ball!"},
 {name:"Ink-blot water",par:3,tee:[180,480],cup:[210,95],blots:[[180,290,52],[92,170,28],[268,205,26]],tip:"new: ink blots are water. +1 stroke!"},
 {name:"Sticky-tape bridge",par:3,tee:[80,480],cup:[280,95],pools:[R(40,250,280,70)],bridges:[R(150,240,60,90)],tip:"new: cross the ink river on the tape"},
 {name:"Ruler gate",par:2,tee:[180,480],cup:[180,100],walls:[[40,280,140,280],[220,280,320,280]],ruler:{y:280,cx:180,amp:85,per:3.2,w:96,h:12},tip:"new: sliding ruler gate - time it"},
 {name:"Staple ramp",par:2,tee:[180,490],cup:[180,110],pools:[R(40,235,280,95)],ramp:{r:R(150,345,60,30),d:[0,-1]},tip:"new: hit the staple ramp HARD"},
 {name:"Spiral tunnel",par:3,tee:[250,470],cup:[250,115],walls:[[40,280,320,280]],tunnel:{a:[78,420],b:[78,150],d:[.97,-.24]},tip:"new: tunnel through the spiral binding"},
 {name:"The Final Page",par:4,tee:[180,500],cup:[180,85],slopes:[{r:R(40,370,280,80),f:[-300,0]}],walls:[[40,280,140,280],[220,280,320,280]],ruler:{y:280,cx:180,amp:85,per:2.6,w:96,h:12},blots:[[112,175,34]],clips:[[218,195,292,168]],tip:"final hole: a bit of everything!"}
];
const BOX=[[40,40],[320,40],[320,520],[40,520]];
HOLES.forEach(h=>{
 const s=[];
 for(let i=0;i<4;i++){const a=BOX[i],b=BOX[(i+1)%4];s.push({x1:a[0],y1:a[1],x2:b[0],y2:b[1],R:1.5,e:.72,k:'wall'})}
 (h.walls||[]).forEach(w=>s.push({x1:w[0],y1:w[1],x2:w[2],y2:w[3],R:1.5,e:.72,k:'wall'}));
 (h.erasers||[]).forEach(r=>{const p=[[r.x,r.y],[r.x+r.w,r.y],[r.x+r.w,r.y+r.h],[r.x,r.y+r.h]];for(let i=0;i<4;i++){const a=p[i],b=p[(i+1)%4];s.push({x1:a[0],y1:a[1],x2:b[0],y2:b[1],R:1.5,e:.3,k:'eraser'})}});
 (h.clips||[]).forEach(c=>s.push({x1:c[0],y1:c[1],x2:c[2],y2:c[3],R:7,e:1.15,k:'clip'}));
 h.segs=s;
});

// ---------- physics ----------
const NOOP=()=>{};
const inR=(r,x,y)=>x>r.x&&x<r.x+r.w&&y>r.y&&y<r.y+r.h;
function rulerX(h,t){return h.ruler.cx+h.ruler.amp*Math.sin(t*2*Math.PI/h.ruler.per)}
function isWater(h,x,y){
 if(h.bridges)for(const b of h.bridges)if(inR(b,x,y))return false;
 if(h.pools)for(const p of h.pools)if(inR(p,x,y))return true;
 if(h.blots)for(const b of h.blots)if(Math.hypot(x-b[0],y-b[1])<b[2]*.95)return true;
 return false;
}
function collideCap(s,c,ux,uy){
 const dx=c.x2-c.x1,dy=c.y2-c.y1,L2=dx*dx+dy*dy;
 let t=L2?((s.x-c.x1)*dx+(s.y-c.y1)*dy)/L2:0;t=t<0?0:t>1?1:t;
 const px=c.x1+dx*t,py=c.y1+dy*t;let nx=s.x-px,ny=s.y-py;const d=Math.hypot(nx,ny),m=BR+c.R;
 if(d>=m)return 0;
 if(d<1e-6){nx=-dy;ny=dx;const l=Math.hypot(nx,ny)||1;nx/=l;ny/=l}else{nx/=d;ny/=d}
 s.x=px+nx*m;s.y=py+ny*m;
 const vn=(s.vx-ux)*nx+(s.vy-uy)*ny;
 if(vn<0){
  s.vx-=(1+c.e)*vn*nx;s.vy-=(1+c.e)*vn*ny;
  const tx=-ny,ty=nx,vt=(s.vx-ux)*tx+(s.vy-uy)*ty;s.vx-=vt*tx*.06;s.vy-=vt*ty*.06;
  if(c.k==='clip'){s.vx+=nx*90;s.vy+=ny*90}
  return -vn;
 }
 return 0;
}
function step(s,h,dt,ev){
 ev=ev||NOOP;s.t+=dt;
 if(s.sunk)return;
 if(s.tun>0){s.tun-=dt;if(s.tun<=0){const T=h.tunnel;s.tun=0;s.x=T.b[0]+T.d[0]*18;s.y=T.b[1]+T.d[1]*18;s.vx=T.d[0]*s.tsp;s.vy=T.d[1]*s.tsp;s.slow=0;ev('tout',0,s.x,s.y)}return}
 if(!s.moving)return;
 const air=s.air>0;let onSlope=false;
 if(!air&&h.slopes)for(const sl of h.slopes)if(inR(sl.r,s.x,s.y)){s.vx+=sl.f[0]*dt;s.vy+=sl.f[1]*dt;onSlope=true}
 let sp=Math.hypot(s.vx,s.vy);
 if(!air&&sp>0){const ns=Math.max(0,sp-(50+.5*sp)*dt);s.vx*=ns/sp;s.vy*=ns/sp;sp=ns}
 const n=Math.max(1,Math.ceil(sp*dt/2)),sd=dt/n;
 let rx=0,rux=0,cap=null;
 if(h.ruler){const Ru=h.ruler,w=2*Math.PI/Ru.per;rx=rulerX(h,s.t);rux=Ru.amp*w*Math.cos(s.t*w);const hw=Ru.w/2-Ru.h/2;cap={x1:rx-hw,y1:Ru.y,x2:rx+hw,y2:Ru.y,R:Ru.h/2,e:.6,k:'ruler'}}
 for(let i=0;i<n;i++){
  s.x+=s.vx*sd;s.y+=s.vy*sd;
  if(cap){const hit=collideCap(s,cap,rux,0);if(hit>25)ev('ruler',hit,s.x,s.y)}
  for(const c of h.segs){const hit=collideCap(s,c,0,0);if(hit>25)ev(c.k,hit,s.x,s.y)}
 }
 if(air){s.air-=dt;if(s.air<=0){s.air=0;ev('land',0,s.x,s.y)}}
 if(s.air<=0){
  if(isWater(h,s.x,s.y)){ev('splash',0,s.x,s.y);s.wet++;s.x=s.lx;s.y=s.ly;s.vx=s.vy=0;s.moving=false;return}
  if(h.ramp&&inR(h.ramp.r,s.x,s.y)){const d=h.ramp.d,va=s.vx*d[0]+s.vy*d[1];
   if(va>200){s.air=.22+va*.00045;s.air0=s.air;ev('jump',va,s.x,s.y)}else{s.vx-=d[0]*500*dt;s.vy-=d[1]*500*dt;onSlope=true}}
  if(h.tunnel){const T=h.tunnel;if(Math.hypot(s.x-T.a[0],s.y-T.a[1])<13){s.tun=.7;s.tsp=Math.max(160,Math.min(480,sp*.95));s.x=T.a[0];s.y=T.a[1];s.vx=s.vy=0;ev('tin',0,s.x,s.y);return}}
  const cx=h.cup[0]-s.x,cy=h.cup[1]-s.y,d=Math.hypot(cx,cy)||1e-6;sp=Math.hypot(s.vx,s.vy);
  if(d<CUPR){
   if(s.lip){if(sp<70){s.sunk=true}}
   else if(sp<230){if(d<CUPR-2.5||sp<90)s.sunk=true;else{s.vx+=cx/d*700*dt;s.vy+=cy/d*700*dt}}
   else{s.lip=true;const cr=s.vx*cy-s.vy*cx,side=cr>0?-1:1,ang=side*(.6+.5*d/CUPR),cs=Math.cos(ang),sn=Math.sin(ang);
    const nvx=(s.vx*cs-s.vy*sn)*.72,nvy=(s.vx*sn+s.vy*cs)*.72;s.vx=nvx;s.vy=nvy;ev('lip',sp,s.x,s.y)}
   if(s.sunk){s.moving=false;s.x=h.cup[0];s.y=h.cup[1];s.vx=s.vy=0;ev('sink',0,s.x,s.y);return}
  }else if(d>CUPR+BR)s.lip=false;
 }
 sp=Math.hypot(s.vx,s.vy);
 if(s.air<=0){
  if(!onSlope&&sp<2){s.vx=s.vy=0;s.moving=false}
  else if(sp<10){s.slow+=dt;if(s.slow>.3){s.vx=s.vy=0;s.moving=false}}
  else s.slow=0;
 }
}

// ---------- drawing helpers ----------
function wl(c,x1,y1,x2,y2,a,sd){
 a=a==null?1.2:a;sd=sd||0;
 const dx=x2-x1,dy=y2-y1,L=Math.hypot(dx,dy)||1,n=Math.max(2,Math.ceil(L/9)),px=-dy/L,py=dx/L;
 const o0=hn(x1+sd,y1)*a*.6;c.moveTo(x1+px*o0,y1+py*o0);
 for(let i=1;i<=n;i++){const t=i/n,o=a*(Math.sin(t*6.283*(L/120+.5)+x1*.31+y1*.17+sd)*.55+hn(x1*.7+i+sd,y1+i)*.45)*(i===n?.5:1);c.lineTo(x1+dx*t+px*o,y1+dy*t+py*o)}
}
function pen(c,segs,col,lw,passes,a){
 c.strokeStyle=col;c.lineWidth=lw;c.lineCap='round';c.lineJoin='round';
 for(let p=0;p<(passes||2);p++){c.globalAlpha=p?.55:.95;c.beginPath();for(const s of segs)wl(c,s[0]+p*.4,s[1]-p*.3,s[2]+p*.3,s[3]+p*.4,a,p*7.3);c.stroke()}
 c.globalAlpha=1;
}
function rectSegs(x,y,w,h){return[[x,y,x+w,y],[x+w,y,x+w,y+h],[x+w,y+h,x,y+h],[x,y+h,x,y]]}
function blobPath(c,cx,cy,r,amt,sd,n){
 n=n||22;const pts=[];
 for(let i=0;i<n;i++){const a=i/n*Math.PI*2,rr=r*(1+amt*hn(i*1.7+sd,cx*.1+cy*.03));pts.push([cx+Math.cos(a)*rr,cy+Math.sin(a)*rr])}
 c.beginPath();const m=(p,q2)=>[(p[0]+q2[0])/2,(p[1]+q2[1])/2];let st=m(pts[n-1],pts[0]);c.moveTo(st[0],st[1]);
 for(let i=0;i<n;i++){const p=pts[i],nx=m(p,pts[(i+1)%n]);c.quadraticCurveTo(p[0],p[1],nx[0],nx[1])}c.closePath();
}
function hiFill(c,x,y,w,h,col,lw){
 c.save();c.globalCompositeOperation='multiply';c.strokeStyle=col;c.lineWidth=lw;c.lineCap='butt';
 for(let yy=y-14;yy<y+h+14;yy+=lw*.85){c.beginPath();c.moveTo(x-10,yy+hn(yy,x)*2);c.lineTo(x+w+10,yy+7+hn(yy,y)*3);c.stroke()}
 c.restore();
}
function hatch(c,x,y,w,h,col,gap,lw){
 c.save();c.beginPath();c.rect(x,y,w,h);c.clip();c.strokeStyle=col;c.lineWidth=lw||.8;c.beginPath();
 for(let k=-h;k<w;k+=gap){c.moveTo(x+k+hn(k,y)*1,y+h);c.lineTo(x+k+h+hn(k,x)*1.5,y)}c.stroke();c.restore();
}
function arrow(c,x,y,dx,dy,L,col){
 const ex=x+dx*L,ey=y+dy*L;c.strokeStyle=col;c.lineWidth=1.6;c.beginPath();wl(c,x,y,ex,ey,.8,x);
 const a=Math.atan2(dy,dx);c.moveTo(ex,ey);c.lineTo(ex-Math.cos(a-.5)*7,ey-Math.sin(a-.5)*7);c.moveTo(ex,ey);c.lineTo(ex-Math.cos(a+.5)*7,ey-Math.sin(a+.5)*7);c.stroke();
}
function star(c,x,y,s,rot){c.beginPath();for(let i=0;i<=10;i++){const a=rot+i*Math.PI/5-Math.PI/2,r=i%2?s*.45:s;const px=x+Math.cos(a)*r,py=y+Math.sin(a)*r;i?c.lineTo(px,py):c.moveTo(px,py)}c.stroke()}
function swirl(c,x,y,s,rot){c.beginPath();for(let a=0;a<12.6;a+=.4){const r=a*s/12;const px=x+Math.cos(a+rot)*r,py=y+Math.sin(a+rot)*r;a?c.lineTo(px,py):c.moveTo(px,py)}c.stroke()}

// ---------- static layer ----------
function drawPaper(c){
 c.fillStyle='#fbf8ec';c.fillRect(0,0,W,H);
 const sp=Math.max(20,28*S);c.strokeStyle='#b9d3f0';c.lineWidth=1;c.beginPath();
 for(let y=(OY%sp)+sp*.5;y<H;y+=sp){c.moveTo(0,y);c.lineTo(W,y)}c.stroke();
 const mx=Math.max(30,OX*.5);c.strokeStyle='rgba(230,110,110,.75)';c.beginPath();c.moveTo(mx,0);c.lineTo(mx,H);c.moveTo(mx+3,0);c.lineTo(mx+3,H);c.lineWidth=.8;c.stroke();
 for(let y=20;y<H;y+=34){c.fillStyle='#e6e0cc';c.beginPath();c.arc(11,y,5,0,7);c.fill();c.strokeStyle='#cfc7ad';c.lineWidth=1;c.stroke()}
 if(OX>110){const r2=mulberry(7);
  for(let i=0;i<8;i++){const left=i%2===0,x=left?mx+20+r2()*(OX-mx-60):OX+WW*S+20+r2()*(OX-60),y=OY+60+r2()*(WH*S-120);
   c.strokeStyle=pick2(r2,['rgba(29,63,184,.35)','rgba(208,38,47,.3)','rgba(42,157,58,.3)']);c.lineWidth=1.5;
   const k=i%4;if(k===0)star(c,x,y,10+r2()*8,r2());else if(k===1)swirl(c,x,y,14,r2()*6);else if(k===2){c.beginPath();for(let j=0;j<5;j++){c.moveTo(x-12,y+j*5);c.lineTo(x+12,y+j*5+2)}c.stroke()}else{c.beginPath();c.arc(x,y,9,0,7);c.moveTo(x-4,y-2);c.arc(x-4,y-2,.8,0,7);c.moveTo(x+4,y-2);c.arc(x+4,y-2,.8,0,7);c.moveTo(x+5,y+3);c.arc(x,y+2,5,.3,2.8);c.stroke()}}}
}
function pick2(r,a){return a[Math.floor(r()*a.length)]}
function drawCourse(c,h,idx){
 c.font=`16px ${HAND}`;c.fillStyle=INK;c.textBaseline='alphabetic';c.textAlign='left';
 c.fillText(`Hole ${idx+1}: ${h.name}`,40,27);c.textAlign='right';c.fillText(`par ${h.par}`,320,27);c.textAlign='left';
 hiFill(c,40,30,170,6,'rgba(255,235,0,.5)',7);
 c.save();c.beginPath();c.rect(40,40,280,480);c.clip();hiFill(c,40,40,280,480,'rgba(130,230,110,.26)',18);c.restore();
 // slopes
 (h.slopes||[]).forEach(sl=>{const r=sl.r;hatch(c,r.x,r.y,r.w,r.h,'rgba(70,70,90,.33)',6,.8);
  const L=Math.hypot(sl.f[0],sl.f[1]),dx=sl.f[0]/L,dy=sl.f[1]/L;
  for(let i=0;i<3;i++){const ax=r.x+r.w*(.25+.25*i)-dx*24,ay=r.y+r.h*(i%2?.33:.66)-dy*24;arrow(c,ax,ay,dx,dy,48,'rgba(60,60,80,.75)')}
  c.font=`12px ${HAND}`;c.fillStyle='rgba(60,60,80,.8)';c.fillText('downhill',r.x+6,r.y+14)});
 // water
 (h.pools||[]).forEach((p,pi)=>{c.beginPath();const N=24;
  for(let i=0;i<=N;i++){const x=p.x+p.w*i/N,y=p.y+hn(i,pi+1)*4;i?c.lineTo(x,y):c.moveTo(x,y)}
  for(let i=N;i>=0;i--){c.lineTo(p.x+p.w*i/N,p.y+p.h+hn(i,pi+9)*4)}c.closePath();c.fillStyle=BLOT;c.fill();
  c.strokeStyle='rgba(255,255,255,.35)';c.lineWidth=1.2;for(let i=0;i<5;i++){c.beginPath();const x=p.x+20+i*55,y=p.y+p.h*(.3+.4*((i*37)%10)/10);c.moveTo(x,y);c.quadraticCurveTo(x+8,y-4,x+16,y);c.quadraticCurveTo(x+24,y+4,x+32,y);c.stroke()}});
 (h.blots||[]).forEach((b,i)=>{c.fillStyle=BLOT;blobPath(c,b[0],b[1],b[2],.16,i*3.1+1);c.fill();
  for(let k=0;k<7;k++){const a=hn(k,b[0])*Math.PI,dd=b[2]*(1.15+Math.abs(hn(k,b[1]))*.4),rr=1.2+Math.abs(hn(k+3,b[2]))*3;c.beginPath();c.arc(b[0]+Math.cos(a)*dd,b[1]+Math.sin(a)*dd,rr,0,7);c.fill()}
  c.strokeStyle='rgba(255,255,255,.3)';c.lineWidth=1.3;c.beginPath();c.arc(b[0]-b[2]*.3,b[1]-b[2]*.3,b[2]*.35,3.4,4.6);c.stroke()});
 (h.bridges||[]).forEach(b=>{c.save();c.globalAlpha=.88;c.fillStyle='#efe3b8';c.beginPath();c.moveTo(b.x,b.y);
  for(let i=0;i<=6;i++)c.lineTo(b.x+b.w*i/6,b.y+(i%2?4:0));c.lineTo(b.x+b.w,b.y+b.h);for(let i=6;i>=0;i--)c.lineTo(b.x+b.w*i/6,b.y+b.h-(i%2?4:0));c.closePath();c.fill();c.restore();
  c.strokeStyle='rgba(150,120,60,.5)';c.lineWidth=1;c.beginPath();c.moveTo(b.x,b.y+4);c.lineTo(b.x,b.y+b.h-4);c.moveTo(b.x+b.w,b.y+4);c.lineTo(b.x+b.w,b.y+b.h-4);c.stroke();
  c.strokeStyle='rgba(255,255,255,.7)';c.lineWidth=2;for(let k=0;k<3;k++){c.beginPath();c.moveTo(b.x+8+k*16,b.y+20+k*20);c.lineTo(b.x+20+k*16,b.y+8+k*20);c.stroke()}
  c.font=`11px ${HAND}`;c.fillStyle='rgba(120,90,40,.9)';c.save();c.translate(b.x+b.w/2,b.y+b.h/2);c.rotate(-Math.PI/2);c.textAlign='center';c.fillText('sticky tape',0,4);c.restore()});
 if(h.ramp){const r=h.ramp.r;c.fillStyle='rgba(200,200,210,.5)';c.fillRect(r.x,r.y,r.w,r.h);hatch(c,r.x,r.y,r.w,r.h,'rgba(80,80,100,.4)',4,.7);
  c.strokeStyle='#7d838f';c.lineWidth=3.2;c.lineCap='round';c.lineJoin='round';c.beginPath();c.moveTo(r.x+7,r.y+r.h-2);c.lineTo(r.x+7,r.y+3);c.lineTo(r.x+r.w-7,r.y+3);c.lineTo(r.x+r.w-7,r.y+r.h-2);c.stroke();
  c.strokeStyle='rgba(255,255,255,.8)';c.lineWidth=1;c.beginPath();c.moveTo(r.x+12,r.y+2);c.lineTo(r.x+r.w-12,r.y+2);c.stroke();
  c.strokeStyle=INK;c.lineWidth=1.5;for(let k=0;k<2;k++){const y=r.y+r.h-6-k*9;c.beginPath();c.moveTo(r.x+r.w/2-9,y+5);c.lineTo(r.x+r.w/2,y);c.lineTo(r.x+r.w/2+9,y+5);c.stroke()}
  c.font=`12px ${HAND}`;c.fillStyle=INK;c.fillText('staple ramp',r.x+r.w+6,r.y+r.h-8);}
 if(h.tunnel){const T=h.tunnel;c.setLineDash([5,5]);c.strokeStyle='rgba(29,63,184,.55)';c.lineWidth=1.5;c.beginPath();c.moveTo(T.a[0],T.a[1]);c.quadraticCurveTo(14,(T.a[1]+T.b[1])/2,T.b[0],T.b[1]);c.stroke();c.setLineDash([]);
  for(let y=T.b[1]-10;y<T.a[1]+14;y+=20){c.strokeStyle='#5d636e';c.lineWidth=2.2;c.beginPath();c.ellipse(40,y,17,6,-.3,Math.PI*.9,Math.PI*2.1);c.stroke();c.strokeStyle='rgba(255,255,255,.7)';c.lineWidth=.8;c.beginPath();c.ellipse(40,y-1,15,4.5,-.3,Math.PI*1.2,Math.PI*1.7);c.stroke();c.fillStyle='#e6e0cc';c.beginPath();c.arc(52,y+3,2.6,0,7);c.fill()}
  [[T.a,'in'],[T.b,'out']].forEach(([p,l])=>{c.fillStyle='#22264a';c.beginPath();c.arc(p[0],p[1],12,0,7);c.fill();c.strokeStyle=INK;c.lineWidth=1.5;c.beginPath();c.arc(p[0],p[1],14,0,7);c.stroke();c.font=`12px ${HAND}`;c.fillStyle=INK;c.fillText(l,p[0]+17,p[1]+4)});
  c.font=`11px ${HAND}`;c.fillStyle='rgba(60,60,80,.85)';c.save();c.translate(26,(T.a[1]+T.b[1])/2);c.rotate(-Math.PI/2);c.textAlign='center';c.fillText('spiral binding tunnel',0,0);c.restore();}
 (h.erasers||[]).forEach(r=>{c.fillStyle='#f4a3b5';c.fillRect(r.x,r.y,r.w,r.h);c.fillStyle='#6d93db';c.fillRect(r.x+r.w*.64,r.y,r.w*.36,r.h);
  hatch(c,r.x,r.y,r.w,r.h,'rgba(120,40,70,.18)',5,.7);pen(c,rectSegs(r.x,r.y,r.w,r.h),INK,1.6,2,.9);
  c.font=`${Math.min(14,r.h*.55)}px ${HAND}`;c.fillStyle='rgba(120,30,60,.8)';c.textAlign='center';c.fillText('eraser',r.x+r.w*.32,r.y+r.h/2+4);c.textAlign='left';
  c.fillStyle='rgba(200,120,140,.6)';for(let k=0;k<5;k++){c.beginPath();c.arc(r.x+10+k*r.w/5+hn(k,r.x)*4,r.y+r.h+5+Math.abs(hn(k,r.y))*5,1.3,0,7);c.fill()}});
 (h.clips||[]).forEach(cl=>{const[x1,y1,x2,y2]=cl,L=Math.hypot(x2-x1,y2-y1),a=Math.atan2(y2-y1,x2-x1);
  c.save();c.globalCompositeOperation='multiply';c.strokeStyle='rgba(255,120,200,.35)';c.lineWidth=20;c.lineCap='round';c.beginPath();c.moveTo(x1,y1);c.lineTo(x2,y2);c.stroke();c.restore();
  c.save();c.translate(x1,y1);c.rotate(a);c.strokeStyle='#636c80';c.lineWidth=2.2;c.lineCap='round';
  c.beginPath();c.moveTo(0,-7);c.lineTo(L,-7);c.arc(L,0,7,-Math.PI/2,Math.PI/2);c.lineTo(0,7);c.arc(0,0,7,Math.PI/2,Math.PI*1.5);c.stroke();
  c.beginPath();c.moveTo(L*.85,3.5);c.lineTo(L*.12,3.5);c.arc(L*.12,0,3.5,Math.PI/2,Math.PI*1.5);c.lineTo(L*.9,-3.5);c.stroke();
  c.strokeStyle='rgba(255,255,255,.85)';c.lineWidth=.9;c.beginPath();c.moveTo(L*.3,-6);c.lineTo(L*.7,-6);c.stroke();c.restore()});
 // walls
 const ws=[];for(let i=0;i<4;i++){const a=BOX[i],b=BOX[(i+1)%4];ws.push([a[0],a[1],b[0],b[1]])}(h.walls||[]).forEach(w=>ws.push(w));
 pen(c,ws,INK,2.6,2,1.3);
 pen(c,rectSegs(35,35,290,490),'rgba(29,63,184,.35)',1,1,1.6);
 // tee & cup
 const[tx,ty]=h.tee;c.strokeStyle=RED;c.lineWidth=1.6;c.beginPath();c.moveTo(tx-6,ty-6);c.lineTo(tx+6,ty+6);c.moveTo(tx+6,ty-6);c.lineTo(tx-6,ty+6);c.stroke();
 c.font=`11px ${HAND}`;c.fillStyle=RED;c.fillText('tee',tx+9,ty+12);
 const[cx,cy]=h.cup;c.fillStyle='#14162e';blobPath(c,cx,cy,CUPR,.05,cx,16);c.fill();c.strokeStyle=INK;c.lineWidth=1.3;c.beginPath();c.arc(cx,cy,CUPR+1.5,0,7);c.stroke();
 c.strokeStyle='#333';c.lineWidth=1.6;c.beginPath();c.moveTo(cx,cy);c.lineTo(cx+3,cy-34);c.stroke();
 c.fillStyle='rgba(255,70,170,.6)';c.beginPath();c.moveTo(cx+3,cy-34);c.lineTo(cx+24,cy-28);c.lineTo(cx+3,cy-21);c.closePath();c.fill();c.strokeStyle=RED;c.lineWidth=1.1;c.stroke();
 c.font=`10px ${HAND}`;c.fillStyle='#fff';c.fillText(String(idx+1),cx+7,cy-25);
}
function buildLayer(){
 layer.width=cv.width;layer.height=cv.height;
 lctx.setTransform(dpr,0,0,dpr,0,0);drawPaper(lctx);
 lctx.setTransform(dpr*S,0,0,dpr*S,dpr*OX,dpr*OY);drawCourse(lctx,HOLES[hi],hi);
 lctx.setTransform(1,0,0,1,0,0);
}
function resize(){
 W=innerWidth;H=innerHeight;dpr=Math.max(.75,Math.min(devicePixelRatio||1,2)*q);
 cv.width=Math.round(W*dpr);cv.height=Math.round(H*dpr);
 const top=hud.offsetHeight+2,bot=58;
 S=Math.min((W-16)/WW,(H-top-bot)/WH);if(S<.3)S=.3;
 OX=(W-WW*S)/2;OY=top+Math.max(0,(H-top-bot-WH*S)/2);
 buildLayer();
}

// ---------- audio ----------
let AC=null,muted=false,nbuf=null;
function ensureAudio(){
 if(!AC){try{AC=new(window.AudioContext||window.webkitAudioContext)();nbuf=AC.createBuffer(1,AC.sampleRate*.6,AC.sampleRate);const d=nbuf.getChannelData(0),r=mulberry(5);for(let i=0;i<d.length;i++)d[i]=r()*2-1}catch(e){AC=null}}
 if(AC&&AC.state==='suspended')AC.resume();
}
function tone(f,d,type,v,f2,delay){if(!AC||muted)return;const t=AC.currentTime+(delay||0),o=AC.createOscillator(),g=AC.createGain();o.type=type||'sine';o.frequency.setValueAtTime(f,t);if(f2)o.frequency.exponentialRampToValueAtTime(f2,t+d);g.gain.setValueAtTime(0.0001,t);g.gain.linearRampToValueAtTime(v,t+.008);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g).connect(AC.destination);o.start(t);o.stop(t+d+.03)}
function noise(d,v,fq,type){if(!AC||muted||!nbuf)return;const t=AC.currentTime,s=AC.createBufferSource(),f=AC.createBiquadFilter(),g=AC.createGain();s.buffer=nbuf;f.type=type||'lowpass';f.frequency.value=fq;g.gain.setValueAtTime(v,t);g.gain.exponentialRampToValueAtTime(.0001,t+d);s.connect(f).connect(g).connect(AC.destination);s.start(t);s.stop(t+d+.02)}
let lastSnd=0;
const SND={
 putt:p=>{noise(.06,.35,2500,'highpass');tone(900,.07,'triangle',.15+p*.15,300)},
 wall:v=>{const n=performance.now();if(n-lastSnd<40)return;lastSnd=n;tone(240+Math.min(v,600)*.5,.05,'triangle',Math.min(.25,v/1600))},
 eraser:()=>tone(110,.09,'sine',.25,70),
 clip:()=>{tone(180,.25,'square',.06,620);tone(360,.2,'sine',.12,900)},
 ruler:()=>{tone(520,.05,'square',.07);noise(.04,.15,3000,'bandpass')},
 splash:()=>{noise(.5,.45,900);tone(300,.3,'sine',.12,90)},
 jump:()=>tone(300,.3,'sine',.18,1000),
 land:()=>tone(160,.08,'triangle',.18),
 tin:()=>tone(220,.5,'sawtooth',.06,70),
 tout:()=>tone(90,.3,'sine',.15,260),
 lip:()=>{tone(700,.08,'triangle',.18,380);tone(500,.12,'triangle',.12,260,.07)},
 sink:big=>{tone(520,.12,'sine',.25,140);[523,659,784,1047].concat(big?[1319,1568]:[]).forEach((f,i)=>tone(f,.18,'triangle',.14,0,.12+i*.09))}
};

// ---------- game state ----------
let hi=0,strokes=0,scores=[],phase='aim',ball=null,shot=null,trail=[],fx=[],gen=0;
const aim={on:false,id:-1,sx:0,sy:0,cx:0,cy:0};
function newBall(p){return{x:p[0],y:p[1],vx:0,vy:0,moving:false,air:0,air0:1,tun:0,tsp:0,sunk:false,lip:false,slow:0,lx:p[0],ly:p[1],t:0,wet:0}}
const later=(ms,fn)=>{const g=gen;setTimeout(()=>{if(g===gen)fn()},ms)};
function loadHole(i){gen++;hi=i;strokes=0;ball=newBall(HOLES[i].tee);phase='aim';trail=[];fx=[];aim.on=false;buildLayer();updHud();if(!demo.on)say(HOLES[i].tip,3600)}
function newGame(){gen++;scores=[];card.classList.add('hide');loadHole(0)}
function holeDone(){
 if(demo.on){demoNext();return}
 scores[hi]=strokes;if(hi>=HOLES.length-1)showCard();else loadHole(hi+1);
}
function updHud(){
 const h=HOLES[hi];let tp=0,ts=0;for(let i=0;i<HOLES.length;i++)if(scores[i]!=null){tp+=HOLES[i].par;ts+=scores[i]}
 const rel=ts-tp;elHole.textContent=(demo.on?'DEMO - ':'')+`Hole ${hi+1}/9 · Par ${h.par}`;
 elStr.textContent=`Strokes ${strokes} · Total ${ts} (${rel===0?'E':rel>0?'+'+rel:rel})`;
}
let noteT=0;
function say(t,ms){noteEl.textContent=t;noteEl.style.setProperty('--r',(-5+rng()*5).toFixed(1)+'deg');noteEl.classList.add('show');clearTimeout(noteT);noteT=setTimeout(()=>noteEl.classList.remove('show'),ms||2600)}
const NOTES={
 ace:["HOLE IN ONE!!! frame this page","ACE!! nobody will believe me","one stroke. absolute legend."],
 birdie:["under par - smooth!","nice putt :)","gold star for you ★"],
 par:["par. solid.","by the book.","respectable!"],
 bogey:["meh... it went in","counts all the same"],
 bad:["that took a while...","maybe try croquet?","erase that hole from memory"],
 splash:["glug glug... +1 stroke","ink everywhere! +1","swim lessons? +1"],
 lip:["LIPPED OUT!! way too hot","so close it hurts","the cup said NO"],
 wrong:["wrong way?!","bold strategy.","uh... the cup is THAT way"],
 hard:["easy there, tiger","full send!? ok then"],
 tap:["tap-in time","almost! easy one now"]
};
function shoot(ang,pow){
 ball.lx=ball.x;ball.ly=ball.y;ball.vx=Math.cos(ang)*pow*MAXV;ball.vy=Math.sin(ang)*pow*MAXV;ball.moving=true;ball.slow=0;ball.lip=false;
 strokes++;shot={pow,d0:Math.hypot(ball.x-HOLES[hi].cup[0],ball.y-HOLES[hi].cup[1]),splash:false,lip:false};phase='roll';trail=[];SND.putt(pow);updHud();
}
function shotEnd(){
 const h=HOLES[hi],d=Math.hypot(ball.x-h.cup[0],ball.y-h.cup[1]);let k=null;
 if(shot.splash)k='splash';else if(shot.lip)k='lip';else if(d>shot.d0+60)k='wrong';else if(shot.pow>.97&&d>80)k='hard';else if(d<28)k='tap';
 phase='aim';
 if(strokes>=10){say("picked up at 10. next page!",2200);phase='wait';later(1500,holeDone);return}
 if(k&&!demo.on)say(pick(NOTES[k]));
}
function onEv(k,v,x,y){
 switch(k){
  case'wall':SND.wall(v);break;
  case'eraser':SND.eraser();break;
  case'ruler':SND.ruler();break;
  case'clip':SND.clip();fx.push({k:'text',x,y:y-12,str:'boing!',t:0,life:.8,col:'#e0409a',sz:13});break;
  case'splash':strokes++;if(shot)shot.splash=true;SND.splash();for(let i=0;i<3;i++)fx.push({k:'ring',x,y,t:-i*.15,life:.9,col:BLOT});for(let i=0;i<8;i++){const a=rng()*6.28;fx.push({k:'drop',x,y,vx:Math.cos(a)*60,vy:Math.sin(a)*60,t:0,life:.6,col:BLOT,s:2})}updHud();break;
  case'jump':SND.jump();fx.push({k:'text',x,y:y-10,str:'wheee!',t:0,life:.9,col:RED,sz:13});break;
  case'land':SND.land();fx.push({k:'ring',x,y,t:0,life:.4,col:'#555'});break;
  case'tin':SND.tin();break;
  case'tout':SND.tout();fx.push({k:'text',x:x+10,y:y-10,str:'pop!',t:0,life:.7,col:INK,sz:12});break;
  case'lip':if(shot)shot.lip=true;SND.lip();fx.push({k:'text',x,y:y-14,str:'!!',t:0,life:.7,col:RED,sz:16});break;
  case'sink':{const h=HOLES[hi],big=strokes===1;phase='celebrate';SND.sink(big);celebrate(x,y,big);
   const p=h.par,key=strokes===1?'ace':strokes<p?'birdie':strokes===p?'par':strokes<=p+1?'bogey':'bad';
   if(!demo.on)say(pick(NOTES[key]),2400);later(big?2300:1700,holeDone);break}
 }
}
function celebrate(x,y,big){
 const n=big?28:16;
 for(let i=0;i<n;i++){const a=rng()*6.283,v=40+rng()*120;fx.push({k:i%3===0?'swirl':'star',x,y,vx:Math.cos(a)*v,vy:Math.sin(a)*v,r:rng()*6,vr:(rng()-.5)*6,s:4+rng()*5,t:0,life:1.3+rng()*.5,col:COLS[i%COLS.length]})}
 fx.push({k:'text',x:Math.max(90,Math.min(270,x)),y:y-24,str:big?'HOLE IN ONE!':pick(['PLOP!','in!','sunk it!','yesss']),t:0,life:1.8,col:RED,sz:big?22:19,ul:true});
 fx.push({k:'ring',x,y,t:0,life:.8,col:INK});fx.push({k:'ring',x,y,t:-.2,life:.8,col:'#e0409a'});
}
function showCard(){
 phase='card';let tp=0,ts=0,r1='<tr><th>Hole</th>',r2='<tr><th>Par</th>',r3='<tr><th>You</th>';
 HOLES.forEach((h,i)=>{const s=scores[i]||0;tp+=h.par;ts+=s;r1+=`<td>${i+1}</td>`;r2+=`<td>${h.par}</td>`;const d=s-h.par;r3+=`<td class="${d<0?'g':d>0?'b':''}">${s}</td>`});
 tbl.innerHTML=r1+'<th>Tot</th></tr>'+r2+`<th>${tp}</th></tr>`+r3+`<th>${ts}</th></tr>`;
 const d=ts-tp;let best=null;
 try{best=parseInt(localStorage.getItem('nb-minigolf-best'),10);if(!(best>0)||ts<best){localStorage.setItem('nb-minigolf-best',String(ts));best=best>0?best:null}}catch(e){best=null}
 verdict.textContent=(d<0?`${-d} under par - doodle champion!`:d===0?'right on par. nice!':`${d} over par. there's always the next page!`)+(best?`  (best: ${Math.min(best,ts)})`:'');
 card.classList.remove('hide');SND.sink(d<0);
}

// ---------- demo ----------
const demo={on:false,list:[0,2,5,6,7],idx:0,ht:0,ph:'idle',t:0,from:{x:0,y:0},to:{x:0,y:0},plan:null,cur:{x:0,y:0,down:false}};
const w2s=(x,y)=>({x:OX+x*S,y:OY+y*S});
function autoplan(){
 const h=HOLES[hi];let best=null;
 for(let a=0;a<48;a++){const ang=a/48*Math.PI*2;for(const p of[.2,.3,.42,.55,.7,.85,1]){
  const s=Object.assign({},ball);s.t=ball.t+1.45;s.vx=Math.cos(ang)*p*MAXV;s.vy=Math.sin(ang)*p*MAXV;s.moving=true;s.lx=s.x;s.ly=s.y;s.wet=0;s.lip=false;s.slow=0;
  let i=0;for(;i<900;i++){step(s,h,STEP,null);if(s.sunk||(!s.moving&&s.tun<=0))break}
  const sc=s.sunk?-1000+i*.01+p:Math.hypot(s.x-h.cup[0],s.y-h.cup[1])+s.wet*400;
  if(!best||sc<best.sc)best={sc,ang,pow:p};
 }}
 return best;
}
function startDemo(){demo.on=true;demo.idx=0;demo.ht=0;demo.ph='idle';demo.cur={x:W*.7,y:H*.8,down:false};scores=[];loadHole(demo.list[0]);say('demo - tap anywhere to play!',30000)}
function demoNext(){demo.idx=(demo.idx+1)%demo.list.length;demo.ht=0;demo.ph='idle';loadHole(demo.list[demo.idx])}
function endDemo(){demo.on=false;demo.cur.down=false;aim.on=false;noteEl.classList.remove('show');newGame()}
const ease=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;
function demoUpdate(dt){
 demo.ht+=dt;const c=demo.cur;
 if(phase==='roll'&&demo.ht>7){demoNext();return}
 if(demo.ph==='idle'){
  if(phase!=='aim')return;
  if(demo.ht>4.6){demoNext();return}
  demo.plan=autoplan();demo.ph='move';demo.t=0;demo.from={x:c.x,y:c.y};demo.to=w2s(ball.x,ball.y);return;
 }
 const b=w2s(ball.x,ball.y);
 if(demo.ph==='move'){demo.t+=dt/.5;const e=ease(Math.min(1,demo.t));c.x=demo.from.x+(b.x-demo.from.x)*e;c.y=demo.from.y+(b.y-demo.from.y)*e;
  if(demo.t>=1){demo.ph='drag';demo.t=0;c.down=true;aim.on=true;aim.sx=b.x;aim.sy=b.y;aim.cx=b.x;aim.cy=b.y}}
 else if(demo.ph==='drag'){demo.t+=dt/.7;const e=ease(Math.min(1,demo.t)),L=demo.plan.pow*MAXPULL*S*e;
  c.x=b.x-Math.cos(demo.plan.ang)*L;c.y=b.y-Math.sin(demo.plan.ang)*L;aim.cx=c.x;aim.cy=c.y;if(demo.t>=1){demo.ph='hold';demo.t=0}}
 else if(demo.ph==='hold'){demo.t+=dt/.25;if(demo.t>=1){aim.on=false;c.down=false;demo.ph='idle';shoot(demo.plan.ang,demo.plan.pow)}}
}

// ---------- input ----------
function aimVals(){const px=(aim.sx-aim.cx)/S,py=(aim.sy-aim.cy)/S,L=Math.hypot(px,py);return{ang:Math.atan2(py,px),pow:Math.min(1,L/MAXPULL),L}}
addEventListener('pointerdown',()=>{ensureAudio();if(demo.on)endDemo()},true);
addEventListener('keydown',e=>{ensureAudio();if(demo.on){endDemo();return}const k=(e.key||'').toLowerCase();
 if(k==='m')toggleMute();else if(k==='r')retry();else if(k==='n')newGame();else if((k==='enter'||k===' ')&&phase==='card'){e.preventDefault();newGame()}});
cv.addEventListener('pointerdown',e=>{if(demo.on||phase!=='aim'||aim.on)return;aim.on=true;aim.id=e.pointerId;aim.sx=aim.cx=e.clientX;aim.sy=aim.cy=e.clientY;try{cv.setPointerCapture(e.pointerId)}catch(_){}e.preventDefault()});
cv.addEventListener('pointermove',e=>{if(!aim.on||demo.on||e.pointerId!==aim.id)return;aim.cx=e.clientX;aim.cy=e.clientY});
cv.addEventListener('pointerup',e=>{if(!aim.on||demo.on||e.pointerId!==aim.id)return;aim.cx=e.clientX;aim.cy=e.clientY;aim.on=false;const a=aimVals();if(a.pow>=.05&&phase==='aim')shoot(a.ang,a.pow)});
cv.addEventListener('pointercancel',()=>{if(!demo.on)aim.on=false});
cv.addEventListener('contextmenu',e=>e.preventDefault());
function toggleMute(){muted=!muted;bMute.textContent=muted?'Unmute':'Mute'}
function retry(){if(phase==='card')return;loadHole(hi)}
bMute.addEventListener('click',toggleMute);
document.getElementById('bRetry').addEventListener('click',retry);
document.getElementById('bNew').addEventListener('click',()=>newGame());
document.getElementById('again').addEventListener('click',()=>newGame());
addEventListener('resize',resize);

// ---------- render ----------
function drawDynamic(c){
 const h=HOLES[hi];
 if(h.ruler){const Ru=h.ruler,rx=rulerX(h,ball.t),x=rx-Ru.w/2,y=Ru.y-Ru.h/2;
  c.fillStyle='rgba(0,0,0,.12)';c.fillRect(x+2,y+3,Ru.w,Ru.h);c.fillStyle='#f2d06b';c.fillRect(x,y,Ru.w,Ru.h);
  c.strokeStyle=INK;c.lineWidth=1.2;c.strokeRect(x,y,Ru.w,Ru.h);c.lineWidth=.7;c.beginPath();
  for(let i=4;i<Ru.w;i+=4){const L=i%20===0?Ru.h*.6:i%10===0?Ru.h*.42:Ru.h*.25;c.moveTo(x+i,y);c.lineTo(x+i,y+L)}c.stroke();
  c.font=`5px ${HAND}`;c.fillStyle=INK;for(let i=20,n=1;i<Ru.w;i+=20,n++)c.fillText(String(n),x+i-1.5,y+Ru.h-1.5);}
 if(!lowFx&&trail.length>1){c.fillStyle='rgba(60,60,80,.35)';for(let i=0;i<trail.length;i+=2){c.beginPath();c.arc(trail[i][0],trail[i][1],.9,0,7);c.fill()}}
 if(ball.tun>0&&h.tunnel){const T=h.tunnel,p=1-ball.tun/.7,mx=14,my=(T.a[1]+T.b[1])/2,u=1-p;
  const x=u*u*T.a[0]+2*u*p*mx+p*p*T.b[0],y=u*u*T.a[1]+2*u*p*my+p*p*T.b[1];c.setLineDash([2,2]);c.strokeStyle=INK;c.lineWidth=1;c.beginPath();c.arc(x,y,BR,0,7);c.stroke();c.setLineDash([])}
 if(!ball.sunk&&ball.tun<=0&&phase!=='celebrate'){
  let lift=0,sc=1;if(ball.air>0){const p=1-ball.air/ball.air0;lift=Math.sin(p*Math.PI);sc=1+lift*.6}
  c.fillStyle='rgba(30,30,70,.22)';c.beginPath();c.ellipse(ball.x+1.5,ball.y+2,BR*(1-lift*.3),BR*.8*(1-lift*.3),0,0,7);c.fill();
  const bx=ball.x,by=ball.y-lift*14,r=BR*sc;c.fillStyle='#fff';c.beginPath();c.arc(bx,by,r,0,7);c.fill();c.strokeStyle=INK;c.lineWidth=1.3;c.stroke();
  c.lineWidth=.7;c.beginPath();c.arc(bx,by,r*.62,.3,1.7);c.stroke();c.beginPath();c.moveTo(bx+r*.1,by+r*.75);c.lineTo(bx+r*.7,by+r*.15);c.stroke();
 }
 if(aim.on&&phase==='aim'){const a=aimVals();if(a.pow>.03){
  const dx=Math.cos(a.ang),dy=Math.sin(a.ang),L=26+a.pow*150,col=`hsl(${(55-55*a.pow)|0},95%,${a.pow>.8?45:40}%)`;
  c.setLineDash([4,6]);c.strokeStyle='rgba(80,80,90,.45)';c.lineWidth=1;c.beginPath();c.moveTo(ball.x,ball.y);c.lineTo(ball.x-dx*a.pow*MAXPULL,ball.y-dy*a.pow*MAXPULL);c.stroke();
  c.setLineDash([.5,6]);c.lineCap='round';c.strokeStyle=a.pow>.55?RED:INK;c.lineWidth=2.6;c.beginPath();c.moveTo(ball.x+dx*8,ball.y+dy*8);c.lineTo(ball.x+dx*L,ball.y+dy*L);c.stroke();c.setLineDash([]);
  const ex=ball.x+dx*(L+6),ey=ball.y+dy*(L+6);c.strokeStyle=col;c.lineWidth=2;c.beginPath();c.moveTo(ex,ey);c.lineTo(ex-Math.cos(a.ang-.5)*8,ey-Math.sin(a.ang-.5)*8);c.moveTo(ex,ey);c.lineTo(ex-Math.cos(a.ang+.5)*8,ey-Math.sin(a.ang+.5)*8);c.stroke();
 }}
 for(const f of fx){if(f.t<0)continue;const al=Math.max(0,Math.min(1,(f.life-f.t)/(f.life*.35)));c.globalAlpha=al;c.strokeStyle=f.col;c.fillStyle=f.col;
  if(f.k==='star'){c.lineWidth=1.4;star(c,f.x,f.y,f.s,f.r)}
  else if(f.k==='swirl'){c.lineWidth=1.3;swirl(c,f.x,f.y,f.s*1.4,f.r)}
  else if(f.k==='drop'){c.beginPath();c.arc(f.x,f.y,f.s,0,7);c.fill()}
  else if(f.k==='ring'){c.lineWidth=1.4;c.beginPath();c.arc(f.x,f.y,6+f.t/f.life*24,0,7);c.stroke()}
  else if(f.k==='text'){c.save();c.translate(f.x,f.y-f.t*12);c.rotate(-.08);c.font=`bold ${f.sz||18}px ${HAND}`;c.textAlign='center';c.fillText(f.str,0,0);
   if(f.ul){const w=c.measureText(f.str).width/2;c.lineWidth=1.5;c.beginPath();wl(c,-w,5,w,5,2,3);c.stroke();c.beginPath();wl(c,-w+6,9,w-6,9,2,8);c.stroke()}c.restore()}
 }
 c.globalAlpha=1;
}
function drawScreen(c){
 if(aim.on&&phase==='aim'){const a=aimVals(),w=Math.min(160,W*.4),x=W-w-14,y=H-42,hh=20;
  c.fillStyle=`hsla(${(55-55*a.pow)|0},100%,55%,.6)`;c.fillRect(x,y,w*a.pow,hh);
  c.strokeStyle=INK;c.lineWidth=1.6;c.beginPath();for(const s of rectSegs(x,y,w,hh))wl(c,s[0],s[1],s[2],s[3],1,x);c.stroke();
  c.lineWidth=.8;c.beginPath();for(let i=1;i<10;i++){c.moveTo(x+w*i/10,y+hh);c.lineTo(x+w*i/10,y+hh-(i%5?5:9))}c.stroke();
  c.font=`13px ${HAND}`;c.fillStyle=INK;c.textAlign='right';c.fillText(`power ${Math.round(a.pow*100)}%`,x+w,y-5);c.textAlign='left';}
 if(demo.on){const p=demo.cur;c.save();c.translate(p.x,p.y);
  if(p.down){c.strokeStyle='rgba(208,38,47,.7)';c.lineWidth=2;c.beginPath();c.arc(0,0,16,0,7);c.stroke()}
  c.beginPath();c.moveTo(0,0);c.lineTo(0,22);c.lineTo(6,17);c.lineTo(10,26);c.lineTo(14,24);c.lineTo(10,15);c.lineTo(17,15);c.closePath();
  c.fillStyle='#fff';c.fill();c.strokeStyle='#111';c.lineWidth=1.5;c.stroke();c.restore();}
}
function draw(){
 ctx.setTransform(1,0,0,1,0,0);ctx.drawImage(layer,0,0);
 ctx.setTransform(dpr*S,0,0,dpr*S,dpr*OX,dpr*OY);drawDynamic(ctx);
 ctx.setTransform(dpr,0,0,dpr,0,0);drawScreen(ctx);
}
function updFx(dt){
 for(const f of fx){f.t+=dt;if(f.vx!==undefined){f.x+=f.vx*dt;f.y+=f.vy*dt;f.vx*=.95;f.vy*=.95}if(f.vr)f.r+=f.vr*dt}
 fx=fx.filter(f=>f.t<f.life);
}

// ---------- loop ----------
let last=performance.now(),acc=0,ready=false,ft=0,fn=0,slowCnt=0;
function frame(now){
 let dt=(now-last)/1000;last=now;if(dt>.1)dt=.1;if(dt<0)dt=0;
 ft+=dt;fn++;if(fn>=90){const avg=ft/fn;if(avg>1/45){if(++slowCnt>=2&&q>.55){q=Math.max(.5,q-.2);lowFx=true;resize();slowCnt=0}}else slowCnt=0;ft=0;fn=0}
 if(demo.on)demoUpdate(dt);
 acc+=dt;const h=HOLES[hi];while(acc>=STEP){step(ball,h,STEP,onEv);acc-=STEP}
 if(phase==='roll'){
  if(ball.moving&&ball.air<=0&&ball.tun<=0){const l=trail[trail.length-1];if(!l||Math.hypot(l[0]-ball.x,l[1]-ball.y)>4){trail.push([ball.x,ball.y]);if(trail.length>60)trail.shift()}}
  if(!ball.moving&&ball.tun<=0&&!ball.sunk)shotEnd();
 }
 updFx(dt);draw();
 if(!ready){ready=true;try{parent.postMessage({vcb:"ready"},"*")}catch(e){}}
 requestAnimationFrame(frame);
}
hi=0;ball=newBall(HOLES[0].tee);
resize();
if((location.hash||'')==='#demo')startDemo();else newGame();
requestAnimationFrame(frame);
})();
</script>
</body>
</html>