Back to WoTformer
SOURCE / PINNED RELEASE

Made of little things.

WoTformer

Release
02d5269e1ca4…
Author-recorded commit
Not provided
License
Check the original source

The hash-verified playable HTML, which may contain bundled or minified code. This view does not execute it.

index.html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" /><title>WoTformer</title><meta name="description" content="An 8-bit platformer on the TV, your Web of Trust as the enemies, phones as controllers, nearby or online"><meta name="napplet-id" content="wotformer"><meta name="napplet-requires" content="outbox webrtc"><meta name="napplet-optional" content="identity neighbor relay resource storage"><link rel="icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgAAAAIACAIAAAB7GkOtAAANQUlEQVR42u3dMVVrURCG0SOAggIxFEhAAAVSUlAigAIJFCkiIAIokUCBjFvgIKyzwiQzZ/asT8Cf3Ly7X8d4ftskSQ0bvgJJAoAkCQCSJABIkgAgSQKAJAkAkiQASJIAIEkCgCQJAJIkAEiSACBJAoAkCQCSJABIkgAgSQKAJAkAkiQASJIAIEkCgCQJAJIkAEgSACRJAJAkAUCSBABJEgAkSQCQJAFAkgQASRIAJEkAkCQBQJIEAEkSACRJAJAkAUCSBABJEgAkSQCQJAFAkgQASRIAJEkAkCQBQJIA0OwDVz8/WUkAAIAkAQAAkgQAAEgSAAAgSQAAgCQBAACSBAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAJAxxc0YCQBAAAAkAQAAABAEgAAAABJAAAAACQBAAAAkAQABwBJAHAAkAQABwBJAHAAkAQABwBJAHAAkAQABwBJAHAAkAQABwBJAHAAkAQABwAJAABwAJAAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAAAIAkAAAAAJIA4AAgCQAOAJIA4OoDMNxVzytPAHAAAIAEAAcAAAgAAHAAAIAAAAAAAAAAAgAAAAAAAAgAAAAAAAAgAAAAAAAAgAAAAAAAAAACAAAAAAAACAAAAAAAACAAAAAAAACAAAAAAHgFA0AAAAAAHAAEAAAAwAFAAAAAABwA1BcALf6Dm7zt/V4nAoAAIAAAAAACgAAAAAAIAAIAAAAgAAgAAACAACAAAEACgAAAAAFAAgAABAAJAAAQACQAAEAAkAAAAAFAAgAABAAJAAAQACQAAEAAkAAAAAFAAgAABAApJQDRBwABQAIAAAQAAQAAABAABAAAAEAAEAAAAAABQAAAAAAEAAEAAAAQAAQAAABAABAAAAAAAUAAAAAABAABAAAAEAAEAAAAQAAQAAAAAAFAAACAX6AAIAAAQAKAAAAAAUDqCEA2YAAgAAgAAACAACAAAAAAAoAAAAAACAACAAAAIAAIAAAAgAAgAAAAAAKAAAAAAAgAAgAAACAACAAAkAAgAABAAPAtCAAAEAAkAABAAJAAAAABQAIAAAQACQAAEACkjgD4gzACgAQAAAgAEgAAIABIAACAACABAAACgAQAAAgA8oMDAAAEAAEAAAAQAAQAAABAABAAAAAAAUAAAAAABAABAAAAEAAEAAAAQAAQAAAAAAFAAAAAAAQAAQAAABAABIDlA4AAIAAAAAACgAAAAAAIAAIAAAAgAAgAAACAACAAAEACgAAAAAFAAgAABAAJAAAQACQAAEAAkAAAAAFAAgAABAAJAAAQACQAAEAAkAAAAAFAAgAABICqL6BsBwB/EAYAAgAAAAAAAAgAAAAAAAAgAAAAAAAAgAAAAAAAAAACAAAAAAAACAAAAAAAJAAAAAAAEAAAAAAAAEAAAAAAAAAAAQAAAAAAAAQAAAAAAAAQAAAAAAAAQAAAAAAAAAABAAAAAAAABAAAAAAAABAAMr5QfsZT6ar/gx/OfyAEAAAAwAFAAAAAABwABAAAAMABQAAAAAAcAAQAAADAAUAAAAAAHAAEAAAAwAFAAAAAABwABAAAAMABQAAAAAAcAAQAAADAAUAAAAAAACABAAAAAIAAAAAAAAAAAgAAAAAAAAgAS77Qt+LXDQxJAAAAACQBAAAAkAQAAABAEgAAAABJAAAAACQBAAAAkAQAAABAEgAAAABJAAAAACQAAAAAAJAAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASALAmgBE/4EOAOic37/zB3kAAAAAAMABAAAAAAAAHAAAAAAAAMABAAAAAAAAHAAAAAAAAMABAAAAAAAAHAAAAAAAAMABAAAAEAAcAAAAAAHAAQAAABAAHAAAAAABwAEAAAAQABwAAAAAAcABAAAAEAAcAAAAAAHAAcAfhPEHYfT/v/+Xr1tdMQAAAAACAAAAAAAACAAAAAAAACAAAAAAAACAAAAAAAAAAAIAAAAAAAAIAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvIIBAAAAAAAAAgAAAAAAAAgAAAAAAAAgAFQCIBsY2fJCB8A5AET/ByX6hZttPwAAAAABAAAAAAAABAAAAAAAABAAAAAAAABAAAAAAAAAAAEAAAAAAAAEAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAUAmA7XiYavYBvI67qaJf6LN7Zj/v7PfpFbw2ANO/n2QAZNsPAAAAQAAAAAAAAAABAAAAAAAABAAAAAAAABAAAAAAAABAAAAAAAAAAAEAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD4gzB9AfBKBYDygAQAAABAAAAAAAAAAAEAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAgAAAAAAAAgAAACAtyoABAAAAEAAEAAAAAABQAAAAAAEAAEAAAAQAASASv8Adg9zZXtg3T6v1gYg+j9MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA+LwCAAAAAACfVwAAAAC8EH1eAQAAAPBC9HkFAAAAwAvR5xUAAACAy/0D6PaC8/0A4JIARL/Qq4MBAC84348AAAAAeMH5fgQAAADAC873IwAAAABecL4fAQAAAPCC8/0IAAAAgBec70cAAAAAvOB8PwIAAADgBef7AQAAAAAALzjfDwAAAAAAeMH5fgAAAAAAAAC+HwAAAAAAAIDvBwAAAAAAAOD7AQAAAAAAAAAAAAAAAAAAAAAAAAAAlQCQAOBWPQBIAgAAACAJAAAAgCQAAAAAEgAcAAAgAcABAAASABwAACABwAEAABIAHAAAIAHAAQAAEgAcAAAgAcABAAASABwAACABwAEAABIAHAAkAcABQNKaYOx3OlX1FzoAJAAAAAAAkAAAAAAAQAIAAAAAAAkAAgAAJAAIAJIAIABIAgAAACAJAAAAgCQAAAAAkgAAAABIAgAAACAJAAAAgCQAAAAAkgAAAABIAgAAagMQff5Jyws97oW+fX9MVf2FHv152/1BGABIAAAAAAAgAQAAAACABAAAAAAAEgAAAAAASAAAAAAAIAEAAAAAgAQAAAAAABIAAAAAAEgAAAAAJAAAAAAAkAAAAAAAQAIAAAAAAAkAAAAAACQAAAAAAJAAAAAAhAIgqQ8Y0S/E6vvL/378E5IAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAAAIAkAAAAAJIAAAAASAIAAAAgCQAACP39bMeDpKKNZOfzFvv9+CckAQAAAJAEAAAAQBIAAAAASQAAAAAkAQAAAJAEAAAAQBIAAAAASQDweQEgCQA+LwAkeSH6vACQ5IXo8wJAkheizwsASV6IPi8AJHkh+rwAkOSFCIBU3+fn402q7Lfffvvtv8x+D8B+++23HwAegP32228/ADwA++23334AeAD222+//QDwAOy33377AeAB2G+//fYDwAOw33777QeAB2C//fbbDwAPwH777bcfAB6A/fbbbz8APAD77bfffgB4APbbb7/9APADst9+++0HgB+Q/fbbbz8A7LfffvvtB4D99ttvv/0AsN9+++23HwD222+//fYDwH777bfffgDYb7/99tvvAdhvv/322+8B2G+//fbb7wHYb7/99tvvAdhvv/32A8ADsN9+++0HgAdgv/322w8AD8B+++23HwAegP32228/ADwA++23334AeAD222+//QDwAOy33377qwHgnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzjnnnHPOOeecc84555xzzrm/zx9MsN9+++3vuR8A9ttvv/0A8ADst99++wHgAdhvv/32A8ADsN9+++0HgAdgv/322w8AD8B+++23HwAegP32228/ADwA++23334AeAD222+//QDwAOy33377AeAB2G+//fYDwAOw33777QeAH5D99ttvPwD8gOy33377AeAHZL/99tsPAD8g++23334A+AHZb7/99gPAD8h+++23HwD222+//fYDwH777bfffgDYb7/99tsPAPvtt99++wFgv/32228/AOy33377AeAB2G+//fYDwAOw33777QeAB2C//fbbDwAPwH777bcfAB6A/fbbbz8APAD77bfffgB4APbbb7/9xfb/AsvZdGj9ibvrAAAAAElFTkSuQmCC" type="image/png">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
    
    <script type="module" crossorigin>var Fe=Object.defineProperty;var Be=(n,t,e)=>t in n?Fe(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var c=(n,t,e)=>Be(n,typeof t!="symbol"?t+"":t,e);class $e{constructor(t,e){c(this,"next",0);this.start=t,this.stepDur=e}timeOf(t){return this.start+t*this.stepDur}due(t,e,s=.02){const i={steps:[],skipped:0,late:0},o=t-this.timeOf(this.next);if(o>0&&(i.late=o),o>s){const a=Math.ceil((t-s-this.start)/this.stepDur);i.skipped=Math.max(0,a-this.next),this.next=Math.max(this.next,a)}const r=t+e;for(;this.timeOf(this.next)<r;)i.steps.push({n:this.next,time:this.timeOf(this.next)}),this.next++;return i}}class We{constructor(t,e=4){c(this,"acc",0);c(this,"dropped",0);this.tickMs=t,this.maxSteps=e}advance(t){this.acc+=Math.max(0,t);let e=Math.floor(this.acc/this.tickMs);return this.acc-=e*this.tickMs,e>this.maxSteps&&(this.dropped+=e-this.maxSteps,e=this.maxSteps,this.acc=0),e}reset(){this.acc=0}}function fe(){const n=globalThis.navigator;return((n==null?void 0:n.hardwareConcurrency)??8)<=4||((n==null?void 0:n.deviceMemory)??8)<=2}const He={C:0,D:2,E:4,F:5,G:7,A:9,B:11};function R(n){const t=/^([A-G])(#|b)?(\d)$/.exec(n);if(!t)return 0;let e=He[t[1]]+(t[2]==="#"?1:t[2]==="b"?-1:0);return e+=(Number(t[3])+1)*12,440*Math.pow(2,(e-69)/12)}const Ue={bpm:148,lead:["E5 - G5 - C6 - G5 - A5 G5 E5 - C5 - D5 -","E5 . . C5 A4 - C5 - E5 - D5 C5 D5 . . -","F5 - A5 - C6 - A5 - G5 F5 E5 - D5 - C5 -","D5 . . - G4 - B4 - D5 - F5 - E5 - D5 -","E5 - G5 - C6 - G5 - A5 G5 E5 - G5 - A5 -","C6 . . B5 A5 - E5 - A5 - G5 - E5 - C5 -","F5 - A5 - C6 - A5 - B5 - D6 - B5 - G5 -","C6 - G5 - E5 - G5 - C6 . . . . . - -"].join(" "),harmony:["C5 - E5 - G5 - E5 - F5 E5 C5 - A4 - B4 -","C5 . . A4 E4 - A4 - C5 - B4 A4 B4 . . -","C5 - F5 - A5 - F5 - E5 C5 C5 - A4 - A4 -","B4 . . - D4 - G4 - B4 - D5 - C5 - B4 -","C5 - E5 - G5 - E5 - F5 E5 C5 - E5 - F5 -","A5 . . G5 E5 - C5 - E5 - E5 - C5 - A4 -","C5 - F5 - A5 - F5 - G5 - B5 - G5 - D5 -","E5 - E5 - C5 - E5 - E5 . . . . . - -"].join(" "),bass:["C3 - C3 - G3 - C4 - C3 - G3 - C4 - G3 -","A2 - A2 - E3 - A3 - A2 - E3 - A3 - E3 -","F2 - F2 - C3 - F3 - F2 - C3 - F3 - C3 -","G2 - G2 - D3 - G3 - G2 - D3 - G3 - B2 -","C3 - C3 - G3 - C4 - C3 - G3 - C4 - G3 -","A2 - A2 - E3 - A3 - A2 - E3 - A3 - E3 -","F2 - F2 - C3 - F3 - G2 - G2 - D3 - G3 -","C3 - G2 - C3 - E3 - G3 - E3 - C3 - - -"].join(" "),drums:["k - h - s - h - k - h k s - h -","k - h - s - h - k - h k s - h h","k - h - s - h - k - h k s - h -","k - h - s - h - k k h - s s s s","k - h - s - h - k - h k s - h -","k - h - s - h - k - h k s - h h","k - h - s - h - k - h k s - h -","k - s - k - s - k s k s s s s s"].join(" "),loop:!0},je={bpm:112,lead:["A4 - C5 - E5 . . - D5 - C5 - B4 . . -","G4 - B4 - D5 . . - C5 - B4 - A4 . . -","F4 - A4 - C5 . . - B4 - A4 - G4 - E5 -","E5 . . . D5 . C5 . B4 . . . - - - -"].join(" "),bass:["A2 - - - A2 - E3 - A2 - - - A2 - E3 -","G2 - - - G2 - D3 - G2 - - - G2 - D3 -","F2 - - - F2 - C3 - F2 - - - F2 - C3 -","E2 - - - E2 - B2 - E2 - G#2 - B2 - E3 -"].join(" "),drums:["k - - - h - - - s - - - h - - -","k - - - h - - - s - - - h - h -","k - - - h - - - s - - - h - - -","k - - - h - k - s - - - s - s s"].join(" "),loop:!0},qe={bpm:170,lead:"C5 E5 G5 C6 . - G5 C6 E6 . . . G6 . . . . . . . - - - -",bass:"C3 - - - E3 - - - G3 - - - C4 . . . . . . . - - - -",drums:"k - - - k - - - k - - - s - s s s - - - - - - -",loop:!1},Ye={bpm:120,lead:"E5 . D#5 . D5 . C#5 . C5 . . . B4 . A4 . G#4 . . . . . . . - -",bass:"A2 . . . G#2 . . . G2 . . . F#2 . . . E2 . . . . . . . - -",drums:"k - - - - - - - k - - - - - - - k - - - s - - - - -",loop:!1},Ve={title:je,level:Ue,clear:qe,over:Ye};function Xe(n){const t=n.trim().split(/\s+/),e=[];for(const s of t)s==="."?e.length?e[e.length-1].len++:e.push({hz:0,len:1}):s==="-"?e.push({hz:0,len:1}):e.push({hz:R(s),len:1});return e}function wt(n){const t=[];for(const e of Xe(n)){t.push(e.hz>0?{hz:e.hz,len:e.len}:null);for(let s=1;s<e.len;s++)t.push(null)}return t}function ze(n){const t=wt(n.lead);return{length:t.length,lead:t,harmony:n.harmony?wt(n.harmony):null,bass:wt(n.bass),drums:n.drums.trim().split(/\s+/)}}class Je{constructor(){c(this,"ctx",null);c(this,"master");c(this,"musicBus");c(this,"sfxBus");c(this,"waves",new Map);c(this,"noise");c(this,"voices",null);c(this,"track",null);c(this,"grid",null);c(this,"trackName",null);c(this,"clock",null);c(this,"timer",null);c(this,"lookahead",fe()?.35:.2);c(this,"stats",{lateMs:0,skipped:0,lookaheadMs:0});c(this,"muted",!1)}unlock(){try{if(!this.ctx){const t=globalThis.AudioContext??globalThis.webkitAudioContext;if(!t)return;this.ctx=new t,this.build()}this.ctx.state==="suspended"&&this.ctx.resume()}catch{this.ctx=null}}build(){const t=this.ctx;this.master=t.createGain(),this.master.gain.value=this.muted?0:.5,this.master.connect(t.destination),this.musicBus=t.createGain(),this.musicBus.gain.value=.5,this.musicBus.connect(this.master),this.sfxBus=t.createGain(),this.sfxBus.gain.value=.8,this.sfxBus.connect(this.master);const e=u=>{const f=new Float32Array(48),y=new Float32Array(48);for(let h=1;h<48;h++)f[h]=2/(h*Math.PI)*Math.sin(h*Math.PI*u);return t.createPeriodicWave(f,y)};this.waves.set("pulse12",e(.125)),this.waves.set("pulse25",e(.25)),this.waves.set("pulse50",e(.5));const s=32,i=new Float32Array(s),o=new Float32Array(s);for(let u=1;u<s;u+=2)o[u]=8/(Math.PI*Math.PI*u*u)*((u-1)/2%2?-1:1);this.waves.set("triangle",t.createPeriodicWave(i,o)),this.noise=t.createBuffer(1,t.sampleRate,t.sampleRate);const r=this.noise.getChannelData(0);let a=1,l=0;for(let u=0;u<r.length;u++){if(u%4===0){const d=(a^a>>1)&1;a=a>>1|d<<14,l=a&1?1:-1}r[u]=l*.6}this.voices=this.makeVoices(),this.stats.lookaheadMs=Math.round(this.lookahead*1e3),this.trackName&&this.play(this.trackName)}makeVoices(){const t=this.ctx,e=i=>{const o=t.createOscillator();o.setPeriodicWave(this.waves.get(i));const r=t.createGain();return r.gain.value=0,o.connect(r).connect(this.musicBus),o.start(),{gain:r,freq:o.frequency}},s=(i,o)=>{const r=t.createBufferSource();r.buffer=this.noise,r.loop=!0;const a=t.createBiquadFilter();a.type=i,a.frequency.value=o;const l=t.createGain();return l.gain.value=0,r.connect(a).connect(l).connect(this.musicBus),r.start(),{gain:l,freq:null}};return{lead:e("pulse25"),harmony:e("pulse12"),bass:e("triangle"),kick:e("triangle"),snare:s("lowpass",1800),hat:s("highpass",7e3)}}suspend(){try{this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}catch{}}resume(){try{this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}catch{}}setMuted(t){this.muted=t,this.ctx&&this.master.gain.setTargetAtTime(t?0:.5,this.ctx.currentTime,.02)}toggleMute(){return this.setMuted(!this.muted),this.muted}tone(t,e,s,i,o,r,a){const l=this.ctx,u=l.createOscillator();u.setPeriodicWave(this.waves.get(t)),u.frequency.setValueAtTime(e,s),a&&u.frequency.exponentialRampToValueAtTime(a,s+i);const d=l.createGain();d.gain.setValueAtTime(o,s),d.gain.setValueAtTime(o,s+Math.max(0,i-.02)),d.gain.linearRampToValueAtTime(0,s+i),u.connect(d).connect(r),u.start(s),u.stop(s+i+.02)}hiss(t,e,s,i,o,r=1){const a=this.ctx,l=a.createBufferSource();l.buffer=this.noise,l.playbackRate.value=r;const u=a.createBiquadFilter();u.type=o>2e3?"highpass":"lowpass",u.frequency.value=o;const d=a.createGain();d.gain.setValueAtTime(s,t),d.gain.exponentialRampToValueAtTime(.001,t+e),l.connect(u).connect(d).connect(i),l.start(t,Math.random()*.5),l.stop(t+e+.02)}play(t){if(this.trackName=t,!this.ctx||!this.voices)return;this.silence();const e=Ve[t];this.track=e,this.grid=ze(e),this.clock=new $e(this.ctx.currentTime+.06,60/e.bpm/4),this.timer===null&&(this.timer=window.setInterval(()=>this.pump(),25)),this.pump()}stop(){this.trackName=null,this.track=null,this.clock=null,this.silence(),this.timer!==null&&window.clearInterval(this.timer),this.timer=null}get playing(){return this.trackName}silence(){var s;const t=this.ctx;if(!t||!this.voices)return;const e=t.currentTime;for(const i of Object.values(this.voices))i.gain.gain.cancelScheduledValues(e),i.gain.gain.setValueAtTime(0,e),(s=i.freq)==null||s.cancelScheduledValues(e)}pump(){var l;const t=this.ctx,e=this.track,s=this.grid,i=this.clock,o=this.voices;if(!t||!e||!s||!i||!o)return;const r=i.due(t.currentTime,this.lookahead);this.stats.lateMs=Math.max(r.late*1e3,this.stats.lateMs*.98),this.stats.skipped+=r.skipped;const a=i.stepDur;for(const{n:u,time:d}of r.steps){if(!e.loop&&u>=s.length){this.stop();return}const f=u%s.length,y=s.lead[f];y&&this.note(o.lead,y.hz,d,y.len*a*.88,.16);const h=(l=s.harmony)==null?void 0:l[f];h&&this.note(o.harmony,h.hz,d,h.len*a*.88,.08);const p=s.bass[f];p&&this.note(o.bass,p.hz,d,p.len*a*.88,.38);const g=s.drums[f];g==="k"?this.note(o.kick,150,d,.09,.5,45):g==="s"?this.hit(o.snare,d,.12,.28):g==="h"&&this.hit(o.hat,d,.04,.12)}}note(t,e,s,i,o,r){t.freq.setValueAtTime(e,s),r&&t.freq.exponentialRampToValueAtTime(r,s+i);const a=t.gain.gain;a.setValueAtTime(0,s),a.linearRampToValueAtTime(o,s+.003),a.setValueAtTime(o,s+Math.max(.004,i-.015)),a.linearRampToValueAtTime(0,s+i)}hit(t,e,s,i){const o=t.gain.gain;o.setValueAtTime(i,e),o.exponentialRampToValueAtTime(.001,e+s),o.setValueAtTime(0,e+s+.001)}sfx(t){const e=this.ctx;if(!e)return;const s=e.currentTime+.005,i=this.sfxBus;switch(t){case"jump":this.tone("pulse25",260,s,.16,.18,i,720);break;case"shoot":this.tone("pulse12",1400,s,.07,.15,i,380),this.hiss(s,.05,.08,i,6e3);break;case"stomp":this.tone("pulse50",420,s,.05,.18,i,160),this.tone("pulse50",220,s+.05,.08,.16,i,90),this.hiss(s,.1,.2,i,900);break;case"kill":this.tone("pulse25",900,s,.25,.14,i,120),this.hiss(s,.15,.15,i,2500,.5);break;case"coin":this.tone("pulse25",R("E6"),s,.05,.13,i),this.tone("pulse25",R("G6"),s+.05,.05,.13,i),this.tone("pulse25",R("C7"),s+.1,.18,.12,i);break;case"bump":this.tone("triangle",130,s,.08,.5,i,70);break;case"die":{["B4","F5","F5","F5","E5","D5","C5"].forEach((r,a)=>this.tone("pulse50",R(r),s+.25+a*.11,.1,.15,i)),this.tone("pulse25",900,s,.25,.15,i,200);break}case"1up":["E5","G5","E6","C6","D6","G6"].forEach((o,r)=>this.tone("pulse25",R(o),s+r*.08,.08,.13,i));break;case"join":this.tone("pulse25",R("C6"),s,.06,.13,i),this.tone("pulse25",R("G6"),s+.07,.12,.13,i);break;case"leave":this.tone("pulse25",R("G5"),s,.06,.12,i),this.tone("pulse25",R("C5"),s+.07,.12,.12,i);break;case"pause":["E6","C6","E6","C6"].forEach((o,r)=>this.tone("pulse50",R(o),s+r*.06,.05,.12,i));break;case"move":this.tone("pulse12",1200,s,.03,.1,i);break;case"select":this.tone("pulse25",R("A5"),s,.05,.13,i),this.tone("pulse25",R("A6"),s+.05,.08,.13,i);break;case"face":this.tone("pulse12",R("C6")*(1+Math.random()*.5),s,.04,.06,i);break}}}function Qe(){const n=new Map;function t(i,o){if(n.has(i))throw new Error(`NAP domain "${i}" is already registered`);n.set(i,o)}function e(i){const o=i.type.indexOf(".");if(o<=0)return!1;const r=i.type.slice(0,o),a=n.get(r);return a?(a(i),!0):!1}function s(){return Array.from(n.keys())}return{registerNap:t,dispatch:e,getRegisteredDomains:s}}var Ze=Qe(),at=Ze.registerNap,ts="relay";function es(){var t;const n=window;if(!((t=n.napplet)!=null&&t.relay))throw new Error("window.napplet.relay is unavailable -- runtime did not inject the relay domain");return n.napplet.relay}function ue(n,t,e,s){return es().subscribe(n,t,e,s)}at(ts,n=>{});var ss="identity";function Gt(){var t;const n=window;if(!((t=n.napplet)!=null&&t.identity))throw new Error("window.napplet.identity is unavailable -- runtime did not inject this domain");return n.napplet.identity}function is(){return Gt().getPublicKey()}function de(){return Gt().getProfile()}function pe(){return Gt().getFollows()}at(ss,n=>{});var ns="storage";function me(){var t;const n=window;if(!((t=n.napplet)!=null&&t.storage))throw new Error("window.napplet.storage is unavailable -- runtime did not inject this domain");return n.napplet.storage}function os(n){return me().getItem(n)}function rs(n,t){return me().setItem(n,t)}at(ns,n=>{});var as="resource";function ge(){var t;const n=window;if(!((t=n.napplet)!=null&&t.resource))throw new Error("window.napplet.resource is unavailable -- runtime did not inject this domain");return n.napplet.resource}function ls(){return ge().info()}function cs(n,t){return ge().bytes(n,t)}at(as,n=>{});var hs="outbox";function Pt(){var t;const n=window;if(!((t=n.napplet)!=null&&t.outbox))throw new Error("window.napplet.outbox is unavailable -- runtime did not inject this domain");return n.napplet.outbox}function fs(n,t){return Pt().query(n,t)}function dt(n,t){return Pt().subscribe(n,t)}function bt(n,t){return Pt().publish(n,t)}at(hs,n=>{});function tt(){const n=globalThis.napplet,t=n==null?void 0:n.webrtc;if(t&&typeof t.open=="function"&&typeof t.send=="function"&&typeof t.onEvent=="function")return t}function ye(n){return typeof n.admit=="function"}const it="wotformer",xt="bbb5dda0e15567979f0543407bdc2033d6f0bbb30f72512a981cfdb2f09e2747",kt=`35129:${xt}:${it}`,_t=35050,J=30078,Mt=`${it}:`;let pt=!1;const et="soy.app-data/1",Ct="tvs",ot=`${it}.tv`,ke="wss://relay.napplet.soy",we=90,Ft=600,us=200,ds=48;function Tt(){return pt?Ft:we}function be(n){return typeof n!="string"?"":n.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,ds)}const I=(n,t)=>n.tags.find(e=>e[0]===t),nt=(n,t)=>{const e=Number(n);return Number.isInteger(e)&&e>=0&&e<=64?e:t};function ps(n,t){var u,d,f,y,h,p,g,v;if(n.kind===J&&((u=I(n,"L"))==null?void 0:u[1])===et)return bs(n,t);if(n.kind!==_t&&n.kind!==J||!n.tags.find(M=>M[0]==="a"&&M[1]===kt)||((d=I(n,"version"))==null?void 0:d[1])!=="1")return null;const s=(f=I(n,"d"))==null?void 0:f[1],i=n.kind===J?s!=null&&s.startsWith(Mt)?s.slice(Mt.length):void 0:s,o=(y=I(n,"room"))==null?void 0:y[1];if(!i||!o||o.length>128||i.length>64)return null;const r=((h=I(n,"status"))==null?void 0:h[1])??"open";if(!["open","full","closed"].includes(r))return null;const a=I(n,"capacity"),l=Number(((p=I(n,"expiration"))==null?void 0:p[1])??n.created_at+we);return{key:`${n.pubkey}:${i}`,game:i,room:o,host:n.pubkey,title:be((g=I(n,"title"))==null?void 0:g[1])||"A screen",status:r,keyed:((v=I(n,"identity"))==null?void 0:v[1])==="account",max:nt(a==null?void 0:a[1],4),taken:nt(a==null?void 0:a[2],0),place:t,createdAt:n.created_at,expires:l}}function vt(n){const t=Math.floor(Date.now()/1e3);return{kind:_t,content:"",created_at:t,tags:[["d",n.game],["a",kt,"","protocol"],["version","1"],["gate","open"],["room",n.room],["capacity",String(n.max),String(n.taken)],["status",n.status],["identity",n.keyed?"account":"ephemeral"],["title",n.title],["expiration",String(t+Tt())],["client",it]]}}function ms(n){const t=s=>{var i;return((i=n.tags.find(o=>o[0]===s))==null?void 0:i[1])??""},e=n.tags.find(s=>s[0]==="capacity")??[];return{game:t("d"),room:t("room"),status:t("status"),title:t("title"),keyed:t("identity")==="account",max:nt(e[1],4),taken:nt(e[2],0)}}function gs(n){return{...n,kind:J,tags:n.tags.map(t=>t[0]==="d"?["d",Mt+t[1]]:t)}}let Ut=null,jt=null;const ve=new Map;function ys(){return Ut??(Ut=(async()=>{var t,e;const n=(t=window.napplet)==null?void 0:t.shell;if(!(n!=null&&n.ready))return null;try{const s=await Promise.race([n.ready(),new Promise(a=>setTimeout(()=>a(null),2e3))]),i=(e=s==null?void 0:s.capabilities)==null?void 0:e.appData;if(!i||i.profile!==et||typeof i.scope!="string"||!i.scope)return null;const o=a=>Array.isArray(a)?a.filter(l=>typeof l=="string"):[],r=o(i.defaultRelays);return{scope:i.scope,relays:r.length?r:o(i.relays).slice(0,1)}}catch{return null}})()),Ut}async function ks(n){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,"0")).join("")}async function qt(){const n=[`${xt}:35129:${it}`,kt,`${xt}:${it}`];return Promise.all(n.map(async t=>({scope:await ks(JSON.stringify([et,t])),relays:[ke]})))}function ws(n,t){var o;const e=ms(n),s=e.status==="closed",i=Number(((o=n.tags.find(r=>r[0]==="expiration"))==null?void 0:o[1])??0);return{kind:J,created_at:n.created_at,tags:[["d",`${et}:${t.scope}:${Ct}:${e.game}`],["s",t.scope],["c",Ct],["L",et],["l",ot,et],["v","1"]],content:JSON.stringify({schema:ot,version:1,title:e.title||"A screen",previous:ve.get(e.game)??null,deleted:s,data:s?null:{room:e.room,status:e.status,keyed:e.keyed,max:e.max,taken:e.taken,expires:i}})}}function bs(n,t){var a,l,u;if(((a=I(n,"c"))==null?void 0:a[1])!==Ct||((l=I(n,"l"))==null?void 0:l[1])!==ot)return null;const e=(((u=I(n,"d"))==null?void 0:u[1])??"").split(":").pop()??"";let s;try{s=JSON.parse(n.content)}catch{return null}if(s.schema!==ot||!e||e.length>64)return null;const i=s.data??{},o=typeof i.room=="string"?i.room:"",r=s.deleted===!0?"closed":i.status;return!o&&r!=="closed"||o.length>128||!["open","full","closed"].includes(r)?null:{key:`${n.pubkey}:${e}`,game:e,room:o,host:n.pubkey,title:be(s.title)||"A screen",status:r,keyed:i.keyed===!0,max:nt(String(i.max),4),taken:nt(String(i.taken),0),place:t,createdAt:n.created_at,expires:typeof i.expires=="number"?i.expires:n.created_at+Ft}}async function Yt(n,t){const e=[],s=(l,u)=>(l&&e.push(`${u}: ${l}`),l),i=()=>`Couldn't list the screen. ${e.join(" · ")}`,o=async(l,u)=>{var d;try{const f=u!==void 0?await bt(l,{relays:u,toOutbox:!1}):n.kind==="neighborhood"?await bt(l,{relays:[n.address],toOutbox:!1}):await bt(l);return f.ok?{problem:null,id:((d=f.event)==null?void 0:d.id)??f.eventId}:{problem:f.error??"publish failed"}}catch(f){return{problem:f instanceof Error?f.message:"publish failed"}}},r=async l=>{pt=!0;const{problem:u,id:d}=await o(ws(vt(t),l),l.relays);return u||(d&&ve.set(t.game,d),jt=l,null)};if(n.kind==="online"){const l=jt??await ys();if(l)return s(await r(l),"app-data")?i():null;const u=tt();if(u&&!ye(u)){for(const[d,f]of(await qt()).entries())if(!s(await r(f),`app-data ${d+1}`))return null}}if(!pt){const l=s((await o(vt(t))).problem,"kind 35050");if(!l)return null;if(!/kind/i.test(l))return i();pt=!0}const a=s((await o(gs(vt(t)))).problem,"kind 30078");if(!a)return null;if(!/kind/i.test(a)||n.kind!=="online"||e.some(l=>l.startsWith("app-data")))return i();for(const[l,u]of(await qt()).entries())if(!s(await r(u),`app-data ${l+1}`))return null;return i()}class vs{constructor(){c(this,"follows",new Set);c(this,"fof",new Set)}async load(t){var s;try{this.follows=new Set(await pe())}catch{return}t();const e=[...this.follows].slice(0,us);if(e.length!==0)try{const i=await fs([{kinds:[3],authors:e}]);for(const o of i.events)for(const r of((s=o.event)==null?void 0:s.tags)??[])r[0]==="p"&&r[1]&&!this.follows.has(r[1])&&this.fof.add(r[1]);t()}catch{}}tier(t){return this.follows.has(t)?0:this.fof.has(t)?1:2}}class Es{constructor(t){c(this,"adverts",new Map);c(this,"subs",[]);this.onChange=t}open(t,e){this.close();const s=Math.floor(Date.now()/1e3)-Ft,i={kinds:[_t,J],"#a":[kt],since:s};for(const o of t){const r=a=>this.take(a,o);try{if(o.kind==="neighborhood")this.subs.push(ue([i],r,()=>{},{relay:o.address}));else{const a=dt([{kinds:[J],"#l":[ot],since:s}],{relays:[ke]});a.on("event",r),this.subs.push(a);const l=dt([i]);l.on("event",r),this.subs.push(l);const u=[...e.follows,...e.fof].slice(0,500);if(u.length>0){const d=dt([i],{authors:u});d.on("event",r),this.subs.push(d)}}}catch{}}}close(){for(const t of this.subs.splice(0))t.close()}take(t,e){const s=t.event;if(!s)return;const i=ps(s,e);if(!i)return;const o=this.adverts.get(i.key);o&&o.createdAt>=i.createdAt||(this.adverts.set(i.key,i),this.onChange())}get(t){return this.adverts.get(t)}list(t){const e=Math.floor(Date.now()/1e3),s=new Map;for(const i of this.adverts.values()){const o=`${i.host}|${i.place.key}`,r=s.get(o);(!r||i.createdAt>r.createdAt)&&s.set(o,i)}return[...s.values()].filter(i=>i.status!=="closed"&&i.expires>e).map(i=>({...i,tier:t.tier(i.host)})).sort((i,o)=>i.tier-o.tier||o.createdAt-i.createdAt)}}const b={LEFT:1,RIGHT:2,UP:4,DOWN:8,A:16,B:32,START:64,SELECT:128},st=[b.A,b.B,b.START,b.SELECT,b.UP],Ss=1500;class As{constructor(){c(this,"held",0);c(this,"seq",0);c(this,"presses",st.map(()=>0))}set(t,e){if((this.held&t)!==0===e)return!1;if(e){this.held|=t;const i=st.indexOf(t);i>=0&&(this.presses[i]=this.presses[i]+1&255)}else this.held&=~t;return!0}setMask(t,e){let s=!1;for(let i=1;i<=128;i<<=1)e&i&&(s=this.set(i,(t&i)!==0)||s);return s}releaseAll(){return this.setMask(0,255)}message(){return this.seq++,{s:this.seq,b:this.held,p:[...this.presses]}}}class xs{constructor(t){c(this,"lastSeq",-1);c(this,"held",0);c(this,"prevHeld",0);c(this,"counts",null);c(this,"pending",0);c(this,"lastHeardMs");this.lastHeardMs=t}receive(t,e){if(this.lastHeardMs=Math.max(this.lastHeardMs,e),!(t.s<=this.lastSeq)){if(this.lastSeq=t.s,this.counts)for(let s=0;s<st.length;s++){const i=(t.p[s]??0)-(this.counts[s]??0)&255;i>0&&i<64&&(this.pending|=st[s])}this.counts=st.map((s,i)=>t.p[i]??0),this.held=t.b&255}}setHeld(t,e){this.lastHeardMs=e,this.held=t&255}stale(t){return t-this.lastHeardMs>Ss}tick(t){this.stale(t)&&(this.held=0);const e=(this.held&~this.prevHeld|this.pending)&255;return this.pending=0,this.prevHeld=this.held,{held:this.held|e,pressed:e}}}const mt=4,O="keyboard";class Ms{constructor(t=mt){c(this,"seats");this.max=t,this.seats=Array.from({length:t},()=>null)}get(t){return this.seats.find(e=>(e==null?void 0:e.sid)===t)??void 0}get count(){return this.seats.filter(Boolean).length}get full(){return this.count>=this.max}join(t,e,s,i){const o=this.get(t);if(o)return e&&(o.name=e),s&&(o.pubkey=s),o.tracker.lastHeardMs=Math.max(o.tracker.lastHeardMs,i),{seat:o,fresh:!1};const r=this.seats.indexOf(null);if(r<0)return null;const a={sid:t,slot:r,name:e||`P${r+1}`,pubkey:s,tracker:new xs(i),echo:null};return this.seats[r]=a,{seat:a,fresh:!0}}leave(t){const e=this.seats.findIndex(i=>(i==null?void 0:i.sid)===t);if(e<0)return null;const s=this.seats[e];return this.seats[e]=null,s}prune(t,e){const s=[];for(let i=0;i<this.seats.length;i++){const o=this.seats[i];o&&o.sid!==O&&t-o.tracker.lastHeardMs>e&&(s.push(o),this.seats[i]=null)}return s}}function Bt(){const n=globalThis.napplet,t=n==null?void 0:n.neighbor;if(t&&typeof t.list=="function")return t}const Cs="nearby";function ct(n){return n.autoAccept&&n.name===Cs}const Ts={kind:"online",key:"online",label:"Online"};function Ls(){var t;const n=globalThis.napplet;return typeof((t=n==null?void 0:n.outbox)==null?void 0:t.publish)=="function"}async function Ee(){const n=[],t=Bt();if(t){let e=[];try{e=await t.list()}catch{}const s=(Array.isArray(e)?e:[]).filter(r=>typeof r.address=="string"&&r.address),i=s.filter(ct),o=s.filter(r=>!ct(r)).sort((r,a)=>r.name.localeCompare(a.name));for(const r of[...i,...o])n.push({kind:"neighborhood",key:r.address,label:ct(r)?"Nearby":r.name,address:r.address,nearby:ct(r),...typeof r.reachable=="number"?{reachable:r.reachable}:{}})}return Ls()&&n.push(Ts),n}function Rs(n){return n.kind==="neighborhood"?{neighborhood:n.address}:{relays:Os}}const Os=["wss://nos.lol","wss://relay.damus.io","wss://relay.primal.net"],Ds="wotformer",Ks="wotformer/1",Ns=2,Is=["loading","lobby","play","pause","clear","over"],Gs=["hurt","die","coin","stomp","kill","1up","clear","over","join"];function Se(n=6){const t=crypto.getRandomValues(new Uint8Array(n));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}const Ps=n=>typeof n=="number"&&Number.isFinite(n),H=(n,t,e)=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e,Lt=n=>typeof n=="string"&&n.length>0&&n.length<64,_s=n=>n===void 0||typeof n=="string"&&n.length<=64,Rt=n=>n===void 0||Ps(n);function Fs(n){if(!n||typeof n!="object")return!1;const t=n;return Lt(t.c)&&H(t.s,0,7)&&H(t.l,0,99)&&H(t.sc,0,1e9)&&H(t.k,0,1e6)&&Rt(t.et)&&Rt(t.eh)}function Bs(n){if(!n||typeof n!="object")return!1;const t=n;return H(t.i,0,1e12)&&typeof t.c=="string"&&t.c.length<64&&Gs.includes(t.k)}function $s(n){let t;if(typeof n=="string")try{t=JSON.parse(n)}catch{return null}else t=n;if(!t||typeof t!="object"||t.v!==1||!Lt(t.sid))return null;switch(t.t){case"join":return _s(t.name)?t:null;case"in":return H(t.s,0,Number.MAX_SAFE_INTEGER)&&H(t.b,0,255)&&Array.isArray(t.p)&&t.p.length===st.length&&t.p.every(e=>H(e,0,255))&&Rt(t.ts)?t:null;case"st":return Is.includes(t.ph)&&H(t.lv,0,9999)&&Array.isArray(t.pl)&&t.pl.length<=8&&t.pl.every(Fs)&&Array.isArray(t.ev)&&t.ev.length<=32&&t.ev.every(Bs)?t:null;case"full":return Lt(t.to)?t:null;case"bye":return t;default:return null}}class rt{constructor(t){c(this,"sid",Se());c(this,"sessionId",null);c(this,"events",null);c(this,"inFlight",0);c(this,"closed",!1);c(this,"peers",new Set);c(this,"admits",!1);c(this,"v149",!1);c(this,"hostNamed",!1);c(this,"sendMs",0);this.handlers=t}static available(){return tt()!==void 0}async open(t){var i;const e=tt();if(!e)return"This shell has no direct connections (NAP-WEBRTC).";const s=ye(e);this.v149=s,this.admits=t.admit&&s,this.hostNamed=!!t.host&&s,this.events=e.onEvent(o=>this.onEvent(o));try{const o=s?Rs(t.place):void 0,{session:r}=await e.open({scope:{type:"room",room:t.room,...this.hostNamed?{peers:[t.host]}:{}},channel:Ds,protocol:Ks,...s?{identity:t.identity}:{},...this.admits?{admission:"napplet"}:{},...o?{signaling:o}:{}});return this.closed?(e.close(r.id).catch(()=>{}),null):(this.sessionId=r.id,null)}catch(o){return(i=this.events)==null||i.close(),this.events=null,o instanceof Error?`Couldn't connect: ${o.message}`:"Couldn't connect."}}onEvent(t){var e,s,i,o;if(!(!this.sessionId||t.sessionId!==this.sessionId))switch(t.type){case"request":{const{pubkey:r}=t,a=((s=(e=this.handlers).onRequest)==null?void 0:s.call(e,r))??!1;(o=(i=tt())==null?void 0:i.admit)==null||o.call(i,this.sessionId,r,a).catch(()=>{});return}case"peer":{const r=t;r.state==="joined"?(this.peers.add(r.pubkey),this.handlers.onJoined(r.pubkey)):r.state==="left"?(this.peers.delete(r.pubkey),this.handlers.onLeft(r.pubkey)):r.state==="failed"&&(this.peers.delete(r.pubkey),this.handlers.onFailed(r.pubkey,r.reason??"failed"));return}case"message":{const r=t,a=$s(r.payload);a&&a.sid!==this.sid&&this.handlers.onMessage(a,r.from);return}case"closed":{const r=t;this.peers.clear(),this.handlers.onClosed(r.reason?`Connection ended: ${r.reason}`:"Connection ended.");return}default:return}}get canSendGame(){return this.inFlight<Ns}send(t){const e=tt();if(!e||!this.sessionId||this.peers.size===0)return;const s=performance.now();this.inFlight++,e.send(this.sessionId,{v:1,sid:this.sid,...t}).then(()=>{const i=performance.now()-s;this.sendMs=this.sendMs?this.sendMs*.8+i*.2:i}).catch(()=>{}).finally(()=>{this.inFlight--})}close(){var e,s;this.closed=!0,(e=this.events)==null||e.close(),this.events=null,this.peers.clear();const t=this.sessionId;this.sessionId=null,t&&((s=tt())==null||s.close(t).catch(()=>{}))}}const Ws=36,ht=(n,t)=>(n.x-t.x)**2+(n.y-t.y)**2;function Hs(n,t,e){if(Math.hypot(n,t)<e)return 0;let s=Math.atan2(t,n)*180/Math.PI;s<0&&(s+=360);const i=Ws/2,o=[45,135,225,315],r=[b.RIGHT|b.DOWN,b.DOWN|b.LEFT,b.LEFT|b.UP,b.UP|b.RIGHT];for(let a=0;a<4;a++)if(Math.abs(s-o[a])<=i)return r[a];return s<45||s>315?b.RIGHT:s<135?b.DOWN:s<225?b.LEFT:b.UP}function Vt(n,t){return n.x<0||n.y<0||n.x>t.w||n.y>t.h?0:n.x<t.dpadEdge?Hs(n.x-t.dpad.x,n.y-t.dpad.y,t.dead):n.x<t.buttonsEdge?ht(n,t.select)<=ht(n,t.start)?b.SELECT:b.START:ht(n,t.a)<=ht(n,t.b)?b.A:b.B}function Us(n,t,e,s){return{dpadEdge:(n+t)/2,buttonsEdge:(e+s)/2}}const m={black:"#000000",white:"#fcfcfc",skyDay:"#5c94fc",skyDusk:"#6844fc",skyNight:"#000000",brick:"#c84c0c",brickDark:"#7c0800",brickLight:"#fcbcb0",q:"#fc9838",qDark:"#c84c0c",pipe:"#00a800",pipeLight:"#b8f818",pipeDark:"#005800",coin:"#f8b800",coinLight:"#fce0a8",hill:"#00a800",hillDark:"#005800",bush:"#80d010",cloudShade:"#a4e4fc",skin:"#fcbcb0",boot:"#7c3c00",gray:"#7c7c7c"},U=[{name:"RED",main:"#e40058",dark:"#880014"},{name:"BLUE",main:"#0078f8",dark:"#0000bc"},{name:"GREEN",main:"#00b800",dark:"#005800"},{name:"GOLD",main:"#f8b800",dark:"#ac7c00"}];function Z(n,t){const e=document.createElement("canvas");return e.width=n,e.height=t,e}function Ae(n,t,e){const s=Z(e,n.length),i=s.getContext("2d");return n.forEach((o,r)=>{for(let a=0;a<e;a++){const l=t[o[a]??"."];l&&(i.fillStyle=l,i.fillRect(a,r,1,1))}}),s}const js=["....KKKK....","..KKCCCCKK..",".KCCCCCCCCK.",".KCWWWWWWCK.","KCWWKWWKWWCK","KCWWKWWKWWCK",".KCWWWWWWCK.","..KKCCCCKK.."],qs=[".KSKDDDDKSK.","KSSKDCCDKSSK",".KKKDCCDKKK.","...KDDDDK..."],Ys=["KSK.DDDD.KSK","KSKKDCCDKKSK",".K.KDCCDK.K.","...KDDDDK..."],Vs={stand:["..KDDKKDDK..","..KDDKKDDK..",".KBBBK.KBBBK",".KKKKK.KKKKK"],walk1:["..KDDKKDDK..",".KDDK..KDDK.","KBBBK...KBBK","KKKKK...KKKK"],walk2:["...KDDDDK...","...KDDDK....","...KBBBK....","...KKKKK...."],jump:[".KDDK..KDDK.","KBBK....KBBK","KKKK....KKKK","............"]};function Xs(n){const t=Z(n.width,n.height),e=t.getContext("2d");return e.translate(n.width,0),e.scale(-1,1),e.drawImage(n,0,0),t}function zs(n){const t={K:m.black,C:n.main,D:n.dark,W:m.white,S:m.skin,B:m.boot},e={};for(const s of["stand","walk1","walk2","jump"]){const i=[...js,...s==="jump"?Ys:qs,...Vs[s]],o=Ae(i,t,12);e[s]=[o,Xs(o)]}return{poses:e}}const Js=[["...KGGGGGGK...","..KGGGGGGGGK..",".KGLKGGGGKLGK.","..KGGGGGGGGK..","...KGGKKGGK...","..KGGK..KGGK..","..KKKK..KKKK..",".............."],["...KGGGGGGK...","..KGGGGGGGGK..",".KGLKGGGGKLGK.","..KGGGGGGGGK..","...KGGKKGGK...","....KGGKGGK...","....KKKKKKK...",".............."]];function Xt(n,t){return Js.map(e=>Ae(e,{K:m.black,G:n,L:t},14))}function V(n){const t=Z(16,16);return n(t.getContext("2d")),t}function zt(n){const t=n?"#3c7cfc":m.brick,e=n?"#0000a8":m.brickDark,s=n?"#a4e4fc":m.brickLight,i=(h,p,g,v,M,lt)=>{h.fillStyle=p,h.fillRect(g,v,M,lt)},o=V(h=>{i(h,t,0,0,16,16),i(h,s,0,0,16,1),i(h,s,0,0,1,16),i(h,m.black,0,15,16,1),i(h,m.black,15,0,1,16),i(h,m.black,9,0,1,8),i(h,m.black,1,8,14,1),i(h,m.black,4,9,1,6),i(h,e,10,1,4,1)}),r=V(h=>{i(h,t,0,0,16,16),i(h,s,0,0,16,1);for(const p of[3,7,11,15])i(h,m.black,0,p,16,1);for(const[p,g]of[[7,0],[15,0],[3,4],[11,4],[7,8],[15,8],[3,12],[11,12]])i(h,m.black,p,g,1,3)}),a=h=>V(p=>{i(p,m.black,0,0,16,16),i(p,m.q,1,1,14,14),i(p,m.qDark,1,14,14,1),i(p,m.qDark,14,1,1,14);for(const[g,v]of[[2,2],[13,2],[2,13],[13,13]])i(p,m.black,g,v,1,1);i(p,h,5,3,6,2),i(p,h,4,4,2,3),i(p,h,10,4,2,4),i(p,h,8,7,3,2),i(p,h,7,8,2,2),i(p,h,7,11,2,2),i(p,m.qDark,6,5,1,1)}),l=[a(m.white),a(m.coinLight),a(m.qDark),a(m.coinLight)],u=V(h=>{i(h,m.black,0,0,16,16),i(h,m.qDark,1,1,14,14);for(const[p,g]of[[2,2],[13,2],[2,13],[13,13]])i(h,m.black,p,g,1,1)}),d=V(h=>{i(h,e,0,0,16,16),i(h,t,1,1,14,14),i(h,s,1,1,13,2),i(h,s,1,1,2,13),i(h,m.black,15,0,1,16),i(h,m.black,0,15,16,1),i(h,e,4,4,8,8),i(h,t,5,5,6,6)}),f=(h,p)=>V(g=>{const v=p?0:h?2:0,M=p||h?16:14;i(g,m.black,v,0,M-v,16),i(g,m.pipe,v+(h?1:0),p?1:0,M-v-1,p?14:16),h?(i(g,m.pipeLight,v+3,p?2:0,3,p?12:16),i(g,m.pipeDark,v+8,p?2:0,1,p?12:16)):(i(g,m.pipeDark,M-5,p?2:0,3,p?12:16),i(g,m.pipeLight,2,p?2:0,1,p?12:16)),p&&i(g,m.black,v,15,M-v,1)}),y=h=>V(p=>{const g=8-Math.ceil(h/2);i(p,m.black,g,2,h,12),h<=2?i(p,m.coin,g,3,h,10):(i(p,m.coin,g+1,3,h-2,10),h>4&&i(p,m.coinLight,g+2,4,1,8))});return{ground:o,brick:r,question:l,used:u,block:d,pipeTL:f(!0,!0),pipeTR:f(!1,!0),pipeL:f(!0,!1),pipeR:f(!1,!1),coin:[y(8),y(6),y(2),y(6)]}}const Ot=16;function Qs(n){const t=Math.min(n.width,n.height),e=(n.width-t)/2,s=(n.height-t)/2;let i=n,o=t,r=e,a=s;for(;o>56;){const y=Math.max(56,Math.floor(o/2)),h=Z(y,y),p=h.getContext("2d");p.imageSmoothingEnabled=!0,p.imageSmoothingQuality="high",p.drawImage(i,r,a,o,o,0,0,y,y),i=h,o=y,r=0,a=0}const l=Z(14,14),u=l.getContext("2d");u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high",u.drawImage(i,r,a,o,o,0,0,14,14);const d=u.getImageData(0,0,14,14),f=6;for(let y=0;y<d.data.length;y+=4){for(let h=0;h<3;h++){const p=d.data[y+h];d.data[y+h]=Math.round(Math.round(p/255*(f-1))*(255/(f-1)))}d.data[y+3]=255}return u.putImageData(d,0,0),xe(l)}function xe(n){const t=Z(Ot,Ot),e=t.getContext("2d");e.fillStyle=m.black,e.fillRect(1,0,14,16),e.fillRect(0,1,16,14),e.drawImage(n,1,1),e.clearRect(0,0,1,1),e.clearRect(15,0,1,1),e.clearRect(0,15,1,1),e.clearRect(15,15,1,1),e.fillStyle=m.black;for(const[s,i]of[[1,1],[14,1],[1,14],[14,14]])e.fillRect(s,i,1,1);return t}function Zs(n){const t=Z(14,14),e=t.getContext("2d");return e.fillStyle=`hsl(${n} 60% 45%)`,e.fillRect(0,0,14,14),e.fillStyle=m.black,e.fillRect(2,4,10,3),e.fillStyle=m.white,e.fillRect(3,5,2,1),e.fillRect(9,5,2,1),e.fillStyle=m.black,e.fillRect(5,10,4,1),e.fillStyle=m.white,e.fillRect(6,0,2,1),e.fillRect(8,1,1,1),e.fillRect(7,2,1,1),xe(t)}function G(n,t){var s;const e=globalThis.napplet;return typeof((s=e==null?void 0:e[n])==null?void 0:s[t])=="function"}async function ti(){try{if(G("identity","getPublicKey"))return(await is()||"").toLowerCase()}catch{}return""}function Et(){return G("outbox","subscribe")||G("relay","subscribe")}const ei=8*1024*1024,Jt="wot-faces:";function si(n,t){try{if(G("outbox","subscribe")){const e=[...new Set(n.flatMap(i=>i.authors??[]))],s=dt(n,e.length?{authors:e}:void 0);return s.on("event",i=>{i!=null&&i.event&&t(i.event)}),()=>s.close()}if(G("relay","subscribe")){const e=ue(n,s=>(s==null?void 0:s.event)&&t(s.event),()=>{});return()=>e.close()}}catch{}return()=>{}}async function ii(n){try{return await createImageBitmap(n,{resizeWidth:64,resizeQuality:"medium"})}catch{return createImageBitmap(n)}}class ni{constructor(t){c(this,"pictures",new Map);c(this,"https",null);this.self=t}async ownFollows(t){if(!(t!==this.self||!G("identity","getFollows")))try{const e=await pe();return e.length?e:void 0}catch{return}}stream(t,e){return si(t.map(s=>({kinds:s.kinds,authors:s.authors})),e)}httpsAllowed(){return this.https??(this.https=(async()=>{if(!G("resource","info"))return!0;try{return(await ls()).schemes.some(e=>e.scheme==="https"&&e.enabled!==!1)}catch{return!0}})()),this.https}async remembered(t){if(!G("storage","getItem"))return[];try{const e=await os(Jt+t),s=e?JSON.parse(e):[];return Array.isArray(s)?s.filter(i=>{const o=i;return!!o&&typeof o.pubkey=="string"&&typeof o.name=="string"&&typeof o.picture=="string"}).slice(0,60):[]}catch{return[]}}remember(t,e){if(G("storage","setItem"))try{rs(Jt+t,JSON.stringify(e.slice(0,60))).catch(()=>{})}catch{}}loadImage(t,e){let s=this.pictures.get(t);return s||(s=this.decode(t,e),this.pictures.set(t,s),s.catch(()=>{e.aborted&&this.pictures.delete(t)})),s}async decode(t,e){if(!G("resource","bytes"))throw new Error("no resource domain");const s=await cs(t,{signal:e});if(s.size===0||s.size>ei)throw new Error("bad size");if(s.type.includes("svg")||s.type&&!s.type.startsWith("image/")&&s.type!=="application/octet-stream")throw new Error("not a raster image");const i=await ii(s);try{if(i.width<8||i.height<8)throw new Error("too small");return Qs(i)}finally{i.close()}}}const oi=1e3,ri=300,ai=1e4,li=35e3,ci=4e3,hi={hurt:[60],die:[140,60,140],coin:[12],stomp:[35],kill:[25],"1up":[40,40,40,40,80],clear:[60,40,60,40,220],over:[400],join:[25,40,25]};function fi(n){const t=Math.max(0,Math.floor(Date.now()/1e3)-n);return t<60?`${t} s ago`:t<3600?`${Math.floor(t/60)} m ago`:`${Math.floor(t/3600)} h ago`}const _=n=>document.getElementById(n);class ui{constructor(t){c(this,"life",new AbortController);c(this,"timers",[]);c(this,"pad",new As);c(this,"mode","finding");c(this,"circle",new vs);c(this,"lobby",new Es(()=>this.renderList()));c(this,"places",[]);c(this,"target",null);c(this,"link",null);c(this,"displayKey","");c(this,"displaySid","");c(this,"connected",!1);c(this,"lastJoin",0);c(this,"lastSend",0);c(this,"sendPending",!1);c(this,"lastHeard",0);c(this,"lastListed",0);c(this,"lastEv",-1);c(this,"slot",-1);c(this,"name","");c(this,"rtt",0);c(this,"pointers",new Map);c(this,"keys",0);c(this,"away",!1);c(this,"ui",{root:_("ctl"),status:_("ctlStatus"),who:_("ctlWho"),stats:_("ctlStats"),picker:_("picker"),list:_("displays"),pickerNote:_("pickerNote"),leave:_("ctlLeave"),pad:_("pad"),dpad:_("dpad")});c(this,"neighborSub",null);c(this,"layoutCache",null);c(this,"debug",!!window.__WOT_DEBUG__);c(this,"chordTimer",null);this.onExit=t,window.__WOT_ROLE__&&(window.__wotController=this)}get on(){return{signal:this.life.signal}}every(t,e){this.timers.push(window.setInterval(t,e))}endLife(){this.life.abort();for(const t of this.timers.splice(0))window.clearInterval(t)}start(){var s,i,o,r,a;this.ui.root.classList.remove("hidden"),this.initTouch(),this.initKeys(),this.ui.leave.addEventListener("click",()=>this.back(),this.on),this.loadName(),this.refreshPlaces(),this.circle.load(()=>this.lobby.open(this.places,this.circle)),this.neighborSub=((i=(s=Bt())==null?void 0:s.onEvent)==null?void 0:i.call(s,l=>{l.type==="neighborhood"&&this.refreshPlaces()}))??null,this.render();const t=()=>{this.life.signal.aborted||(this.pump(performance.now()),requestAnimationFrame(t))};requestAnimationFrame(t),this.every(()=>this.pump(performance.now()),100),this.every(()=>this.renderList(),1e3);const e=()=>this.setAway(document.visibilityState==="hidden");document.addEventListener("visibilitychange",e,this.on),window.addEventListener("pagehide",()=>this.setAway(!0),this.on),window.addEventListener("pageshow",e,this.on),window.addEventListener("beforeunload",()=>{var l,u;(l=this.link)==null||l.send({t:"bye"}),(u=this.link)==null||u.close(),this.lobby.close()},this.on);try{(a=(r=(o=screen.orientation).lock)==null?void 0:r.call(o,"landscape"))==null||a.catch(()=>{})}catch{}}async refreshPlaces(){const t=await Ee(),e=t.length===this.places.length&&t.every((s,i)=>s.key===this.places[i].key);this.places=t,(!e||t.length===0)&&this.lobby.open(t,this.circle),this.renderList()}setAway(t){t!==this.away&&(t?(this.pointers.clear(),this.keys=0,this.pad.releaseAll(),this.lightButtons(),this.link&&this.connected&&this.link.send({t:"in",...this.pad.message(),ts:Math.round(performance.now())}),this.sendPending=!1):(this.lastHeard=performance.now(),this.refreshPlaces()),this.away=t)}async loadName(){try{if(G("identity","getProfile")){const t=await de();this.name=((t==null?void 0:t.displayName)||(t==null?void 0:t.name)||"").trim().slice(0,32)}}catch{}}status(t){this.ui.status.textContent=t}onMessage(t,e,s){if(!(t!==this.link||!this.target)){if(e.t==="st"){if(this.displayKey||(this.displayKey=s),s!==this.displayKey)return;this.displaySid||(this.displaySid=e.sid),this.lastHeard=performance.now(),this.onState(e,this.lastHeard);return}s===this.displayKey&&(this.lastHeard=performance.now(),e.t==="full"&&e.to===t.sid?(this.status(`${this.target.title} is full (4 players). Pick another screen, or try again when a seat is free.`),this.toFinding()):e.t==="bye"&&e.sid===this.displaySid&&(this.status(`${this.target.title} closed.`),this.toFinding()))}}onState(t,e){var o;const s=t.pl.find(r=>{var a;return r.c===((a=this.link)==null?void 0:a.sid)});if(s){if(this.lastListed=e,this.mode!=="joined"&&(this.mode="joined",this.render()),s.s!==this.slot&&(this.slot=s.s,this.render()),s.et!==void 0&&s.eh!==void 0){const a=e-s.et-s.eh;a>=0&&a<3e4&&(this.rtt=this.rtt?this.rtt*.8+a*.2:a)}const r=t.ph==="lobby"?"IN THE LOBBY":t.ph==="loading"?"LOADING FOES":t.ph==="pause"?"PAUSED":t.ph==="over"?"GAME OVER":`LEVEL ${t.lv}`;this.ui.stats.textContent=`${r} · ♥ ${s.l} · ${s.sc} pts · ¢ ${s.k}${this.rtt?` · ${Math.round(this.rtt)} ms`:""}`}const i=t.ev.reduce((r,a)=>Math.max(r,a.i),-1);if(this.lastEv<0){this.lastEv=i;return}for(const r of t.ev)r.i<=this.lastEv||(r.c===((o=this.link)==null?void 0:o.sid)||r.c==="")&&this.vibrate(hi[r.k]);this.lastEv=Math.max(this.lastEv,i)}pump(t){if(this.away||this.mode==="finding")return;const e=this.target,s=this.link,i=this.lobby.get(e.key);if(!this.connected&&i&&i.room!==e.room&&i.status==="open"){this.join(i);return}if(!this.connected&&i&&(i.status==="closed"||i.expires*1e3<Date.now())){this.status(`${e.title} closed.`),this.toFinding();return}if(t-this.lastHeard>(this.connected?ai:li)){this.status(this.connected?`Lost ${e.title}. Looking again…`:`Couldn't reach ${e.title}.`),this.toFinding();return}this.connected&&((this.mode==="joining"||t-this.lastListed>ci)&&(this.mode==="joined"&&(this.mode="joining",this.render()),t-this.lastJoin>=oi&&(this.lastJoin=t,s.send({t:"join",name:this.name||void 0}))),t-this.lastSend>=ri&&(this.sendPending=!0),this.sendPending&&s.canSendGame&&(this.sendPending=!1,this.lastSend=t,s.send({t:"in",...this.pad.message(),ts:Math.round(t)})))}changed(){this.sendPending=!0,this.mode!=="finding"&&this.pump(performance.now())}join(t){this.closeLink(),this.target=t,this.mode="joining",this.connected=!1,this.displayKey="",this.displaySid="",this.lastJoin=0,this.lastHeard=performance.now(),this.lastListed=0,this.lastEv=-1,this.slot=-1,this.status(`Connecting to ${t.title}…`),this.render();const e=new rt({onJoined:s=>{e===this.link&&(e.hostNamed&&s!==t.host||this.connected||(this.connected=!0,this.lastHeard=performance.now(),this.status(`Joining ${t.title}…`)))},onLeft:s=>{const i=this.displayKey?s===this.displayKey:e.hostNamed&&s===t.host;e!==this.link||!i||(this.status(`${t.title} went away. Looking again…`),this.toFinding())},onFailed:(s,i)=>{e!==this.link||e.hostNamed&&s!==t.host||(this.status(i==="rejected"?`${t.title} is full (4 players). Pick another screen, or try again when a seat is free.`:`Couldn't reach ${t.title} (${i}).`),this.toFinding())},onMessage:(s,i)=>this.onMessage(e,s,i),onClosed:s=>{e===this.link&&(this.status(s),this.toFinding())}});this.link=e,e.open({place:t.place,room:t.room,host:t.keyed?t.host:void 0,admit:!1,identity:"account"}).then(s=>{e!==this.link||!s||(this.status(s),this.toFinding())})}back(){this.mode!=="finding"?(this.status(""),this.toFinding()):this.exit()}exit(){var t,e;this.closeLink(),this.lobby.close(),(t=this.neighborSub)==null||t.close(),this.neighborSub=null,this.endLife(),this.pointers.clear(),this.keys=0,this.pad.releaseAll(),this.lightButtons(),(e=this.zonesCanvas())==null||e.remove(),this.ui.list.replaceChildren(),this.status(""),this.ui.root.classList.add("hidden"),this.onExit()}closeLink(){const t=this.link;this.link=null,t&&(t.send({t:"bye"}),t.close())}toFinding(){this.closeLink(),this.mode="finding",this.target=null,this.connected=!1,this.slot=-1,this.pad.releaseAll(),this.pointers.clear(),this.render(),this.renderList()}render(){var s,i;const t=this.mode==="joined";this.ui.picker.classList.toggle("hidden",this.mode!=="finding");const e=U[this.slot];this.ui.root.style.setProperty("--seat",e?e.main:"#7c7c7c"),this.ui.root.style.setProperty("--seat-dark",e?e.dark:"#3c3c3c"),this.mode==="finding"?(this.ui.who.textContent="No screen yet",this.ui.stats.textContent=""):t?(this.ui.who.textContent=`${e?`P${this.slot+1} ${e.name}`:"Seated"} on ${((i=this.target)==null?void 0:i.title)??""}`,this.status("")):this.ui.who.textContent=`Joining ${((s=this.target)==null?void 0:s.title)??""}…`}renderList(){if(this.mode!=="finding")return;const t=this.lobby.list(this.circle);this.ui.list.replaceChildren();for(const o of t){const r=document.createElement("li"),a=document.createElement("button");a.type="button",a.className="display-btn";const l=o.place.kind==="online"?"Online":o.place.label;a.textContent=`📺 ${o.title} · ${l} — ${o.taken}/${o.max} players · ${fi(o.createdAt)}`,a.disabled=o.status!=="open",a.addEventListener("click",()=>this.join(o),this.on),r.append(a),this.ui.list.append(r)}const e=t.filter(o=>o.status==="open"),s=this.places.map(o=>o.label),i=s.length>1?`${s.slice(0,-1).join(", ")} and ${s.at(-1)}`:s[0];this.ui.pickerNote.textContent=rt.available()?this.places.length===0?"No neighborhoods and no relays here, so there is nowhere to find a screen.":t.length?e.length?"Pick the screen to play on.":"Every screen is full. A seat may free up.":`Looking for a WoTformer screen (${i})… Open WoTformer on the big screen and pick Display.`:"This shell has no direct connections, so this phone can’t be a controller. Open WoTformer in Myco."}vibrate(t){var e;try{(e=navigator.vibrate)==null||e.call(navigator,t)}catch{}}portrait(){var t;return((t=window.matchMedia)==null?void 0:t.call(window,"(orientation: portrait)").matches)??!1}toLocal(t,e){const s=this.ui.pad.getBoundingClientRect();return this.portrait()?{x:e-s.top,y:s.right-t}:{x:t-s.left,y:e-s.top}}centre(t){const e=t.getBoundingClientRect();return this.toLocal(e.left+e.width/2,e.top+e.height/2)}layout(){if(this.layoutCache)return this.layoutCache;const t=this.ui.pad,e=h=>t.querySelector(h),s=this.ui.dpad,i=this.centre(s),o=this.centre(e('[data-btn="A"]')),r=this.centre(e('[data-btn="B"]')),a=this.centre(e('[data-btn="SELECT"]')),l=this.centre(e('[data-btn="START"]')),u=e(".pills"),d=e('[data-btn="B"]').offsetWidth,f=s.offsetWidth/2,y=Us(i.x+f,Math.min(a.x,l.x)-u.offsetWidth/2+e('[data-btn="SELECT"]').offsetWidth/2,Math.max(a.x,l.x)+u.offsetWidth/2-e('[data-btn="START"]').offsetWidth/2,Math.min(o.x,r.x)-d/2);return this.layoutCache={w:t.offsetWidth,h:t.offsetHeight,dpad:i,dead:Math.max(10,s.offsetWidth*.1),a:o,b:r,select:a,start:l,...y},this.debug&&this.drawZones(),this.layoutCache}hit(t,e){return Vt(this.toLocal(t,e),this.layout())}apply(){let t=this.keys;for(const s of this.pointers.values())t|=s;const e=this.pad.held;this.pad.setMask(t,255)&&(this.lightButtons(),t&~e&&this.vibrate([10]),this.changed(),this.watchDebugChord(t))}lightButtons(){for(const t of this.ui.pad.querySelectorAll("[data-btn]")){const e=t.dataset.btn;t.classList.toggle("on",(this.pad.held&b[e])!==0)}}initTouch(){const t=this.ui.pad,e=s=>{this.pointers.delete(s.pointerId)&&this.apply()};t.addEventListener("pointerdown",s=>{if(!s.target.closest(".leave")){s.preventDefault(),this.layoutCache=null;try{t.setPointerCapture(s.pointerId)}catch{}this.pointers.set(s.pointerId,this.hit(s.clientX,s.clientY)),this.apply()}},this.on),t.addEventListener("pointermove",s=>{if(!this.pointers.has(s.pointerId))return;s.preventDefault();const i=this.hit(s.clientX,s.clientY);i!==this.pointers.get(s.pointerId)&&(this.pointers.set(s.pointerId,i),this.apply())},this.on),t.addEventListener("pointerup",e,this.on),t.addEventListener("pointercancel",e,this.on),t.addEventListener("lostpointercapture",e,this.on),window.addEventListener("pointerup",e,this.on),window.addEventListener("pointercancel",e,this.on);for(const s of["contextmenu","selectstart","dragstart","touchstart","touchmove","gesturestart"])t.addEventListener(s,i=>{var o,r;return i.cancelable&&!((r=(o=i.target)==null?void 0:o.closest)!=null&&r.call(o,".leave"))&&i.preventDefault()},{passive:!1,signal:this.life.signal});window.addEventListener("resize",()=>{this.layoutCache=null,this.debug&&this.layout()},this.on),window.addEventListener("blur",()=>{this.pointers.clear(),this.keys=0,this.apply()},this.on),this.debug&&requestAnimationFrame(()=>this.layout())}watchDebugChord(t){const e=(t&(b.SELECT|b.START))===(b.SELECT|b.START);e&&this.chordTimer===null?this.chordTimer=window.setTimeout(()=>{var s;this.chordTimer=null,this.debug=!this.debug,this.vibrate([30,30,30]),this.debug?this.drawZones():(s=this.zonesCanvas())==null||s.remove()},1500):!e&&this.chordTimer!==null&&(clearTimeout(this.chordTimer),this.chordTimer=null)}zonesCanvas(){return this.ui.pad.querySelector("canvas.zones")}drawZones(){const t=this.layoutCache??this.layout();let e=this.zonesCanvas();e||(e=document.createElement("canvas"),e.className="zones",this.ui.pad.append(e)),e.width=Math.round(t.w),e.height=Math.round(t.h);const s=e.getContext("2d"),i=r=>r===0?"rgba(0,0,0,0)":`hsla(${r*47%360} 90% 55% / 0.35)`,o=6;for(let r=0;r<t.h;r+=o)for(let a=0;a<t.w;a+=o)s.fillStyle=i(Vt({x:a+o/2,y:r+o/2},t)),s.fillRect(a,r,o,o);s.fillStyle="#fff",s.font="bold 12px monospace";for(const[r,a]of[["A",t.a],["B",t.b],["SELECT",t.select],["START",t.start],["+",t.dpad]])s.fillText(r,a.x-4,a.y+4);s.strokeStyle="#fff",s.beginPath(),s.arc(t.dpad.x,t.dpad.y,t.dead,0,Math.PI*2),s.moveTo(t.dpadEdge,0),s.lineTo(t.dpadEdge,t.h),s.moveTo(t.buttonsEdge,0),s.lineTo(t.buttonsEdge,t.h),s.stroke()}initKeys(){const t={ArrowLeft:b.LEFT,ArrowRight:b.RIGHT,ArrowUp:b.UP,ArrowDown:b.DOWN,z:b.A," ":b.A,x:b.B,Enter:b.START,Shift:b.SELECT},e=s=>t[s.key.length===1?s.key.toLowerCase():s.key]??0;window.addEventListener("keydown",s=>{if(s.key==="Escape"){s.preventDefault(),this.back();return}const i=e(s);i&&(s.preventDefault(),this.keys|=i,this.apply())},this.on),window.addEventListener("keyup",s=>{const i=e(s);i&&(this.keys&=~i,this.apply())},this.on)}}const di=6e3;function pi(n){return di}function mi(n){return{pauseGame:n==="play",suspendAudio:!0}}const gi={A:[".###.","#...#","#...#","#####","#...#","#...#","#...#"],B:["####.","#...#","#...#","####.","#...#","#...#","####."],C:[".###.","#...#","#....","#....","#....","#...#",".###."],D:["####.","#...#","#...#","#...#","#...#","#...#","####."],E:["#####","#....","#....","####.","#....","#....","#####"],F:["#####","#....","#....","####.","#....","#....","#...."],G:[".###.","#...#","#....","#.###","#...#","#...#",".####"],H:["#...#","#...#","#...#","#####","#...#","#...#","#...#"],I:[".###.","..#..","..#..","..#..","..#..","..#..",".###."],J:["..###","...#.","...#.","...#.","...#.","#..#.",".##.."],K:["#...#","#..#.","#.#..","##...","#.#..","#..#.","#...#"],L:["#....","#....","#....","#....","#....","#....","#####"],M:["#...#","##.##","#.#.#","#.#.#","#...#","#...#","#...#"],N:["#...#","#...#","##..#","#.#.#","#..##","#...#","#...#"],O:[".###.","#...#","#...#","#...#","#...#","#...#",".###."],P:["####.","#...#","#...#","####.","#....","#....","#...."],Q:[".###.","#...#","#...#","#...#","#.#.#","#..#.",".##.#"],R:["####.","#...#","#...#","####.","#.#..","#..#.","#...#"],S:[".####","#....","#....",".###.","....#","....#","####."],T:["#####","..#..","..#..","..#..","..#..","..#..","..#.."],U:["#...#","#...#","#...#","#...#","#...#","#...#",".###."],V:["#...#","#...#","#...#","#...#","#...#",".#.#.","..#.."],W:["#...#","#...#","#...#","#.#.#","#.#.#","#.#.#",".#.#."],X:["#...#","#...#",".#.#.","..#..",".#.#.","#...#","#...#"],Y:["#...#","#...#",".#.#.","..#..","..#..","..#..","..#.."],Z:["#####","....#","...#.","..#..",".#...","#....","#####"],0:[".###.","#...#","#..##","#.#.#","##..#","#...#",".###."],1:["..#..",".##..","..#..","..#..","..#..","..#..",".###."],2:[".###.","#...#","....#","...#.","..#..",".#...","#####"],3:["####.","....#","....#",".###.","....#","....#","####."],4:["...#.","..##.",".#.#.","#..#.","#####","...#.","...#."],5:["#####","#....","####.","....#","....#","#...#",".###."],6:["..##.",".#...","#....","####.","#...#","#...#",".###."],7:["#####","....#","...#.","..#..",".#...",".#...",".#..."],8:[".###.","#...#","#...#",".###.","#...#","#...#",".###."],9:[".###.","#...#","#...#",".####","....#","...#.",".##.."]," ":[".....",".....",".....",".....",".....",".....","....."],".":[".....",".....",".....",".....",".....",".##..",".##.."],",":[".....",".....",".....",".....",".##..","..#..",".#..."],":":[".....",".##..",".##..",".....",".##..",".##..","....."],"!":["..#..","..#..","..#..","..#..","..#..",".....","..#.."],"?":[".###.","#...#","....#","...#.","..#..",".....","..#.."],"-":[".....",".....",".....",".###.",".....",".....","....."],"+":[".....","..#..","..#..","#####","..#..","..#..","....."],"/":["....#","....#","...#.","..#..",".#...","#....","#...."],"'":["..#..","..#..",".#...",".....",".....",".....","....."],"(":["...#.","..#..",".#...",".#...",".#...","..#..","...#."],")":[".#...","..#..","...#.","...#.","...#.","..#..",".#..."],_:[".....",".....",".....",".....",".....",".....","#####"],"@":[".###.","#...#","#.###","#.#.#","#.###","#....",".####"],"#":[".#.#.",".#.#.","#####",".#.#.","#####",".#.#.",".#.#."],"=":[".....",".....","#####",".....","#####",".....","....."],"<":["...#.","..#..",".#...","#....",".#...","..#..","...#."],">":[".#...","..#..","...#.","....#","...#.","..#..",".#..."],"*":[".....","#.#.#",".###.","#####",".###.","#.#.#","....."],"♥":[".....",".#.#.","#####","#####",".###.","..#..","....."],"¢":[".###.","#.#.#","#.#..","#.#..","#.#..","#.#.#",".###."],"☺":[".###.","#...#","#.#.#","#...#","#.#.#","#..##",".###."],"▶":["#....","##...","###..","####.","###..","##...","#...."],"◀":["....#","...##","..###",".####","..###","...##","....#"],"×":[".....","#...#",".#.#.","..#..",".#.#.","#...#","....."]},yi={A:[".#.","#.#","###","#.#","#.#"],B:["##.","#.#","##.","#.#","##."],C:[".##","#..","#..","#..",".##"],D:["##.","#.#","#.#","#.#","##."],E:["###","#..","##.","#..","###"],F:["###","#..","##.","#..","#.."],G:[".##","#..","#.#","#.#",".##"],H:["#.#","#.#","###","#.#","#.#"],I:["###",".#.",".#.",".#.","###"],J:["..#","..#","..#","#.#",".#."],K:["#.#","#.#","##.","#.#","#.#"],L:["#..","#..","#..","#..","###"],M:["#.#","###","###","#.#","#.#"],N:["##.","#.#","#.#","#.#","#.#"],O:[".#.","#.#","#.#","#.#",".#."],P:["##.","#.#","##.","#..","#.."],Q:[".#.","#.#","#.#","##.",".##"],R:["##.","#.#","##.","#.#","#.#"],S:[".##","#..",".#.","..#","##."],T:["###",".#.",".#.",".#.",".#."],U:["#.#","#.#","#.#","#.#","###"],V:["#.#","#.#","#.#","#.#",".#."],W:["#.#","#.#","###","###","#.#"],X:["#.#","#.#",".#.","#.#","#.#"],Y:["#.#","#.#",".#.",".#.",".#."],Z:["###","..#",".#.","#..","###"],0:["###","#.#","#.#","#.#","###"],1:[".#.","##.",".#.",".#.","###"],2:["##.","..#",".#.","#..","###"],3:["##.","..#",".#.","..#","##."],4:["#.#","#.#","###","..#","..#"],5:["###","#..","##.","..#","##."],6:[".##","#..","###","#.#","###"],7:["###","..#",".#.",".#.",".#."],8:["###","#.#","###","#.#","###"],9:["###","#.#","###","..#","##."]," ":["...","...","...","...","..."],".":["...","...","...","...",".#."],"-":["...","...","###","...","..."],_:["...","...","...","...","###"],"'":[".#.",".#.","...","...","..."],"!":[".#.",".#.",".#.","...",".#."],"?":["##.","..#",".#.","...",".#."],"+":["...",".#.","###",".#.","..."],"@":["###","#.#","#.#","#..",".##"],"/":["..#","..#",".#.","#..","#.."],":":["...",".#.","...",".#.","..."],",":["...","...","...",".#.","#.."],"(":[".#.","#..","#..","#..",".#."],")":[".#.","..#","..#","..#",".#."],"<":["..#",".#.","#..",".#.","..#"],">":["#..",".#.","..#",".#.","#.."],"=":["...","###","...","###","..."]},T={glyphs:gi,adv:6},E={glyphs:yi,adv:4};function D(n,t,e=64){let s="";for(const i of t.toUpperCase())if(n.glyphs[i]&&(s+=i),s.length>=e)break;return s.replace(/\s+/g," ").trim()}function X(n,t){return t.length?t.length*n.adv-1:0}function x(n,t,e,s,i,o,r=1,a){a&&x(n,t,e,s+r,i+r,a,r),n.fillStyle=o;let l=Math.round(s);const u=Math.round(i);for(const d of e){const f=t.glyphs[d]??t.glyphs[d.toUpperCase()];if(f)for(let y=0;y<f.length;y++){const h=f[y];for(let p=0;p<h.length;p++)h[p]==="#"&&n.fillRect(l+p*r,u+y*r,r,r)}l+=t.adv*r}}function C(n,t,e,s,i,o,r=1,a){x(n,t,e,Math.round(s-X(t,e)*r/2),i,o,r,a)}class Me{constructor(t){c(this,"s");this.s=t|0}next(){this.s=this.s+1831565813|0;let t=Math.imul(this.s^this.s>>>15,this.s|1);return t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}int(t,e){return t+Math.floor(this.next()*(e-t+1))}chance(t){return this.next()<t}pick(t){return t[Math.floor(this.next()*t.length)]}get state(){return this.s}}const k=16,P=12,A=10,ki=3,Qt=3,S={EMPTY:0,GROUND:1,BRICK:2,QUESTION:3,USED:4,BLOCK:5,PIPE_TL:6,PIPE_TR:7,PIPE_L:8,PIPE_R:9,COIN:10};function Q(n){return n>=S.GROUND&&n<=S.PIPE_R}function B(n,t,e){return t<0||t>=n.w?S.BLOCK:e<0||e>=P?S.EMPTY:n.tiles[e*n.w+t]}function L(n,t,e,s){t<0||t>=n.w||e<0||e>=P||(n.tiles[e*n.w+t]=s)}function wi(n){return Math.min(150+(n-1)*30,360)}function Ce(n,t){const e=new Me(n^Math.imul(t,2654435761)),s=wi(t),i=s+64,o={seed:n,number:t,w:i,tiles:new Uint8Array(i*P),spawns:[],flagCol:0,theme:(t-1)%3,deco:{clouds:[],hills:[],bushes:[]}},r=(h,p)=>{for(let g=p;g<P;g++)L(o,h,g,S.GROUND)},a=Math.min(.25+t*.08,.7),l=t<2?0:Math.min(.15+(t-2)*.08,.45),u=t===1?2:ki,d=(h,p)=>{h<18||o.spawns.some(g=>g.col===h)||o.spawns.push({col:h,row:p,kind:e.chance(l)?"hopper":"walker"})};let f=0;for(;f<14;f++)r(f,A);for(;f<s;){const h=e.int(0,9);if(h<=2){const p=e.int(6,12);for(let g=0;g<p;g++)r(f+g,A);if(e.chance(.7)){const g=f+e.int(1,Math.max(1,p-5)),v=Math.max(1,Math.min(e.int(1,4),f+p-4-g));for(let M=0;M<v;M++)L(o,g+M,A-4,e.chance(.45)?S.QUESTION:S.BRICK);e.chance(.35)&&L(o,g+Math.floor(v/2),A-8,S.QUESTION)}else if(e.chance(.6)){const g=f+e.int(1,Math.max(1,p-4));for(let v=0;v<3;v++)L(o,g+v,A-2,S.COIN)}e.chance(a)&&d(f+p-2,A),e.chance(a*.6)&&d(f+Math.floor(p/2),A),f+=p}else if(h<=4){const p=e.int(2,u);if(r(f,A),r(f+1,A),f+=2,e.chance(.5))for(let g=0;g<p;g++)L(o,f+g,A-4,S.COIN);f+=p;for(let g=0;g<3;g++)r(f+g,A);f+=3}else if(h===5){const p=e.int(2,Qt);for(let M=0;M<6;M++)r(f+M,A);const g=f+2,v=A-p;L(o,g,v,S.PIPE_TL),L(o,g+1,v,S.PIPE_TR);for(let M=v+1;M<A;M++)L(o,g,M,S.PIPE_L),L(o,g+1,M,S.PIPE_R);e.chance(a)&&d(f+5,A),f+=6}else if(h===6){const p=e.int(2,4);for(let g=0;g<p;g++){r(f+g,A);for(let v=A-1-g;v<A;v++)L(o,f+g,v,S.BLOCK)}f+=p,e.chance(.4)&&p>=3&&(f+=e.int(1,2));for(let g=0;g<p;g++){r(f+g,A);for(let v=A-p+g;v<A;v++)L(o,f+g,v,S.BLOCK)}f+=p;for(let g=0;g<2;g++)r(f+g,A);f+=2}else if(h===7){const p=e.int(1,Qt),g=e.int(4,9);r(f,A),f+=1;for(let v=0;v<g;v++)r(f+v,A-p);if(e.chance(.5))for(let v=1;v<g-1;v++)L(o,f+v,A-p-2,S.COIN);e.chance(a)&&d(f+g-1,A-p),f+=g;for(let v=0;v<2;v++)r(f+v,A);f+=2}else{const p=e.int(3,4);r(f,A),r(f+1,A),f+=2,f+=2;for(let g=0;g<p;g++)L(o,f+g,A-3,e.chance(.2)?S.QUESTION:S.BRICK);for(let g=0;g<p;g++)e.chance(.5)&&L(o,f+g,A-5,S.COIN);t>=2&&e.chance(a)&&d(f+p-1,A-3),f+=p,f+=2;for(let g=0;g<3;g++)r(f+g,A);f+=3}}for(let h=0;h<4;h++)r(f+h,A);f+=4;for(let h=0;h<4;h++){r(f+h,A);for(let p=A-1-h;p<A;p++)L(o,f+h,p,S.BLOCK)}f+=4,o.flagCol=f+3;const y=o.flagCol+14;for(;f<y;f++)r(f,A);L(o,o.flagCol,A-1,S.BLOCK),bi(o,y);for(let h=e.int(2,8);h<o.w;h+=e.int(8,16))o.deco.clouds.push({x:h,y:e.int(1,4),w:e.int(1,3)});for(let h=e.int(0,6);h<o.w;h+=e.int(14,26))o.deco.hills.push({x:h,h:e.int(1,2)});for(let h=e.int(4,10);h<o.w;h+=e.int(9,18))o.deco.bushes.push({x:h,w:e.int(1,3)});return o}function bi(n,t){const e=new Uint8Array(t*P);for(let s=0;s<P;s++)e.set(n.tiles.subarray(s*n.w,s*n.w+t),s*t);n.tiles=e,n.w=t,n.spawns=n.spawns.filter(s=>s.col<t)}const vi=60,w=320,K=180,N=P*k-K,F=10,q=14,$=14,Y=22,z=6,Ei=.18,Si=.7,Zt=.1,Ai=.35,te=1,Dt=.45,yt=4.6,xi=4,ee=1.5,Mi=2.4,Ci=.1,Ti=.13,Li=.08,St=.12,Ri=.25,Oi=5,Di=5.4,Ki=4.2,Ni=6.2,Ii=6,Gi=8,Pi=3.6,_i=2,Fi=14,Bi=3,Te=300,$i=100,Wi=120,Hi=270,Ui=30,ji=50,se=[100,200,400,800,1e3,2e3,4e3,8e3];function Le(n){return{slot:n,state:"off",x:0,y:0,vx:0,vy:0,onGround:!1,facing:1,timer:0,lives:Bi,score:0,coins:0,kills:0,inv:0,fireCd:0,combo:0,coyote:0,jumpBuf:0,jumpT:-1,walk:0,idle:0}}function qi(n,t,e=1){const s=new Me(n),i=Array.from({length:t},(r,a)=>a);for(let r=i.length-1;r>0;r--){const a=Math.floor(s.next()*(r+1));[i[r],i[a]]=[i[a],i[r]]}const o={seed:n,levelNo:e,level:Ce(n,e),tick:0,camX:0,phase:"play",phaseT:0,players:[0,1,2,3].map(Le),enemies:[],shots:[],fx:[],spawned:new Uint8Array(0),nextId:1,faceCount:t,faceOrder:i,faceCursor:0,rng:s,events:[]};return Re(o,e),o}function Re(n,t){n.levelNo=t,n.level=Ce(n.seed,t),n.spawned=new Uint8Array(n.level.spawns.length),n.camX=0,n.phase="play",n.phaseT=0,n.enemies=[],n.shots=[],n.fx=[];for(const e of n.players)e.state!=="off"&&(e.state==="out"&&(e.lives=1),Oe(e))}function Oe(n){n.state="alive",n.x=24+n.slot*26,n.y=10*k-q,n.vx=0,n.vy=0,n.facing=1,n.inv=0,n.onGround=!0}function ie(n,t){const e=n.players[t];!e||e.state!=="off"||(Object.assign(e,Le(t)),n.tick===0?Oe(e):Kt(n,e),n.events.push({k:"spawn",slot:t,face:-1}))}function Yi(n,t){const e=n.players[t];e&&(e.state="off",n.shots=n.shots.filter(s=>s.owner!==t))}function De(n){return n.players.filter(t=>t.state!=="off").length}function Kt(n,t){const e=n.level;let s=n.camX+24;for(const a of n.players)a!==t&&a.state==="alive"&&a.onGround&&(s=Math.max(s,a.x-20));s=Math.min(s,n.camX+w-48);const i=Math.max(0,Math.floor(s/k));let o=i,r=10;t:for(let a=i;a<Math.min(e.w,i+16);a++)for(let l=2;l<P;l++)if(Q(B(e,a,l))&&!Q(B(e,a,l-1))&&!Q(B(e,a,l-2))){o=a,r=l;break t}t.state="alive",t.x=o*k+(k-F)/2,t.y=r*k-q,t.vx=0,t.vy=0,t.onGround=!0,t.inv=Wi,t.timer=0}function $t(n,t,e,s){if(t.vx===0)return!1;t.x+=t.vx;const i=Math.floor(t.y/k),o=Math.floor((t.y+s-.01)/k);if(t.vx>0){const r=Math.floor((t.x+e-.01)/k);for(let a=i;a<=o;a++)if(Q(B(n,r,a)))return t.x=r*k-e,!0}else{const r=Math.floor(t.x/k);for(let a=i;a<=o;a++)if(Q(B(n,r,a)))return t.x=(r+1)*k,!0}return!1}function Wt(n,t,e,s){t.onGround=!1,t.y+=t.vy;const i=Math.floor(t.x/k),o=Math.floor((t.x+e-.01)/k);if(t.vy>0){const r=Math.floor((t.y+s-.01)/k);for(let a=i;a<=o;a++)if(Q(B(n,a,r)))return t.y=r*k-s,t.vy=0,t.onGround=!0,-1}else if(t.vy<0){const r=Math.floor(t.y/k),l=Math.floor((t.x+e/2)/k)===i?[i,o]:[o,i];for(const u of l)if(Q(B(n,u,r)))return t.y=(r+1)*k,t.vy=0,u}return-1}const ne=(n,t,e,s,i,o,r,a)=>n<i+r&&n+e>i&&t<o+a&&t+s>o;function Vi(n,t){if(n.events=[],n.tick++,n.phaseT++,n.phase==="over"){oe(n);return}const e=n.phase==="play";for(const s of n.players)s.state==="off"||s.state==="out"||Xi(n,s,e?t[s.slot]:void 0);if(e&&(tn(n),en(n),sn(n),nn(n,t)),on(n),oe(n),n.phase==="play"){const s=n.players.find(i=>i.state==="alive"&&i.x+F>=n.level.flagCol*k-1);if(s){n.phase="clear",n.phaseT=0,n.shots=[];for(const i of n.players){if(i.state!=="alive")continue;const o=Math.max(0,10*k-(i.y+q)),r=1e3+Math.round(o/k)*500+(i===s?1e3:0);i.score+=r,j(n,"score",i.x,i.y-8,r,i.slot)}n.events.push({k:"clear",slot:s.slot,face:-1})}else De(n)>0&&n.players.every(i=>i.state==="off"||i.state==="out")&&(n.phase="over",n.phaseT=0,n.events.push({k:"over",slot:-1,face:-1}))}else n.phase==="clear"&&n.phaseT>=Hi&&Re(n,n.levelNo+1)}function Xi(n,t,e){const s=n.level;if(t.state==="dying"){t.timer++,t.timer>20&&(t.vy=Math.min(t.vy+Dt,yt),t.y+=t.vy),t.timer>=$i&&(t.lives>0?Kt(n,t):t.state="out");return}const i=(e==null?void 0:e.held)??0,o=(e==null?void 0:e.pressed)??0;t.idle=i?0:t.idle+1;const r=(i&b.RIGHT?1:0)-(i&b.LEFT?1:0),a=(i&b.B)!==0,l=a?Mi:ee;if(r!==0){const g=Math.abs(t.vx);t.onGround&&t.vx!==0&&Math.sign(t.vx)!==r?t.vx+=r*Ri:t.vx+=r*(t.onGround?a?Ti:Ci:Li),Math.abs(t.vx)>l&&(t.vx=Math.sign(t.vx)*(g>l?Math.max(l,g-St):l)),t.facing=r>0?1:-1}else t.onGround&&(t.vx=Math.abs(t.vx)<=St?0:t.vx-Math.sign(t.vx)*St);if(t.coyote=t.onGround?Ii:Math.max(0,t.coyote-1),t.jumpBuf=o&b.A?Gi:Math.max(0,t.jumpBuf-1),t.jumpBuf>0&&t.coyote>0&&(t.vy=-(Math.abs(t.vx)>ee+.3?Di:Oi),t.onGround=!1,t.coyote=0,t.jumpBuf=0,t.jumpT=0,n.events.push({k:"jump",slot:t.slot,face:-1})),t.vy=Math.min(t.vy+zi(t,(i&b.A)!==0),yt),t.jumpT>=0&&t.jumpT++,t.fireCd>0&&t.fireCd--,o&b.B&&t.fireCd===0&&n.shots.filter(g=>g.owner===t.slot).length<_i&&(n.shots.push({owner:t.slot,x:t.facing>0?t.x+F:t.x-z,y:t.y+4,vx:Pi*t.facing+t.vx*.5,vy:1.5,life:100}),t.fireCd=Fi,n.events.push({k:"shoot",slot:t.slot,face:-1})),$t(s,t,F,q)&&(t.vx=0),t.x<n.camX){if(t.idle>=Te&&n.players.some(g=>g!==t&&g.state==="alive")){Kt(n,t);return}t.x=n.camX,t.vx<0&&(t.vx=0)}t.x>n.camX+w-F&&(t.x=n.camX+w-F,t.vx>0&&(t.vx=0));const u=!t.onGround,d=Wt(s,t,F,q);t.onGround&&u&&(t.combo=0),(t.onGround||d>=0)&&(t.jumpT=-1),d>=0&&Ji(n,t,d,Math.floor(t.y/k)-1),t.walk+=Math.abs(t.vx),t.inv>0&&t.inv--;const f=Math.floor(t.x/k),y=Math.floor((t.x+F-.01)/k),h=Math.floor(t.y/k),p=Math.floor((t.y+q-.01)/k);for(let g=f;g<=y;g++)for(let v=h;v<=p;v++)B(s,g,v)===S.COIN&&(L(s,g,v,S.EMPTY),Ke(n,t,100));t.y>P*k+8&&Ne(n,t)}function zi(n,t){const e=t||n.jumpT>=0&&n.jumpT<xi;return n.vy<0?e?-n.vy<te?Zt:Ei:Si:t&&n.vy<te?Zt:Ai}function Ke(n,t,e){t.coins++,t.score+=e,n.events.push({k:"coin",slot:t.slot,face:-1}),t.coins%ji===0&&(t.lives++,n.events.push({k:"1up",slot:t.slot,face:-1}))}function Ji(n,t,e,s){const i=n.level,o=B(i,e,s);if(o===S.QUESTION)L(i,e,s,S.USED),Ke(n,t,200),j(n,"coin",e*k+4,s*k-8,0,t.slot,0,-5),j(n,"bump",e*k,s*k,S.USED,t.slot);else if(o===S.BRICK)j(n,"bump",e*k,s*k,S.BRICK,t.slot);else{n.events.push({k:"bump",slot:t.slot,face:-1});return}n.events.push({k:"bump",slot:t.slot,face:-1});for(const r of n.enemies){if(r.state!=="walk")continue;const a=r.y+Y;Math.abs(a-s*k)<2&&r.x+$>e*k&&r.x<(e+1)*k&&Pe(n,r,t,Math.sign(r.x+$/2-(e*k+8))||1)}}function Ne(n,t){t.state==="alive"&&(t.state="dying",t.timer=0,t.vx=0,t.vy=-5,t.lives=Math.max(0,t.lives-1),n.events.push({k:"die",slot:t.slot,face:-1}))}function Qi(n,t){for(;n.faceCount<t;){const e=n.faceCount++,s=n.faceOrder.length,i=s?n.faceCursor%s+n.rng.int(0,Math.min(3,s)):0;n.faceOrder.splice(Math.min(i,s),0,e)}}function Zi(n){if(n.faceCount===0)return-1;const t=n.faceOrder[n.faceCursor%n.faceCount];return n.faceCursor++,t}function Ie(n,t){let e=null;for(const s of n.players)s.state==="alive"&&(e===null||Math.abs(s.x-t)<Math.abs(e-t))&&(e=s.x);return e}function Ge(n){return Math.min(.45+(n-1)*.07,1)}function tn(n){const t=n.level,e=n.camX+w+24;for(let s=0;s<t.spawns.length;s++){if(n.spawned[s])continue;const i=t.spawns[s];if(i.col*k>e||(n.spawned[s]=1,i.col*k+k<n.camX))continue;const o=i.col*k+(k-$)/2,r=Ie(n,o),a=r!==null&&r>o?1:-1;n.enemies.push({id:n.nextId++,kind:i.kind,face:Zi(n),state:"walk",x:o,y:i.row*k-Y,vx:a*Ge(n.levelNo),vy:0,onGround:!1,timer:i.kind==="hopper"?40+n.rng.int(0,60):90+n.rng.int(0,60),walk:0})}}function en(n){const t=n.level,e=Ge(n.levelNo);for(const i of n.enemies){if(i.state==="squashed"){i.timer--;continue}if(i.state==="flipped"){i.vy=Math.min(i.vy+Dt,yt),i.x+=i.vx,i.y+=i.vy;continue}if(i.timer--,i.timer<=0&&i.onGround)if(i.kind==="hopper")i.vy=-4.6,i.timer=70+n.rng.int(0,60);else{const o=Ie(n,i.x);o!==null&&Math.abs(o-i.x)>24&&(i.vx=(o>i.x?1:-1)*e),i.timer=100+n.rng.int(0,80)}i.vy=Math.min(i.vy+Dt,yt),$t(t,i,$,Y)&&(i.vx=-i.vx),Wt(t,i,$,Y),i.walk+=Math.abs(i.vx)}const s=P*k+32;n.enemies=n.enemies.filter(i=>!(i.state==="squashed"&&i.timer<=0)&&i.y<s&&i.x>n.camX-64)}function sn(n){const t=n.level;for(const e of n.shots){e.life--,e.vy=Math.min(e.vy+.35,4);const s={x:e.x,y:e.y,vx:e.vx,vy:e.vy,onGround:!1};$t(t,s,z,z)&&(e.life=0,j(n,"puff",s.x,s.y,0,e.owner)),Wt(t,s,z,z),s.onGround&&(s.vy=-3.2),e.x=s.x,e.y=s.y,e.vy=s.vy,(e.x<n.camX-8||e.x>n.camX+w+8||e.y>P*k)&&(e.life=0)}n.shots=n.shots.filter(e=>e.life>0)}function Pe(n,t,e,s){t.state="flipped",t.vy=-3.5,t.vx=s*1.2,e&&(e.kills++,e.score+=200,j(n,"score",t.x,t.y-6,200,e.slot)),j(n,"name",t.x+$/2,t.y-10,t.face,(e==null?void 0:e.slot)??-1),n.events.push({k:"kill",slot:(e==null?void 0:e.slot)??-1,face:t.face})}function nn(n,t){var e;for(const s of n.shots)for(const i of n.enemies)i.state!=="walk"||s.life<=0||ne(s.x,s.y,z,z,i.x,i.y,$,Y)&&(s.life=0,Pe(n,i,n.players[s.owner],Math.sign(s.vx)||1));n.shots=n.shots.filter(s=>s.life>0);for(const s of n.players)if(s.state==="alive")for(const i of n.enemies){if(i.state!=="walk"||!ne(s.x,s.y,F,q,i.x+1,i.y+2,$-2,Y-2))continue;const o=s.y+q-s.vy;if(s.vy>0&&o<=i.y+8){i.state="squashed",i.timer=Ui,s.vy=-((((e=t[s.slot])==null?void 0:e.held)??0)&b.A?Ni:Ki),s.jumpT=-1;const r=se[Math.min(s.combo,se.length-1)];s.combo++,s.kills++,s.score+=r,j(n,"score",i.x,i.y-6,r,s.slot),j(n,"name",i.x+$/2,i.y-10,i.face,s.slot),n.events.push({k:"stomp",slot:s.slot,face:i.face})}else if(s.inv===0){Ne(n,s);break}}}function on(n){let t=-1/0,e=1/0;for(const o of n.players)o.state==="alive"&&(t=Math.max(t,o.x),o.idle<Te&&(e=Math.min(e,o.x)));if(t===-1/0)return;const s=n.level.w*k-w,i=Math.min(Math.round(t-130),Math.round(e-8));n.camX=Math.max(n.camX,Math.min(i,s))}function j(n,t,e,s,i,o,r=0,a=0){const l=t==="name"?80:t==="score"?45:t==="coin"?24:t==="bump"?8:16;n.fx.push({k:t,x:e,y:s,vx:r,vy:t==="score"||t==="name"?-.6:a,t:l,n:i,slot:o}),n.fx.length>80&&n.fx.shift()}function oe(n){for(const t of n.fx)t.t--,t.x+=t.vx,t.y+=t.vy,t.k==="coin"?t.vy+=.4:(t.k==="score"||t.k==="name")&&(t.vy*=.95);n.fx=n.fx.filter(t=>t.t>0)}class rn{constructor(){c(this,"heroes",U.map(zs));c(this,"walker",Xt("#ac7c00","#fce0a8"));c(this,"hopper",Xt("#6844fc","#b8b8f8"));c(this,"tilesDay",zt(!1));c(this,"tilesNight",zt(!0));c(this,"generic",[0,60,200,280,330].map(Zs));c(this,"faces",[]);c(this,"genericOnly",!1)}face(t){return t>=0&&t<this.faces.length?this.faces[t]:{name:"???",image:this.generic[Math.abs(t)%this.generic.length]}}}const re=[m.skyDay,m.skyDusk,m.skyNight];class an{constructor(t){c(this,"g");c(this,"scale",1);this.canvas=t,t.width=w,t.height=K,this.g=t.getContext("2d",{alpha:!1}),this.g.imageSmoothingEnabled=!1,this.resize()}resize(){const t=window.devicePixelRatio||1,e=Math.max(1,Math.floor(window.innerWidth*t)),s=Math.max(1,Math.floor(window.innerHeight*t)),i=Math.min(e/w,s/K),o=Math.floor(i);this.scale=o>=1&&o>=i*.9?o:i,this.canvas.style.width=`${w*this.scale/t}px`,this.canvas.style.height=`${K*this.scale/t}px`}present(){}drawWorld(t,e,s){const i=this.g,o=t.level,r=Math.round(t.camX);i.fillStyle=re[o.theme],i.fillRect(0,0,w,K),o.theme===2&&this.stars(r),this.scenery(t,r);const a=o.theme===2?e.tilesNight:e.tilesDay,l=new Map;for(const d of t.fx)d.k==="bump"&&l.set(Math.round(d.x/k)*1e3+Math.round(d.y/k),Math.sin(d.t/8*Math.PI)*4);const u=Math.floor(r/k);for(let d=u;d<=u+w/k+1;d++)for(let f=0;f<P;f++){const y=B(o,d,f);if(y===S.EMPTY||d>=o.w)continue;const h=this.tileImage(a,y,t.tick);if(!h)continue;const p=l.get(d*1e3+f)??0;i.drawImage(h,d*k-r,f*k-N-Math.round(p))}this.flagAndCastle(t,r,a);for(const d of t.enemies)this.enemy(d,e,r,t.tick);for(const d of t.shots){const f=U[d.owner],y=Math.round(d.x-r),h=Math.round(d.y-N);i.fillStyle=m.black,i.fillRect(y,h+1,6,4),i.fillRect(y+1,h,4,6),i.fillStyle=t.tick>>1&1?f.main:m.white,i.fillRect(y+1,h+1,4,4),i.fillStyle=m.white,i.fillRect(y+2,h+2,2,2)}for(const d of t.players)this.player(d,e,r,t.tick,s[d.slot]??"");for(const d of t.enemies)d.state==="walk"&&this.nameTag(e.face(d.face).name,d.x+$/2-r,d.y-N-9);this.effects(t,e,r)}tileImage(t,e,s){switch(e){case S.GROUND:return t.ground;case S.BRICK:return t.brick;case S.QUESTION:return t.question[[0,1,2,1][(s>>3)%4]];case S.USED:return t.used;case S.BLOCK:return t.block;case S.PIPE_TL:return t.pipeTL;case S.PIPE_TR:return t.pipeTR;case S.PIPE_L:return t.pipeL;case S.PIPE_R:return t.pipeR;case S.COIN:return t.coin[(s>>3)%4];default:return null}}stars(t){const e=this.g;e.fillStyle=m.white;for(let s=0;s<40;s++){const i=Math.imul(s+1,2654435761)>>>0,o=((i%640-t*.2)%w+w)%w;e.fillRect(Math.round(o),(i>>>10)%110,1,1)}}scenery(t,e){const s=this.g,i=t.level,o=10*k-N,r=i.theme===2;for(const a of i.deco.hills){const l=Math.round(a.x*k-e*.5),u=a.h===1?20:36,d=u+8;if(!(l+d*2<0||l>w)){s.fillStyle=r?"#00504c":m.hill;for(let f=0;f<u;f+=2){const y=Math.round((u-f)/u*d);s.fillRect(l+d-y,o-f-2,y*2,2)}s.fillStyle=r?"#003020":m.hillDark,s.fillRect(l+d-6,o-u+8,2,4),s.fillRect(l+d+4,o-u+12,2,4)}}for(const a of i.deco.clouds){const l=Math.round(a.x*k-e*.35),u=16+a.w*16;if(l+u+16<0||l-16>w)continue;const d=a.y*k-N+4;s.fillStyle=r?"#3c3c5c":m.white,s.fillRect(l,d+4,u,10),s.fillRect(l+4,d,u-8,16);for(let f=0;f<a.w+1;f++)s.fillRect(l+4+f*16,d-4,10,6);s.fillStyle=r?"#24243c":m.cloudShade,s.fillRect(l+2,d+13,u-4,2),s.fillStyle=m.black,s.fillRect(l+10,d+5,1,3),s.fillRect(l+u-11,d+5,1,3)}for(const a of i.deco.bushes){const l=Math.round(a.x*k-e),u=16+a.w*16;if(!(l+u<0||l>w)){s.fillStyle=r?"#00504c":m.bush,s.fillRect(l,o-8,u,8);for(let d=0;d<=a.w;d++)s.fillRect(l+2+d*16,o-13,12,6);s.fillStyle=r?"#003020":m.hill,s.fillRect(l,o-2,u,2)}}}flagAndCastle(t,e,s){const i=this.g,o=t.level,r=o.flagCol*k+7-e;if(r<-100||r>w+100)return;const a=1*k-N+4,l=9*k-N;i.fillStyle="#80d010",i.fillRect(r,a,2,l-a),i.fillStyle=m.black,i.fillRect(r-2,a-5,6,6),i.fillStyle="#80d010",i.fillRect(r-1,a-4,4,4);const u=t.phase==="clear"?Math.min(t.phaseT*1.6,l-a-18):0,d=a+2+u;i.fillStyle=m.white;for(let h=0;h<12;h++){const p=13-Math.abs(h-6)*2;i.fillRect(r-p,d+h,p,1)}x(i,E,"W",r-7,d+3,"#00a800");const f=(o.flagCol+5)*k-e,y=10*k-N;for(let h=0;h<2;h++)for(let p=0;p<5;p++)i.drawImage(s.brick,f+p*k,y-(h+1)*k);for(let h=1;h<4;h++)i.drawImage(s.brick,f+h*k,y-3*k);i.fillStyle=re[o.theme];for(let h=0;h<5;h++)i.fillRect(f+h*k+4,y-2*k,8,5);for(let h=1;h<4;h++)i.fillRect(f+h*k+4,y-3*k,8,5);i.fillStyle=m.black,i.fillRect(f+2*k+3,y-20,10,20),i.fillRect(f+2*k+5,y-22,6,2),i.fillRect(f+k+5,y-2*k-10,6,6),i.fillRect(f+3*k+5,y-2*k-10,6,6)}enemy(t,e,s,i){const o=this.g,r=Math.round(t.x-s),a=Math.round(t.y-N);if(r<-24||r>w+24)return;const l=e.face(t.face).image,u=t.kind==="hopper"?e.hopper:e.walker;if(t.state==="squashed"){o.drawImage(l,r-1,a+Y-8,Ot,8);return}if(t.state==="flipped"){o.save(),o.translate(r,a+Y),o.scale(1,-1),o.drawImage(u[0],0,0),o.drawImage(l,-1,6),o.restore();return}const d=u[Math.floor(t.walk/5)%2];o.drawImage(d,r,a+14);const f=Math.floor(t.walk/5)%2;o.drawImage(l,r-1,a-1+f),t.kind==="hopper"&&(i>>4)%2&&(o.fillStyle=m.white,o.fillRect(r+6,a-4+f,2,2))}player(t,e,s,i,o){if(t.state==="off"||t.state==="out"||t.inv>0&&t.state==="alive"&&i>>2&1)return;const r=this.g,a=e.heroes[t.slot],l=Math.round(t.x-s)-1,u=Math.round(t.y-N)-2,d=t.facing>0?0:1;if(t.state==="dying"){r.save(),r.translate(l,u+16),r.scale(1,-1),r.drawImage(a.poses.jump[d],0,0),r.restore();return}let f="stand";t.onGround?Math.abs(t.vx)>.1&&(f=["walk1","stand","walk2","stand"][Math.floor(t.walk/6)%4]):f="jump",r.drawImage(a.poses[f][d],l,u);const y=D(E,o,6)||`P${t.slot+1}`,h=X(E,y),p=Math.round(t.x-s+F/2-h/2),g=Math.round(t.y-N-9);r.fillStyle=U[t.slot].dark,r.fillRect(p-1,g-1,h+2,7),x(r,E,y,p,g,m.white)}nameTag(t,e,s){const i=D(E,t,9);if(!i)return;const o=X(E,i),r=Math.round(e-o/2);r+o<0||r>w||(this.g.fillStyle="rgba(0,0,0,0.55)",this.g.fillRect(r-1,Math.round(s)-1,o+2,7),x(this.g,E,i,r,Math.round(s),m.white))}effects(t,e,s){const i=this.g;for(const o of t.fx){const r=Math.round(o.x-s),a=Math.round(o.y-N);if(o.k==="coin"){const l=t.level.theme===2?e.tilesNight:e.tilesDay;i.drawImage(l.coin[(t.tick>>2)%4],r-4,a)}else if(o.k==="score")x(i,E,String(o.n),r,a,m.white,1,m.black);else if(o.k==="name"){const l=D(T,e.face(o.n).name,14);if(!l)continue;const u=o.slot>=0?U[o.slot].main:m.white,d=X(T,l),f=Math.max(2,Math.min(w-d-2,r-d/2));i.fillStyle=m.black,i.fillRect(f-2,a-2,d+4,11),i.fillStyle=u,i.fillRect(f-2,a+8,d+4,1),x(i,T,l,f,a,m.white)}else if(o.k==="puff"){i.fillStyle=m.white;const l=4-Math.floor(o.t/4);i.fillRect(r-l,a+2,l*2,2),i.fillRect(r+2,a-l,2,l*2)}}}drawHud(t,e,s){const i=this.g;i.fillStyle="rgba(0,0,0,0.35)",i.fillRect(0,0,w,21);const o=t.players.reduce((l,u)=>l+(u.state==="off"?0:u.score),0);x(i,T,`TEAM ${String(o).padStart(7,"0")}`,4,2,m.white,1,m.black),C(i,T,`LEVEL ${s}`,w/2+20,2,m.white,1,m.black);const r=t.players.reduce((l,u)=>l+(u.state==="off"?0:u.coins),0);x(i,T,`¢×${r}`,w-44,2,m.coin,1,m.black);let a=4;for(const l of t.players){if(l.state==="off")continue;const u=U[l.slot];i.fillStyle=u.main,i.fillRect(a,12,6,6),i.fillStyle=m.black,i.fillRect(a+1,14,4,1);const d=D(E,e[l.slot]??"",5)||`P${l.slot+1}`;x(i,E,d,a+8,13,m.white);let f=a+8+X(E,d)+3;l.state==="out"?(x(i,E,"OUT",f,13,m.gray),f+=14):(i.fillStyle="#e40058",i.fillRect(f,13,2,2),i.fillRect(f+3,13,2,2),i.fillRect(f,14,5,2),i.fillRect(f+1,16,3,1),i.fillRect(f+2,17,1,1),x(i,E,String(l.lives),f+6,13,m.white),f+=14),x(i,E,String(l.score),f,13,"#fce0a8"),a+=80}}panel(t,e,s,i,o=m.white){const r=this.g;r.fillStyle=m.black,r.fillRect(t,e,s,i),r.fillStyle=o,r.fillRect(t+1,e+1,s-2,1),r.fillRect(t+1,e+i-2,s-2,1),r.fillRect(t+1,e+1,1,i-2),r.fillRect(t+s-2,e+1,1,i-2)}logo(t,e){const s=this.g,i="WOTFORMER",o=3,r=X(T,i)*o,a=Math.round(w/2-r/2);s.fillStyle=m.brickDark,s.fillRect(a-8,t-4,r+16,7*o+8),s.fillStyle=m.brick,s.fillRect(a-7,t-3,r+14,7*o+6),x(s,T,i,a+2,t+2,m.black,o);const l=["#fcfcfc","#fce0a8","#fcfcfc","#fcbcb0"][(e>>4)%4];x(s,T,i,a,t,l,o)}parade(t,e,s){const i=this.g,o=t.faces.length?t.faces.map(u=>u.image):t.generic,r=26,a=Math.ceil(w/r)+2,l=e*.5%r;for(let u=0;u<a;u++){const d=Math.round(w-u*r+l-r),f=o[(u+Math.floor(e/(r*2)))%o.length],y=Math.floor((e+u*7)/8)%2;i.drawImage(t.walker[y],d,s+14),i.drawImage(f,d-1,s-1+y)}i.fillStyle=m.brick,i.fillRect(0,s+22,w,K-s-22),i.fillStyle=m.black;for(let u=0;u<w;u+=16)i.fillRect(u,s+22,1,K-s-22);i.fillRect(0,s+22,w,1)}}const ln=3e4,cn=3e3;function hn(n){let t=2166136261;for(let e=0;e<n.key.length;e++)t=Math.imul(t^n.key.charCodeAt(e),16777619);return`tv-${(t>>>0).toString(16).padStart(8,"0")}`}class fn{constructor(t,e,s){c(this,"places",[]);c(this,"place",null);c(this,"problem","");c(this,"listing",null);c(this,"taken",0);c(this,"status","open");c(this,"reopenAt",0);c(this,"closed",!1);this.handlers=t,this.title=e,this.max=s}get available(){return rt.available()}get peers(){var t;return((t=this.listing)==null?void 0:t.link.peers.size)??0}async start(){var t,e;if(!this.available){this.problem="No direct connections in this shell";return}await this.refreshPlaces(),(e=(t=Bt())==null?void 0:t.onEvent)==null||e.call(t,s=>{s.type==="neighborhood"&&this.refreshPlaces()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.refreshPlaces()})}async refreshPlaces(){const t=await Ee();if(this.closed)return;this.places=t;const e=this.place&&t.find(s=>s.key===this.place.key);if(e){this.place=e;return}if(t.length===0){this.moveTo(null),this.problem="Nowhere to list this screen: no neighborhoods, no relays";return}this.moveTo(t[0])}cycle(t){if(this.places.length<2)return;const e=this.place?this.places.findIndex(s=>s.key===this.place.key):-1;this.moveTo(this.places[(e+t+this.places.length)%this.places.length])}moveTo(t){this.takeDown(),this.place=t,this.reopenAt=0,this.problem="",t&&this.openIn(t)}takeDown(){const t=this.listing;if(t){this.listing=null,t.gone=!0,t.link.send({t:"bye"}),this.advertise(t,"closed");for(const e of[...t.link.peers])this.handlers.onLeft(e);t.link.close()}}async openIn(t){const e=new rt({onRequest:()=>this.handlers.canSeat(),onJoined:()=>{},onLeft:o=>this.handlers.onLeft(o),onFailed:(o,r)=>{this.handlers.onLeft(o),r!=="rejected"&&this.handlers.onNote(`A phone couldn't connect (${r})`)},onMessage:(o,r)=>this.handlers.onMessage(o,r),onClosed:o=>{this.listing===s&&(this.handlers.onNote(o),this.takeDown(),this.reopenAt=performance.now()+cn)}}),s={place:t,game:hn(t),room:Se(32),link:e,lastAdvert:0,advertising:!1,nextAdvert:null,gone:!1};this.listing=s;const i=await e.open({place:t,room:s.room,admit:!0,identity:"account"});if(this.listing!==s){e.close();return}if(i){this.problem=i,this.listing=null,e.close();return}this.advertise(s,this.status)}setTaken(t){const e=t>=this.max?"full":"open";t===this.taken&&e===this.status||(this.taken=t,this.status=e,this.listing&&this.advertise(this.listing,e))}async advertise(t,e){if(t.nextAdvert=e,!t.advertising){t.advertising=!0;try{for(;t.nextAdvert;){const s=t.nextAdvert;t.nextAdvert=null;const i=()=>({game:t.game,room:t.room,status:s,title:this.title(),keyed:t.link.v149,max:this.max,taken:this.taken});let o=await Yt(t.place,i());for(let r=0;o&&/retry|incomplete|busy/i.test(o)&&r<3&&!t.nextAdvert;r++)await new Promise(a=>setTimeout(a,4e3)),o=await Yt(t.place,i());!t.gone&&this.listing===t&&(this.problem=o??"")}}finally{t.advertising=!1,t.lastAdvert=performance.now()}}}pump(t){if(this.closed)return;if(!this.listing&&this.place&&this.reopenAt&&t>=this.reopenAt){this.reopenAt=0,this.openIn(this.place);return}const e=this.listing,s=Tt()>90?Tt()*800:ln;e&&!e.advertising&&e.lastAdvert&&t-e.lastAdvert>=s&&this.advertise(e,this.status)}get canSendGame(){var t;return((t=this.listing)==null?void 0:t.link.canSendGame)??!1}send(t){var e;(e=this.listing)==null||e.link.send(t)}close(){this.closed=!0,this.takeDown()}}const un=/^([0-9a-f]{64})(?:\.([a-z0-9]{1,8}))?$/i,dn=/^[0-9a-f]{64}$/i;function _e(n){try{const t=new URL(n);return t.protocol==="https:"||t.protocol==="http:"?t:null}catch{return null}}function pn(n){const t=n.toLowerCase();return t==="nostr.build"||t.endsWith(".nostr.build")}function mn(n,t){const e=/^blossom:(?:sha256:)?([0-9a-f]{64})/i.exec(n);if(e)return`blossom:${e[1].toLowerCase()}`;const s=_e(n);if(!s||pn(s.hostname))return null;let i="";try{i=decodeURIComponent(s.pathname.split("/").pop()??"")}catch{return null}const o=un.exec(i);if(!o)return null;const r=[`xs=${s.origin}`];return t&&dn.test(t)&&r.push(`as=${t.toLowerCase()}`),`blossom:${o[1].toLowerCase()}?${r.join("&")}`}function gn(n,t,e){var i;if(!n||n.length>2048)return null;const s=mn(n.trim(),t);return s||(e&&((i=_e(n.trim()))==null?void 0:i.protocol)==="https:"?n.trim():null)}const ft=n=>n.startsWith("https:"),ae=0,ut=3,Nt={target:25,max:40,deadlineMs:45e3,imageTimeoutMs:5e3,concurrency:6,quietMs:2500,chunk:100,maxSecond:400,httpsPerMinute:50,thinFollows:80,secondAfterMs:2500},gt=/^[0-9a-f]{64}$/;function yn(n){let t;try{t=JSON.parse(n)}catch{return null}if(!t||typeof t!="object")return null;const e=o=>typeof o=="string"?o.trim():"",s=(e(t.display_name)||e(t.displayName)||e(t.name)).replace(/\s+/g," ").slice(0,40),i=e(t.picture)||e(t.image);return{name:s,picture:i}}function le(n,t=""){const e=[],s=new Set;for(const i of n.tags){if(i[0]!=="p"||typeof i[1]!="string")continue;const o=i[1].toLowerCase();!gt.test(o)||o===t||s.has(o)||(s.add(o),e.push(o))}return e}function kn(n,t){const e=new Map;for(const s of n)for(const i of s)t.has(i)||e.set(i,(e.get(i)??0)+1);return[...e.entries()].sort((s,i)=>i[1]-s[1]).map(([s])=>s)}class wn{constructor(t,e=6e4){c(this,"uses",[]);this.max=t,this.windowMs=e}take(t){return this.uses=this.uses.filter(e=>t-e<this.windowMs),this.uses.length>=this.max?!1:(this.uses.push(t),!0)}}function bn(n){const t=[...n];for(let e=t.length-1;e>0;e--){const s=Math.floor(Math.random()*(e+1));[t[e],t[s]]=[t[s],t[e]]}return t}function vn(n,t,e){return new Promise((s,i)=>{const o=setTimeout(()=>{e.abort(),i(new Error("timeout"))},t);n.then(r=>{clearTimeout(o),s(r)},r=>{clearTimeout(o),i(r instanceof Error?r:new Error(String(r)))})})}function It(n){return[...new Set(n.map(t=>t.toLowerCase()))].sort().join(",")}class En{constructor(t,e={}){c(this,"faces",[]);c(this,"opts");c(this,"stage","start");c(this,"tried",0);c(this,"roots",[]);c(this,"key","");c(this,"degreeOf",new Map);c(this,"profileAt",new Map);c(this,"considered",new Set);c(this,"askedProfile",new Set);c(this,"queue",[]);c(this,"contacts",new Map);c(this,"firstDegree",[]);c(this,"secondAsked",0);c(this,"secondStarted",!1);c(this,"active",new Set);c(this,"closers",[]);c(this,"pendingAsk",{pks:[],timer:null});c(this,"rankTimer",null);c(this,"lastNews",0);c(this,"started",0);c(this,"https",!0);c(this,"budget");c(this,"timers",[]);c(this,"ticker",null);c(this,"resolveDone",null);c(this,"done");c(this,"faceListeners",new Set);c(this,"onProgress",()=>{});c(this,"pictureOf",new Map);this.src=t,this.opts={...Nt,...e},this.budget=new wn(this.opts.httpsPerMinute),this.done=new Promise(s=>{this.resolveDone=s})}onFace(t){return this.faceListeners.add(t),()=>this.faceListeners.delete(t)}get running(){return this.stage!=="done"&&this.stage!=="start"}start(t,e){var s,i;if(this.stage==="start"){if(e&&(this.onProgress=e),this.roots=[...new Set(t.map(o=>o.toLowerCase()).filter(o=>gt.test(o)))],this.key=It(this.roots),this.started=Date.now(),this.lastNews=this.started,this.roots.length===0){this.stop();return}this.stage="follows",this.report(),this.timers.push(setTimeout(()=>this.stop(),this.opts.deadlineMs)),this.ticker=setInterval(()=>this.check(),Math.max(20,Math.min(250,this.opts.quietMs/4))),this.src.httpsAllowed().then(o=>{this.https=o,o||this.dropHttps()}).catch(()=>{}),(i=(s=this.src).remembered)==null||i.call(s,this.key).then(o=>{for(const r of o)this.candidate(r.pubkey,r.name,r.picture,1)}).catch(()=>{});for(const o of this.roots)this.followsOf(o)}}async run(t,e){return this.start(t,e),await this.done,this.faces}ready(t,e){return this.faces.length>=t||this.stage==="done"?Promise.resolve():new Promise(s=>{const i=setTimeout(r,e),o=this.onFace(()=>{this.faces.length>=t&&r()});this.done.then(r);function r(){clearTimeout(i),o(),s()}})}stop(){var t,e,s;if(this.stage!=="done"){this.stage="done";for(const i of this.closers)i();this.closers=[];for(const i of this.active)i.abort();this.active.clear();for(const i of this.timers)clearTimeout(i);this.pendingAsk.timer&&clearTimeout(this.pendingAsk.timer),this.rankTimer&&clearTimeout(this.rankTimer),this.ticker&&clearInterval(this.ticker),this.faces.length&&((e=(t=this.src).remember)==null||e.call(t,this.key,this.faces.map(i=>({pubkey:i.pubkey,name:i.name,picture:this.pictureOf.get(i.pubkey)??""})).filter(i=>i.picture))),this.report(),(s=this.resolveDone)==null||s.call(this)}}report(t){const e={stage:this.stage,found:this.faces.length,target:this.opts.target,tried:this.tried};t&&(e.latest=t),this.onProgress(e)}async followsOf(t){var i,o;const e=await((o=(i=this.src).ownFollows)==null?void 0:o.call(i,t).catch(()=>{}));if(this.stage==="done")return;if(e!=null&&e.length){this.addFollows(e);return}let s=-1;this.closers.push(this.src.stream([{kinds:[ut],authors:[t]}],r=>{r.kind!==ut||r.pubkey.toLowerCase()!==t||r.created_at<=s||(s=r.created_at,this.addFollows(le(r)))}))}addFollows(t){const e=new Set(this.roots),s=bn(t.map(i=>i.toLowerCase()).filter(i=>gt.test(i)&&!e.has(i)&&!this.degreeOf.has(i)));if(s.length){for(const i of s)this.degreeOf.set(i,1);this.firstDegree.push(...s),this.lastNews=Date.now(),this.askProfiles(s),this.firstDegree.length<this.opts.thinFollows&&this.startSecond()}}askProfiles(t){for(const e of t)this.askedProfile.has(e)||(this.askedProfile.add(e),this.pendingAsk.pks.push(e));this.pendingAsk.timer||!this.pendingAsk.pks.length||(this.pendingAsk.timer=setTimeout(()=>{const e=this.pendingAsk.pks;if(this.pendingAsk={pks:[],timer:null},this.stage==="done")return;const s=[];for(let i=0;i<e.length;i+=this.opts.chunk)s.push({kinds:[ae],authors:e.slice(i,i+this.opts.chunk)});this.closers.push(this.src.stream(s,i=>this.onProfile(i)))},50))}onProfile(t){if(t.kind!==ae||this.stage==="done")return;const e=t.pubkey.toLowerCase(),s=this.degreeOf.get(e);if(!s||(this.profileAt.get(e)??-1)>=t.created_at)return;this.profileAt.set(e,t.created_at),this.lastNews=Date.now();const i=yn(t.content);i!=null&&i.picture&&this.candidate(e,i.name,i.picture,s)}candidate(t,e,s,i){const o=t.toLowerCase();if(this.stage==="done"||this.considered.has(o)||!gt.test(o)||this.roots.includes(o))return;const r=gn(s,o,this.https);r&&(this.considered.add(o),this.pictureOf.set(o,s),this.queue.push({pk:o,name:e||o.slice(0,8),source:r,picture:s,degree:i}),this.pump())}dropHttps(){for(let t=this.queue.length-1;t>=0;t--)ft(this.queue[t].source)&&this.queue.splice(t,1)}startSecond(){if(this.secondStarted||this.stage==="done")return;this.secondStarted=!0,this.stage==="follows"&&(this.stage="friends",this.report());const t=this.firstDegree.slice(0,300),e=[];for(let s=0;s<t.length;s+=this.opts.chunk)e.push({kinds:[ut],authors:t.slice(s,s+this.opts.chunk)});e.length&&this.closers.push(this.src.stream(e,s=>{if(s.kind!==ut||this.stage==="done")return;const i=s.pubkey.toLowerCase();this.degreeOf.get(i)===1&&(this.contacts.set(i,le(s)),this.lastNews=Date.now(),this.rankTimer??(this.rankTimer=setTimeout(()=>{this.rankTimer=null,this.askSecond()},300)))}))}askSecond(){if(this.stage==="done"||this.secondAsked>=this.opts.maxSecond||this.faces.length+this.queue.length+this.active.size>=this.opts.target*2)return;const t=new Set([...this.roots,...this.degreeOf.keys()]),e=kn(this.contacts.values(),t).slice(0,Math.min(150,this.opts.maxSecond-this.secondAsked));if(e.length){this.secondAsked+=e.length;for(const s of e)this.degreeOf.set(s,2);this.lastNews=Date.now(),this.askProfiles(e)}}wanted(){return this.opts.max}pump(){for(;this.stage!=="done"&&this.active.size<this.opts.concurrency&&this.faces.length+this.active.size<this.wanted();){this.queue.sort((s,i)=>s.degree-i.degree||Number(ft(s.source))-Number(ft(i.source)));const t=this.queue.findIndex(s=>!ft(s.source)||this.budget.take(Date.now()));if(t<0)return;const e=this.queue.splice(t,1)[0];this.load(e)}}load(t){const e=new AbortController;this.active.add(e),vn(this.src.loadImage(t.source,e.signal),this.opts.imageTimeoutMs,e).then(s=>{if(this.stage==="done"||this.faces.length>=this.wanted())return;const i={pubkey:t.pk,name:t.name,image:s,degree:t.degree};this.faces.push(i),this.lastNews=Date.now();for(const o of this.faceListeners)o(i);this.report(i)}).catch(()=>{}).finally(()=>{this.tried++,this.active.delete(e),this.stage!=="done"&&(this.report(),this.check(),this.pump())})}check(){if(this.stage==="done"||this.stage==="start")return;if(this.faces.length>=this.opts.max)return this.stop();this.pump();const t=Date.now();!this.secondStarted&&this.faces.length<this.opts.target&&t-this.started>=this.opts.secondAfterMs&&this.startSecond(),this.secondStarted&&this.faces.length+this.queue.length+this.active.size<this.opts.target&&this.askSecond();const e=this.queue.length===0&&this.active.size===0&&!this.pendingAsk.timer&&!this.rankTimer,s=t-this.lastNews>=this.opts.quietMs;e&&s&&(this.faces.length>=this.opts.target||this.secondStarted||t-this.started>this.opts.quietMs*2)&&this.stop()}get elapsedMs(){return this.started?Date.now()-this.started:0}}const Sn=500,An=120,xn=12e3,Mn=15e3,ce=1e3/vi,he=2500,At=6,Cn=3500,Tn=3e3,Ln=600;class Rn{constructor(t,e,s=()=>{}){c(this,"life",new AbortController);c(this,"timers",[]);c(this,"r");c(this,"assets",new rn);c(this,"roster",new Ms(mt));c(this,"host",null);c(this,"phase","lobby");c(this,"sim",null);c(this,"fixed",new We(ce,4));c(this,"last",0);c(this,"tick",0);c(this,"dirty",!0);c(this,"lastDraw",0);c(this,"perf",{fps:60,steps:0,maxSteps:0,maxStepsAt:0,frameMs:0});c(this,"debugHud",!!window.__WOT_DEBUG__);c(this,"navLog","");c(this,"away",!1);c(this,"menu",0);c(this,"wotIndex",0);c(this,"me","");c(this,"myName","");c(this,"note","");c(this,"noteUntil",0);c(this,"wot",new Map);c(this,"current",null);c(this,"source",null);c(this,"meKnown",!1);c(this,"loadingSince",0);c(this,"warmKey","");c(this,"warmSince",0);c(this,"kbdHeld",new Set);c(this,"lastState",0);c(this,"stateDue",!1);c(this,"evSeq",0);c(this,"evLog",[]);c(this,"emptySince",0);c(this,"overAt",0);c(this,"levelShown",0);c(this,"levelBannerUntil",0);c(this,"timing",{start:0,play:0,facesAtPlay:0});this.chip=e,this.onExit=s,this.r=new an(t),window.__WOT_ROLE__&&(window.__wotDisplay=this),window.addEventListener("resize",()=>this.r.resize(),this.on)}get on(){return{signal:this.life.signal}}every(t,e){this.timers.push(window.setInterval(t,e))}async start(){this.initKeys(),this.host=new fn({canSeat:()=>!this.roster.full,onMessage:(s,i)=>this.onMessage(s,i),onLeft:s=>this.phoneGone(s),onNote:s=>this.flash(s.toUpperCase())},()=>this.displayName(),mt),this.host.start(),this.chip.play("title");const t=s=>{this.life.signal.aborted||(this.frame(s),requestAnimationFrame(t))};requestAnimationFrame(t),this.every(()=>{document.visibilityState==="hidden"&&this.pump(performance.now())},250),window.addEventListener("beforeunload",()=>{var s;return(s=this.host)==null?void 0:s.close()},this.on);const e=()=>this.setAway(document.visibilityState==="hidden");document.addEventListener("visibilitychange",e,this.on),window.addEventListener("pagehide",()=>this.setAway(!0),this.on),window.addEventListener("pageshow",e,this.on),this.me=await ti(),this.meKnown=!0;try{if(G("identity","getProfile")){const s=await de();this.myName=((s==null?void 0:s.displayName)||(s==null?void 0:s.name)||"").trim()}}catch{}}setAway(t){if(t!==this.away){if(this.away=t,t){mi(this.phase).pauseGame&&this.setPause(!0),this.chip.suspend();for(const s of this.roster.seats)s==null||s.tracker.setHeld(0,performance.now());this.kbdHeld.clear()}else this.chip.resume(),this.last=0,this.fixed.reset(),this.dirty=!0;this.stateDue=!0}}flash(t,e=3e3){this.dirty=!0,this.note=t,this.noteUntil=performance.now()+e}onMessage(t,e){const s=this.host,i=performance.now();if(t.t==="join"||t.t==="in"){const o=t.t==="join"?t.name??"":"";let r=this.roster.get(t.sid);if(r&&r.pubkey!==e)return;if(r)t.t==="join"&&(this.roster.join(t.sid,o,e,i),this.stateDue=!0);else{const a=this.roster.join(t.sid,o,e,i);if(!a){s.send({t:"full",to:t.sid});return}r=a.seat,this.seated(r)}t.t==="in"?(r.tracker.receive(t,i),t.ts!==void 0&&(!r.echo||t.ts>r.echo.ts)&&(r.echo={ts:t.ts,at:i})):r.tracker.lastHeardMs=i;return}if(t.t==="bye"){const o=this.roster.get(t.sid);o&&o.pubkey===e&&this.roster.leave(t.sid)&&this.unseated(o)}}phoneGone(t){for(const e of this.roster.seats)e&&e.sid!==O&&e.pubkey===t&&this.roster.leave(e.sid)&&this.unseated(e)}seated(t){var e;(e=this.host)==null||e.setTaken(this.roster.count),this.chip.sfx("join"),this.pushEv(t.sid,"join"),this.flash(`${D(T,t.name,12)||`P${t.slot+1}`} JOINED AS ${U[t.slot].name}`),this.sim&&(this.phase==="play"||this.phase==="pause")&&ie(this.sim,t.slot)}unseated(t){var e;(e=this.host)==null||e.setTaken(this.roster.count),this.chip.sfx("leave"),this.flash(`${D(T,t.name,12)||`P${t.slot+1}`} LEFT`),this.sim&&Yi(this.sim,t.slot),this.stateDue=!0}pushEv(t,e){this.evLog.push({i:++this.evSeq,c:t,k:e}),this.evLog.length>12&&this.evLog.shift(),this.stateDue=!0}pump(t){for(const o of this.roster.prune(t,xn))this.unseated(o);const e=this.host;if(!e)return;e.pump(t);const s=t-this.lastState,i=this.away?pi():Sn;if((this.stateDue&&s>=An||s>=i)&&e.canSendGame){this.lastState=t,this.stateDue=!1;const o=this.sim;e.send({t:"st",ph:this.phase,lv:(o==null?void 0:o.levelNo)??0,pl:this.roster.seats.filter(r=>!!r&&r.sid!==O).map(r=>{const a=o==null?void 0:o.players[r.slot],l={c:r.sid,s:r.slot,l:(a==null?void 0:a.lives)??3,sc:(a==null?void 0:a.score)??0,k:(a==null?void 0:a.coins)??0};return r.echo&&(l.et=r.echo.ts,l.eh=Math.round(t-r.echo.at)),l}),ev:this.evLog.slice(-8)})}}displayName(){return this.myName?`${this.myName}'s screen`:"WoTformer screen"}initKeys(){const t=s=>s.key==="Enter"||s.key==="Select"||s.keyCode===23||s.keyCode===66,e=s=>s.key==="Escape"||s.key==="GoBack"||s.key==="BrowserBack"||s.key==="Backspace"||s.key==="p"||s.key==="P";window.addEventListener("keydown",s=>{if(this.chip.unlock(),s.key==="m"||s.key==="M"){this.toggleMusic();return}if(s.key==="F3"||(s.key==="d"||s.key==="D")&&!this.roster.get(O)){this.toggleDebug();return}if(this.roster.get(O)&&(this.phase==="play"||this.phase==="pause")&&this.phase==="play"&&!e(s)){this.kbdHeld.add(this.keyName(s)),s.preventDefault(),s.repeat||this.syncKeyboard();return}if(!(s.repeat&&!s.key.startsWith("Arrow"))){if(s.key==="ArrowUp")this.nav("up");else if(s.key==="ArrowDown")this.nav("down");else if(s.key==="ArrowLeft")this.nav("left");else if(s.key==="ArrowRight")this.nav("right");else if(t(s)||s.key===" "||s.key==="z"||s.key==="Z")this.nav("ok");else if(e(s))this.phase==="lobby"&&(s.key==="Escape"||s.key==="GoBack"||s.key==="BrowserBack")?this.exit():this.nav("back");else return;s.preventDefault()}},this.on),window.addEventListener("keyup",s=>{this.kbdHeld.delete(this.keyName(s))&&this.syncKeyboard()},this.on),window.addEventListener("blur",()=>{this.kbdHeld.clear(),this.syncKeyboard()},this.on)}keyName(t){return t.key.length===1?t.key.toLowerCase():t.key}syncKeyboard(){const t=this.roster.get(O);if(!t)return;const e=this.kbdHeld;let s=0;(e.has("ArrowLeft")||e.has("a"))&&(s|=b.LEFT),(e.has("ArrowRight")||e.has("d"))&&(s|=b.RIGHT),(e.has("ArrowDown")||e.has("s"))&&(s|=b.DOWN),(e.has("z")||e.has(" ")||e.has("ArrowUp")||e.has("w"))&&(s|=b.A),(e.has("x")||e.has("c")||e.has("Enter")||e.has("Shift"))&&(s|=b.B),t.tracker.setHeld(s,performance.now())}menuItems(){var t;return(t=this.host)!=null&&t.available?["start","wot","place","keyboard","music","back"]:["start","wot","keyboard","music","back"]}nav(t){var i;if(this.dirty=!0,this.phase==="lobby"&&this.noteNav(t),this.phase==="loading"){(t==="ok"||t==="start"||t==="back")&&performance.now()-this.loadingSince>he&&this.beginPlay();return}if(this.phase==="play"){(t==="back"||t==="start")&&this.setPause(!0);return}if(this.phase==="pause"){t==="start"||t==="ok"||t==="back"?this.setPause(!1):(t==="down"||t==="up")&&this.toLobby();return}if(this.phase==="over"){(t==="ok"||t==="start")&&performance.now()-this.overAt>1500&&this.toLobby();return}const e=this.menuItems();if(t==="start")return this.startGame();if(t==="up"||t==="down"){this.menu=(this.menu+(t==="up"?e.length-1:1))%e.length,this.chip.sfx("move");return}const s=e[this.menu];if(t==="left"||t==="right"||t==="ok")if(s==="start"&&t==="ok")this.startGame();else if(s==="wot"){const o=this.wotOptions().length;this.wotIndex=(this.wotIndex+(t==="left"?o-1:1))%o,this.chip.sfx("move")}else s==="back"&&t==="ok"?this.exit():s==="place"?((i=this.host)==null||i.cycle(t==="left"?-1:1),this.chip.sfx("move")):s==="keyboard"&&(t==="ok"||t==="left"||t==="right")?this.toggleKeyboard():s==="music"&&(t==="ok"||t==="left"||t==="right")&&this.toggleMusic()}toggleKeyboard(){if(this.roster.get(O)){const t=this.roster.leave(O);t&&this.unseated(t)}else{const t=this.roster.join(O,"Keys","",performance.now());t?this.seated(t.seat):this.flash("ALL 4 SEATS ARE TAKEN")}}exit(){var t;if(!this.life.signal.aborted){(t=this.host)==null||t.close(),this.host=null,this.life.abort();for(const e of this.timers.splice(0))window.clearInterval(e);this.chip.stop(),this.onExit()}}toggleMusic(){const t=this.chip.toggleMute();this.flash(t?"SOUND OFF":"SOUND ON",1200)}wotOptions(){const t=[],e=new Set;this.me&&(t.push({label:this.myName?`ME (${this.myName})`:"ME (THIS SCREEN)",roots:[this.me]}),e.add(this.me));for(const s of this.roster.seats)!(s!=null&&s.pubkey)||e.has(s.pubkey)||(e.add(s.pubkey),t.push({label:`P${s.slot+1} ${s.name}`,roots:[s.pubkey]}));return e.size>=2&&t.push({label:"EVERYONE HERE",roots:[...e]}),t.length===0&&t.push({label:"NOBODY KNOWN YET",roots:[]}),this.wotIndex>=t.length&&(this.wotIndex=0),t}startGame(){var o,r;if(this.roster.count===0){const a=this.roster.join(O,"Keys","",performance.now());a&&this.seated(a.seat)}const t=this.wotOptions()[this.wotIndex];this.chip.sfx("select"),this.timing={start:performance.now(),play:0,facesAtPlay:0};const e=this.entry(t);if(this.current=e,this.stopOthers(e),this.ensureLoading(e),!e.art.length&&!((o=e.loader)!=null&&o.running)&&(t.roots.length===0?this.flash("NO KEY TO FOLLOW: GENERIC FOES",4e3):Et()||this.flash("THIS SHELL CANNOT READ NOSTR: GENERIC FOES",4e3)),e.art.length>=At||!((r=e.loader)!=null&&r.running)){this.beginPlay();return}this.phase="loading",this.loadingSince=performance.now(),this.stateDue=!0;const s=e.loader,i=()=>{this.phase==="loading"&&this.current===e&&this.beginPlay()};s.ready(At,Cn).then(()=>e.art.length?void 0:s.ready(1,Tn)).then(i)}entry(t){const e=It(t.roots);let s=this.wot.get(e);return s||(s={key:e,label:t.label,roots:t.roots,art:[],seen:new Set,loader:null,progress:null},this.wot.set(e,s)),s.label=t.label,s}ensureLoading(t){var s;if((s=t.loader)!=null&&s.running||t.art.length>=Nt.target||!t.roots.length||!Et())return;this.source??(this.source=new ni(this.me));const e=new En(this.source,fe()?{concurrency:3}:{});t.loader=e,e.onFace(i=>{t.seen.has(i.pubkey)||(t.seen.add(i.pubkey),t.art.push({name:i.name,image:i.image}),this.phase==="loading"&&this.current===t&&this.chip.sfx("face"))}),e.start(t.roots,i=>{t.progress=i})}stopOthers(t){var e;for(const s of this.wot.values())s!==t&&((e=s.loader)==null||e.stop())}warmUp(t){var o;if(!this.meKnown||!Et())return;const e=this.wotOptions()[this.wotIndex],s=It(e.roots);if(s!==this.warmKey){this.warmKey=s,this.warmSince=t;return}if(t-this.warmSince<Ln||!e.roots.length)return;const i=this.entry(e);(o=i.loader)!=null&&o.running||i.art.length>=Nt.target||(this.stopOthers(i),this.ensureLoading(i))}beginPlay(){var s;const t=((s=this.current)==null?void 0:s.art)??[];this.assets.faces=t,this.assets.genericOnly=t.length===0;const e=crypto.getRandomValues(new Uint32Array(1))[0]|0;this.sim=qi(e,this.assets.faces.length);for(const i of this.roster.seats)i&&ie(this.sim,i.slot);this.phase="play",this.timing.play=performance.now(),this.timing.facesAtPlay=this.assets.faces.length,this.fixed.reset(),this.levelShown=0,this.emptySince=0,this.chip.play("level"),this.stateDue=!0}setPause(t){t&&this.phase==="play"?(this.phase="pause",this.chip.sfx("pause"),this.chip.stop()):!t&&this.phase==="pause"&&(this.phase="play",this.chip.sfx("pause"),this.chip.play("level")),this.stateDue=!0}toLobby(){this.phase="lobby",this.sim=null,this.menu=0,this.chip.play("title"),this.stateDue=!0}frame(t){const e=this.last?t-this.last:0;this.last=t,this.tick=Math.floor(t/ce),e>0&&(this.perf.fps=this.perf.fps*.95+1e3/e*.05),this.chip.pump(),this.pump(t),this.phase!=="play"&&this.menuFromControllers(t),this.phase==="lobby"&&this.warmUp(t),this.sim&&this.assets.faces.length>this.sim.faceCount&&(Qi(this.sim,this.assets.faces.length),this.assets.genericOnly=!1);let s=0;if(this.phase==="play"&&this.sim){const i=this.fixed.advance(e);for(;s<i&&this.phase==="play";s++)this.simTick(t)}else this.fixed.reset();if(this.perf.steps=s,(s>=this.perf.maxSteps||t-this.perf.maxStepsAt>1e3)&&(this.perf.maxSteps=s,this.perf.maxStepsAt=t),this.phase==="play"||this.dirty||t-this.lastDraw>=50){this.dirty=!1,this.lastDraw=t;const i=performance.now();this.draw(t),this.perf.frameMs=this.perf.frameMs*.9+(performance.now()-i)*.1}}menuFromControllers(t){for(const e of this.roster.seats){if(!e||e.sid===O)continue;const i=e.tracker.tick(t).pressed;i&b.START?this.nav("start"):i&b.A?this.nav("ok"):i&b.UP?this.nav("up"):i&b.DOWN?this.nav("down"):i&b.LEFT?this.nav("left"):i&b.RIGHT?this.nav("right"):i&b.SELECT?this.toggleMusic():i&b.B&&this.phase!=="lobby"&&this.nav("back")}}simTick(t){const e=this.sim,s=[];let i=!1;for(const a of this.roster.seats){if(!a)continue;const l=a.tracker.tick(t);s[a.slot]=l,l.pressed&b.START&&(i=!0),l.pressed&b.SELECT&&this.toggleMusic()}const o=e.levelNo,r=e.phase;Vi(e,s);for(const a of e.events)this.onSimEvent(a);e.levelNo!==o&&(this.chip.play("level"),this.levelShown=0),r!=="over"&&e.phase==="over"&&(this.phase="over",this.overAt=performance.now(),this.stateDue=!0),De(e)===0?(this.emptySince||(this.emptySince=t),t-this.emptySince>Mn&&this.toLobby()):this.emptySince=0,i&&this.setPause(!0)}sidOf(t){var e;return((e=this.roster.seats[t])==null?void 0:e.sid)??""}onSimEvent(t){const s={jump:"jump",shoot:"shoot",stomp:"stomp",kill:"kill",coin:"coin",bump:"bump",die:"die","1up":"1up"}[t.k];s&&this.chip.sfx(s),t.k==="clear"&&this.chip.play("clear"),t.k==="over"&&this.chip.play("over");const i=t.slot>=0?this.sidOf(t.slot):"";t.k==="die"?this.pushEv(i,"die"):t.k==="stomp"||t.k==="kill"||t.k==="coin"||t.k==="1up"?this.pushEv(i,t.k):(t.k==="clear"||t.k==="over")&&this.pushEv("",t.k)}names(){return this.roster.seats.map(t=>(t==null?void 0:t.name)??"")}draw(t){const e=this.r,s=e.g;if(this.phase==="lobby")this.drawLobby();else if(this.phase==="loading")this.drawLoading(t);else if(this.sim){const i=this.sim;e.drawWorld(i,this.assets,this.names()),e.drawHud(i,this.names(),i.levelNo),this.levelShown!==i.levelNo&&(this.levelShown=i.levelNo,this.levelBannerUntil=t+2200),t<this.levelBannerUntil&&i.phase==="play"&&(e.panel(w/2-70,60,140,this.assets.genericOnly?44:30),C(s,T,`LEVEL ${i.levelNo}`,w/2,66,m.white,1),C(s,E,this.assets.genericOnly?"GENERIC FOES":`${this.assets.faces.length} FRIENDS IN THE WAY`,w/2,78,"#fce0a8"),this.assets.genericOnly&&(C(s,E,"NO WOT FACES LOADED",w/2,86,m.gray),C(s,E,"THESE ARE NOT REAL PEOPLE",w/2,93,m.gray))),i.phase==="clear"&&(e.panel(w/2-64,50,128,22,"#f8b800"),C(s,T,"LEVEL CLEAR!",w/2,57,"#f8b800")),this.assets.genericOnly&&x(s,E,"GENERIC FOES",w-50,23,m.gray),this.phase==="pause"&&(s.fillStyle="rgba(0,0,0,0.55)",s.fillRect(0,0,w,K),e.panel(w/2-80,56,160,60),C(s,T,"PAUSED",w/2,64,m.white,2),C(s,E,"START / OK: PLAY ON",w/2,88,m.white),C(s,E,"DOWN: BACK TO THE LOBBY",w/2,96,m.white),C(s,E,"SELECT / M: SOUND ON-OFF",w/2,104,m.white)),this.phase==="over"&&this.drawOver(t),this.roster.count===0&&(e.panel(w/2-90,120,180,20),C(s,E,"EVERYONE LEFT. PICK UP A CONTROLLER!",w/2,127,m.white))}if(t<this.noteUntil&&this.note){const i=D(E,this.note,70),o=X(E,i);s.fillStyle=m.black,s.fillRect(w/2-o/2-3,K-12,o+6,10),C(s,E,i,w/2,K-10,"#fce0a8")}this.debugHud&&this.drawDebug(),e.present()}drawDebug(){var o;const t=this.r.g,e=this.chip.stats,s=(o=this.current)==null?void 0:o.loader,i=[`FPS ${this.perf.fps.toFixed(0)} DRAW ${this.perf.frameMs.toFixed(1)}MS`,`SIM ${this.perf.steps}/FRAME MAX ${this.perf.maxSteps} DROP ${this.fixed.dropped}`,`AUDIO LATE ${e.lateMs.toFixed(0)}MS SKIP ${e.skipped} AHEAD ${e.lookaheadMs}`,`FACES ${this.assets.faces.length}${s!=null&&s.running?" LOADING":""} SCALE ${+this.r.scale.toFixed(2)}X`];t.fillStyle="rgba(0,0,0,0.7)",t.fillRect(w-150,22,150,i.length*7+3),i.forEach((r,a)=>x(t,E,r,w-148,24+a*7,"#80d010"))}noteNav(t){this.navLog=(this.navLog+t[0]).slice(-4),this.navLog==="uudd"&&(this.navLog="",this.toggleDebug())}toggleDebug(){this.debugHud=!this.debugHud,this.dirty=!0}placeLine(){const t=this.host;if(!(t!=null&&t.available))return"NO DIRECT CONNECTIONS HERE: KEYBOARD / REMOTE ONLY";if(t.problem)return t.problem.toUpperCase();const e=t.place;if(!e)return"FINDING WHERE TO LIST THIS SCREEN...";const s=[e.kind==="online"?"LISTED ONLINE":`LISTED IN ${e.label.toUpperCase()}`];return e.kind==="neighborhood"&&e.reachable!==void 0&&s.push(`${e.reachable} IN REACH`),t.peers&&s.push(`${t.peers} PHONE${t.peers===1?"":"S"} CONNECTED`),s.join(" - ")}drawLobby(){var l,u,d,f;const t=this.r,e=t.g;e.fillStyle=m.skyDay,e.fillRect(0,0,w,K),t.logo(6,this.tick),C(e,E,D(E,this.placeLine(),62),w/2,31,m.white),t.panel(8,38,150,62),x(e,E,"PLAYERS",13,42,"#fce0a8");for(let y=0;y<mt;y++){const h=this.roster.seats[y],p=50+y*12,g=U[y];if(e.drawImage(this.assets.heroes[y].poses.stand[0],13,p-3,8,11),h){const v=h.sid===O?"KEYS":"PHONE";x(e,E,`${D(E,h.name,14)||`P${y+1}`}`,25,p,m.white),x(e,E,v,128,p,g.main)}else x(e,E,`${g.name}: OPEN SEAT`,25,p,m.gray)}t.panel(162,38,150,62),["ON A PHONE:","OPEN WOTFORMER IN MYCO","AND PICK CONTROLLER.","","NO PHONE? ARROWS MOVE,","Z JUMP, X RUN/FIRE.","M: SOUND ON/OFF"].forEach((y,h)=>x(e,E,y,167,43+h*8,h===0?"#fce0a8":m.white));const i=this.menuItems(),o=this.wotOptions(),r={start:"START GAME",wot:`FOES FROM: < ${D(T,o[this.wotIndex].label,18)} >`,place:`PHONES JOIN: ${(((l=this.host)==null?void 0:l.places.length)??0)>1?"< ":""}${D(T,(((d=(u=this.host)==null?void 0:u.place)==null?void 0:d.label)??"-").toUpperCase(),14)}${(((f=this.host)==null?void 0:f.places.length)??0)>1?" >":""}`,keyboard:`KEYBOARD PLAYER: ${this.roster.get(O)?"IN":"OUT"}`,music:`SOUND: ${this.chip.muted?"OFF":"ON"}`,back:"BACK"},a=i.length;t.panel(8,a>4?101:103,w-16,a>4?50:46),i.forEach((y,h)=>{const p=(a>4?104:108)+h*(a>5?8:a>4?9:10),g=h===this.menu;g&&(this.tick>>4)%2===0&&x(e,T,"▶",14,p,"#f8b800"),x(e,T,r[y],24,p,g?"#f8b800":m.white)}),this.r.parade(this.assets,this.tick,152)}drawLoading(t){const s=this.r.g;s.fillStyle=m.black,s.fillRect(0,0,w,K);const i=this.current;if(!i)return;const o=i.progress,r=i.art.length,a=At;C(s,T,"LOADING YOUR WEB OF TRUST",w/2,10,m.white),C(s,E,D(E,`FOES FROM ${i.label}`,60),w/2,21,"#fce0a8"),C(s,T,`FOUND ${r}/${a} FRIENDS`,w/2,32,r>=a?"#80d010":"#f8b800",1),C(s,E,"THE REST JOIN WHILE YOU PLAY",w/2,126,m.gray);const l=(o==null?void 0:o.stage)==="friends"?"FOLLOWS AND FRIENDS OF FRIENDS":(o==null?void 0:o.stage)==="follows"?"FOLLOWS AND THEIR PICTURES":"READING FOLLOW LISTS";C(s,E,`${l}${".".repeat((this.tick>>4)%4)}`,w/2,44,m.gray);const u=14;i.art.slice(0,42).forEach(({image:f},y)=>{const h=16+y%u*21,p=56+Math.floor(y/u)*24;s.drawImage(f,h,p)});const d=200;s.fillStyle="#3c3c3c",s.fillRect(w/2-d/2,136,d,6),s.fillStyle="#f8b800",s.fillRect(w/2-d/2,136,Math.round(d*Math.min(r,a)/a),6),C(s,E,`TRIED ${(o==null?void 0:o.tried)??0} PICTURES. NO PICTURE, NO FOE.`,w/2,147,m.gray),t-this.loadingSince>he&&(this.tick>>4)%2===0&&C(s,E,"OK / A: START WITH WHAT WE HAVE",w/2,160,m.white)}drawOver(t){const e=this.r,s=e.g,i=this.sim;s.fillStyle="rgba(0,0,0,0.6)",s.fillRect(0,0,w,K),e.panel(30,28,w-60,124,"#e40058"),C(s,T,"GAME OVER",w/2,36,m.white,2);const o=i.players.reduce((a,l)=>a+(l.state==="off"?0:l.score),0);C(s,T,`TEAM SCORE ${o}  LEVEL ${i.levelNo}`,w/2,58,"#f8b800"),x(s,E,"PLAYER",44,74,m.gray),x(s,E,"SCORE",150,74,m.gray),x(s,E,"FOES",196,74,m.gray),x(s,E,"COINS",230,74,m.gray);let r=84;for(const a of i.players){if(a.state==="off")continue;const l=D(E,this.names()[a.slot]??"",18)||`P${a.slot+1}`;s.fillStyle=U[a.slot].main,s.fillRect(44,r,5,5),x(s,E,l,54,r,m.white),x(s,E,String(a.score),150,r,m.white),x(s,E,String(a.kills),196,r,m.white),x(s,E,String(a.coins),230,r,m.white),r+=10}t-this.overAt>1500&&(this.tick>>4)%2===0&&C(s,E,"START / OK: BACK TO THE LOBBY",w/2,138,m.white)}}const W=n=>document.getElementById(n);function On(){return window.__NAPPLET_ALLOW_STANDALONE__===!0?!0:!!document.querySelector('meta[name="napplet-allow-standalone"]')}function Dn(){var v;if(!On()&&!globalThis.napplet){W("guard").classList.remove("hidden"),W("chooser").classList.add("hidden");return}const n=new Je,t=rt.available(),e=W("chooser"),s=W("pickDisplay"),i=W("pickController"),o=W("chooserNote");t||(i.disabled=!0,o.textContent="No direct connections (NAP-WEBRTC) in this shell, so phones can’t connect. The display still plays with a keyboard. Open WoTformer in Myco for the full thing.");let r=!1;const a=[s,i],u=((v=window.matchMedia)==null?void 0:v.call(window,"(pointer: coarse)").matches)&&t?i:s,d=()=>a.includes(document.activeElement),f=()=>{!r&&!d()&&u.focus()};f(),window.addEventListener("focus",f);const y=M=>{if(r||!["ArrowLeft","ArrowUp","ArrowRight","ArrowDown"].includes(M.key))return;if(M.preventDefault(),!d()){u.focus();return}const lt=a.indexOf(document.activeElement),Ht=a[(lt+1)%2];(Ht.disabled?a[lt]:Ht).focus()};document.addEventListener("keydown",y);const h=()=>{W("tv").classList.add("hidden"),e.classList.remove("hidden"),r=!1,u.focus()},p=M=>{r||(r=!0,n.unlock(),e.classList.add("hidden"),M==="display"?(W("tv").classList.remove("hidden"),new Rn(W("screen"),n,h).start()):t&&new ui(h).start())};s.addEventListener("click",()=>p("display")),i.addEventListener("click",()=>p("controller"));const g=window.__WOT_ROLE__;(g==="display"||g==="controller")&&p(g),window.addEventListener("pointerdown",()=>n.unlock()),window.addEventListener("keydown",()=>n.unlock())}Dn();</script>
    <style rel="stylesheet" crossorigin>:root{--bg: #000;--text: #fcfcfc;--sky: #5c94fc;--brick: #c84c0c;--gold: #f8b800;--shell: #c9c6bf;--shell-dark: #9c9890;--panel: #1a1a1a;--red: #d0142c;--seat: #7c7c7c;--seat-dark: #3c3c3c;--pix: ui-monospace, "SF Mono", Menlo, Consolas, "DejaVu Sans Mono", "Courier New", monospace;color-scheme:dark}*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--text);font-family:var(--pix);overflow:hidden;-webkit-user-select:none;user-select:none;-webkit-tap-highlight-color:transparent;touch-action:none}.hidden{display:none!important}button{font-family:inherit}.chooser{min-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1.2rem;padding:1rem;background:linear-gradient(to bottom,transparent 82%,#000 82%,#000 83%,var(--brick) 83%),var(--sky);text-align:center}.logo{margin:0;font-size:clamp(2rem,8vw,4.5rem);font-weight:900;letter-spacing:.06em;text-transform:uppercase;color:#fcfcfc;text-shadow:4px 4px 0 #000,-2px -2px 0 var(--brick)}.tag{margin:0;font-weight:700;text-shadow:2px 2px 0 #000;max-width:40rem}.roles{display:flex;gap:1.5rem;flex-wrap:wrap;justify-content:center}.role{display:flex;flex-direction:column;align-items:center;gap:.3rem;width:min(42vw,18rem);padding:1.2rem 1rem;background:#000;color:#fcfcfc;border:4px solid #fcfcfc;box-shadow:6px 6px #000;cursor:pointer;outline:none}.role:focus-visible,.role:focus,.role:hover{border-color:var(--gold);color:var(--gold);transform:translate(-2px,-2px);box-shadow:8px 8px #000}.role:disabled{opacity:.45;cursor:not-allowed}.role-icon{font-size:2.6rem}.role-name{font-size:1.5rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em}.role-sub{font-size:.85rem}.chooser-note{margin:0;font-size:.85rem;text-shadow:1px 1px 0 #000;max-width:36rem}.tv{position:fixed;top:0;right:0;bottom:0;left:0;background:#000;cursor:none;display:flex;align-items:center;justify-content:center}.tv canvas{display:block;image-rendering:crisp-edges;image-rendering:pixelated}.ctl{position:fixed;top:0;right:0;bottom:0;left:0;background:#111}.pad{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;flex-direction:column;background:linear-gradient(#d6d3cc,var(--shell) 30%,var(--shell-dark));padding:max(8px,env(safe-area-inset-top)) max(10px,env(safe-area-inset-right)) 8px max(10px,env(safe-area-inset-left));touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;overscroll-behavior:none}.pad *{-webkit-touch-callout:none;touch-action:none}.pad canvas.zones{position:absolute;top:0;right:0;bottom:0;left:0;width:100%;height:100%;pointer-events:none;z-index:5}@media(orientation:portrait){.pad{inset:auto;top:0;left:100vw;width:100vh;height:100vw;transform-origin:top left;transform:rotate(90deg)}}.pad-top{display:flex;align-items:center;gap:.6rem;color:#222;font-weight:800;font-size:.8rem;min-height:1.8rem}.leave{border:2px solid #333;background:#e8e6e0;color:#222;width:2rem;height:1.8rem;font-weight:900;border-radius:4px}.who{text-transform:uppercase}.stats{margin-left:auto;text-transform:uppercase}.pad-body{flex:1;display:grid;grid-template-columns:1fr 1fr 1fr;align-items:center;background:var(--panel);border:3px solid #000;border-radius:6px;margin:6px 0;padding:2vh 3vw;box-shadow:inset 0 0 0 4px #2b2b2b}.pad-left,.pad-right,.pad-mid{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%}.dpad{--s: min(17vh, 13vw);position:relative;width:calc(var(--s) * 3);height:calc(var(--s) * 3)}.dpad .arm,.dpad .hub{position:absolute;width:var(--s);height:var(--s);background:#141414;box-shadow:inset 0 -4px #000,inset 0 2px #3a3a3a}.dpad .up{left:var(--s);top:0;border-radius:4px 4px 0 0}.dpad .down{left:var(--s);bottom:0;border-radius:0 0 4px 4px}.dpad .left{left:0;top:var(--s);border-radius:4px 0 0 4px}.dpad .right{right:0;top:var(--s);border-radius:0 4px 4px 0}.dpad .hub{left:var(--s);top:var(--s);box-shadow:none}.dpad .hub:after{content:"";position:absolute;top:30%;right:30%;bottom:30%;left:30%;border-radius:50%;background:#0b0b0b;box-shadow:inset 0 2px 3px #000}.dpad .arm:after{content:"";position:absolute;top:35%;right:35%;bottom:35%;left:35%;border-radius:1px;background:#2c2c2c}.dpad .arm.on,.pill.on,.round.on{filter:brightness(1.6)}.dpad .arm.on{background:#3a3a3a}.brand{color:var(--red);font-weight:900;font-style:italic;font-size:clamp(.7rem,2.4vw,1.2rem);text-transform:uppercase;letter-spacing:.04em;margin-bottom:3vh;text-align:center}.brand b{font-size:1.3em}.pills{display:flex;gap:4vw;background:#c9c6bf;padding:1.6vh 2.4vw;border-radius:6px}.pill-wrap,.btn-wrap{display:flex;flex-direction:column;align-items:center;gap:.6vh}.pill-wrap label,.btn-wrap label{color:var(--red);font-weight:900;font-size:clamp(.6rem,1.8vw,.95rem)}.pill-wrap label{color:#222}.pill{width:min(11vw,5.5rem);height:min(5vh,1.6rem);min-height:18px;border-radius:999px;background:#333;border:3px solid #111;box-shadow:inset 0 -3px #000}.seat-stripe{margin-top:3vh;width:70%;height:6px;background:var(--seat);box-shadow:0 2px 0 var(--seat-dark);border-radius:3px}.ab{display:flex;gap:4vw;align-items:flex-end;transform:rotate(-12deg)}.ab .btn-wrap:last-child{margin-bottom:4vh}.ab .btn-wrap{background:#c9c6bf;padding:1.4vh;border-radius:10px}.round{width:min(20vh,14vw);height:min(20vh,14vw);border-radius:50%;background:radial-gradient(circle at 35% 30%,#ff5a6e,var(--red) 55%,#8a0012);box-shadow:0 5px #5a000c,inset 0 -3px 6px #00000059}.round.on{transform:translateY(4px);box-shadow:0 1px #5a000c}.hint{color:#888;font-size:.7rem;margin:5vh 0 0;text-transform:uppercase}.ctl-status{margin:0;color:#222;font-weight:800;font-size:.8rem;min-height:1rem;text-align:center}.picker{position:absolute;top:12%;right:15%;bottom:12%;left:15%;background:#000;border:4px solid #fcfcfc;box-shadow:8px 8px #0009;padding:1rem;overflow:auto;text-align:center}@media(orientation:portrait){.picker{top:15%;right:8%;bottom:15%;left:8%}}.picker h2{margin:0 0 .8rem;text-transform:uppercase;color:var(--gold);letter-spacing:.08em}.displays{list-style:none;margin:0;padding:0;display:grid;gap:.6rem}.display-btn{width:100%;padding:.8rem;background:#222;color:#fcfcfc;border:3px solid #fcfcfc;font-weight:800;font-size:1rem}.display-btn:disabled{opacity:.5}.picker-note{color:#bcbcbc;font-size:.85rem}.guard{position:fixed;top:0;right:0;bottom:0;left:0;display:grid;place-items:center;background:#000;padding:1rem}.guard-card{max-width:32rem;border:4px solid #fcfcfc;padding:1.2rem}.guard-card h1{font-size:1.2rem;margin-top:0;color:var(--gold)}</style>
  </head>
  <body>
    <!-- First: what is this device? -->
    <main id="chooser" class="chooser">
      <h1 class="logo">WoTformer</h1>
      <p class="tag">An 8-bit romp through your Web of Trust. One big screen, up to four phones.</p>
      <div class="roles">
        <button id="pickDisplay" class="role" type="button">
          <span class="role-icon" aria-hidden="true">📺</span>
          <span class="role-name">Display</span>
          <span class="role-sub">The big screen. Runs the game.</span>
        </button>
        <button id="pickController" class="role" type="button">
          <span class="role-icon" aria-hidden="true">🎮</span>
          <span class="role-name">Controller</span>
          <span class="role-sub">This phone becomes a game pad.</span>
        </button>
      </div>
      <p id="chooserNote" class="chooser-note">Remote: arrows to choose, OK to start.</p>
    </main>

    <!-- Display: one canvas, everything drawn in it. -->
    <section id="tv" class="tv hidden">
      <canvas id="screen"></canvas>
    </section>

    <!-- Controller: the pad. -->
    <section id="ctl" class="ctl hidden">
      <div id="pad" class="pad">
        <header class="pad-top no-pad">
          <button id="ctlLeave" class="leave" type="button" aria-label="Leave">✕</button>
          <span id="ctlWho" class="who"></span>
          <span id="ctlStats" class="stats"></span>
        </header>
        <div class="pad-body">
          <div class="pad-left">
            <div id="dpad" class="dpad" aria-label="D-pad">
              <span class="arm up" data-btn="UP"></span>
              <span class="arm left" data-btn="LEFT"></span>
              <span class="hub"></span>
              <span class="arm right" data-btn="RIGHT"></span>
              <span class="arm down" data-btn="DOWN"></span>
            </div>
          </div>
          <div class="pad-mid">
            <div class="brand"><b>WoT</b> Entertainment System</div>
            <div class="pills">
              <div class="pill-wrap"><span class="pill" data-btn="SELECT"></span><label>SELECT</label></div>
              <div class="pill-wrap"><span class="pill" data-btn="START"></span><label>START</label></div>
            </div>
            <div class="seat-stripe"></div>
          </div>
          <div class="pad-right">
            <div class="ab">
              <div class="btn-wrap"><span class="round" data-btn="B"></span><label>B</label></div>
              <div class="btn-wrap"><span class="round" data-btn="A"></span><label>A</label></div>
            </div>
            <p class="hint">A jump · B run &amp; fire</p>
          </div>
        </div>
        <p id="ctlStatus" class="ctl-status" aria-live="polite"></p>
      </div>
      <div id="picker" class="picker no-pad">
        <h2>Find a screen</h2>
        <ul id="displays" class="displays"></ul>
        <p id="pickerNote" class="picker-note"></p>
      </div>
    </section>

    <div id="guard" class="guard hidden" role="alert">
      <div class="guard-card">
        <h1>WoTformer needs a napplet runtime</h1>
        <p>This is a NIP-5D napplet. Open it inside a napplet shell (Myco, for the mesh) — it can't run as a standalone page.</p>
      </div>
    </div>

  </body>
</html>