Back to Doodle Duo
SOURCE / PINNED RELEASE

Made of little things.

Doodle Duo

Release
fd722bab2fff…
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>Doodle Duo</title><meta name="description" content="Two phones, one doodler: co-op Doodle Jump, one button each. Play nearby, in your neighborhoods, or online"><meta name="napplet-id" content="doodleduo"><meta name="napplet-requires" content="outbox webrtc"><meta name="napplet-optional" content="identity intent neighbor relay theme upload"><link rel="icon" href="data:image/png;base64,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" type="image/png">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    
    <script type="module" crossorigin>var bn=Object.defineProperty;var kn=(e,t,n)=>t in e?bn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var f=(e,t,n)=>kn(e,typeof t!="symbol"?t+"":t,n);function vn(){const e=new Map;function t(i,s){if(e.has(i))throw new Error(`NAP domain "${i}" is already registered`);e.set(i,s)}function n(i){const s=i.type.indexOf(".");if(s<=0)return!1;const r=i.type.slice(0,s),c=e.get(r);return c?(c(i),!0):!1}function o(){return Array.from(e.keys())}return{registerNap:t,dispatch:n,getRegisteredDomains:o}}var wn=vn(),de=wn.registerNap,Sn="relay";function Tn(){var t;const e=window;if(!((t=e.napplet)!=null&&t.relay))throw new Error("window.napplet.relay is unavailable -- runtime did not inject the relay domain");return e.napplet.relay}function jt(e,t,n,o){return Tn().subscribe(e,t,n,o)}de(Sn,e=>{});var xn="identity";function Ze(){var t;const e=window;if(!((t=e.napplet)!=null&&t.identity))throw new Error("window.napplet.identity is unavailable -- runtime did not inject this domain");return e.napplet.identity}function Ln(){return Ze().getPublicKey()}function Nn(){return Ze().getProfile()}function Mn(){return Ze().getFollows()}de(xn,e=>{});var Pn="theme";function Wt(){var t;const e=window;if(!((t=e.napplet)!=null&&t.theme))throw new Error("window.napplet.theme is unavailable -- runtime did not inject this domain");return e.napplet.theme}function An(){return Wt().get()}function En(e){return Wt().onChanged(e)}de(Pn,e=>{});var Rn="outbox";function et(){var t;const e=window;if(!((t=e.napplet)!=null&&t.outbox))throw new Error("window.napplet.outbox is unavailable -- runtime did not inject this domain");return e.napplet.outbox}function Cn(e,t){return et().query(e,t)}function me(e,t){return et().subscribe(e,t)}function te(e,t){return et().publish(e,t)}de(Rn,e=>{});var $n="intent";function _n(){var t;const e=window;if(!((t=e.napplet)!=null&&t.intent))throw new Error("window.napplet.intent is unavailable -- runtime did not inject this domain");return e.napplet.intent}function In(e,t,n){return _n().open(e,t,n)}de($n,e=>{});function On(){const e=window;if(!e.napplet)throw new Error("window.napplet is unavailable -- runtime did not inject the napplet namespace");return e.napplet}function he(e){const n=On()[e];if(!n)throw new Error(`window.napplet.${String(e)} is unavailable -- runtime did not inject this domain`);return n}var Bt={info(){return he("upload").info()},upload(e){return he("upload").upload(e)},status(e){return he("upload").status(e)},onStatus(e){return he("upload").onStatus(e)}};const x=422,k=552,Yn=60,_e=.2,dt=10,ue=70,tt=17,re=55,X=40,ae=26,Ae=30,Dn=75;function ut(e){e.rng=e.rng+1831565813|0;let t=e.rng;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function Fn(e){return e>=5e3?[2,3,3,3,4,4,4,4]:e>=2e3?[2,2,2,3,3,3,3,4,4,4,4]:e>=1e3?[2,2,2,3,3,3,3,3]:e>=500?[1,1,1,1,1,2,2,2,2,3,3,3,3]:e>=100?[1,1,1,1,2,2]:[1]}function Kt(e,t){const n=ut(e)*(x-ue),o=Fn(e.score);let i=o[Math.floor(ut(e)*o.length)];return i===3&&e.broken<1?e.broken++:i===3&&e.broken>=1&&(i=1,e.broken=0),{x:n,y:t,type:i,vx:1,flag:0,state:0}}function Ee(e){const t={rng:e|0,tick:0,px:x/2-re/2,py:k,vx:0,vy:11,facing:-1,prevL:!1,prevR:!1,baseY:k-5,plats:[],broken:0,score:0,springX:-ae,springY:-Ae,springState:0,debrisX:0,debrisY:0,debrisOn:!1,jumpCount:0,dead:!1,deathTicks:0,over:!1};let n=0;for(let o=0;o<dt;o++)t.plats.push(Kt(t,n)),n+=k/dt;return t}function ne(e){const t=new Array(e.plats.length);for(let n=0;n<e.plats.length;n++){const o=e.plats[n];t[n]={x:o.x,y:o.y,type:o.type,vx:o.vx,flag:o.flag,state:o.state}}return{...e,plats:t}}function Gn(e){return e.vy<-7&&e.vy>-15}function je(e){e.vy=-8}function We(e,t,n){if(!e.over){if(e.tick++,e.dead){Kn(e);return}Hn(e),jn(e),Wn(e,t,n)}}function Hn(e){for(const t of e.plats)t.type===2&&((t.x<0||t.x+ue>x)&&(t.vx*=-1),t.x+=t.vx),t.flag===1&&!e.debrisOn&&e.jumpCount===0&&(e.debrisX=t.x,e.debrisY=t.y,e.debrisOn=!0,e.jumpCount++);e.debrisOn&&(e.debrisY+=8,e.debrisY>k&&(e.debrisOn=!1))}function jn(e){const t=e.plats[0];t.type===1||t.type===2?(e.springX=t.x+ue/2-ae/2,e.springY=t.y-tt-10,e.springY>k/1.1&&(e.springState=0)):(e.springX=-ae,e.springY=-Ae)}function Wn(e,t,n){if(t&&!e.prevL&&(e.facing=-1),n&&!e.prevR&&(e.facing=1),e.prevL=t,e.prevR=n,t?(e.px+=e.vx,e.vx-=.15):(e.px+=e.vx,e.vx<0&&(e.vx+=.1)),n?(e.px+=e.vx,e.vx+=.15):(e.px+=e.vx,e.vx>0&&(e.vx-=.1)),e.vx>8?e.vx=8:e.vx<-8&&(e.vx=-8),e.py+X>e.baseY&&e.baseY<k&&je(e),e.baseY>k&&e.py+X>k){e.dead=!0;return}if(e.px>x?e.px=-re:e.px<-re&&(e.px=x),e.py>=k/2-X/2)e.py+=e.vy,e.vy+=_e;else{for(let o=0;o<e.plats.length;o++){const i=e.plats[o];e.vy<0&&(i.y-=e.vy),i.y>k&&(e.plats[o]=Kt(e,i.y-k))}e.baseY-=e.vy,e.vy+=_e,e.vy>=0&&(e.py+=e.vy,e.vy+=_e),e.score++}Bn(e)}function ft(e,t,n,o,i){return e.px+15<t+o&&e.px+re-15>t&&e.py+X>n&&e.py+X<n+i}function Bn(e){for(const t of e.plats)if(e.vy>0&&t.state===0&&ft(e,t.x,t.y,ue,tt))if(t.type===3&&t.flag===0){t.flag=1,e.jumpCount=0;continue}else if(t.type===4&&t.state===0)je(e),t.state=1;else{if(t.flag===1)continue;je(e)}e.vy>0&&e.springState===0&&ft(e,e.springX,e.springY,ae,Ae)&&(e.springState=1,e.vy=-16)}function Kn(e){for(const t of e.plats)t.y-=12;e.springY-=12,e.py+=6,e.debrisOn=!1,e.deathTicks++,e.deathTicks>=Dn&&(e.over=!0)}const Ie=new DataView(new ArrayBuffer(8));function Xn(e){let t=2166136261;const n=o=>{Ie.setFloat64(0,o),t=Math.imul(t^Ie.getUint32(0),16777619),t=Math.imul(t^Ie.getUint32(4),16777619)};n(e.rng),n(e.tick),n(e.px),n(e.py),n(e.vx),n(e.vy),n(e.baseY),n(e.score),n(e.springState),n(e.dead?1:0);for(const o of e.plats)n(o.x),n(o.y),n(o.type*4+o.flag*2+o.state),n(o.vx);return t>>>0}const Xt={PLAT_W:ue,PLAT_H:tt,PLAYER_W:re,PLAYER_H:X,SPRING_W:ae,SPRING_H:Ae},G=4,pe=2,Un=6,Jn=G*1e3/60,ht=45,pt=15,qn=240,Oe=1e3/Yn;class Ut{constructor(t,n){f(this,"role");f(this,"seed");f(this,"confirmed");f(this,"confirmedFrame",0);f(this,"tick",0);f(this,"carryMs",0);f(this,"sampledFrame",-1);f(this,"localKnown",pe-1);f(this,"inputDelay",pe);f(this,"local",[]);f(this,"remote",[]);f(this,"remoteKnown",-1);f(this,"remoteLatest",-1);f(this,"ackedByRemote",-1);f(this,"remoteAdv",0);f(this,"hashes",new Map);f(this,"pendingCheck",null);f(this,"desynced",!1);f(this,"changed",!1);f(this,"lastShown",null);f(this,"correctionX",0);f(this,"correctionY",0);f(this,"correctionScroll",0);f(this,"rttMs",0);f(this,"lastProbe",null);this.seed=t,this.role=n,this.confirmed=Ee(t);for(let o=0;o<pe;o++)this.local[o]=!1}get frame(){return Math.floor(this.tick/G)}get stalled(){return this.frame-(this.remoteKnown+1)>=ht&&this.tick%G===0}get over(){return this.confirmed.over}get confirmedState(){return this.confirmed}advance(t,n){if(this.confirmed.over)return!1;const o=(this.frame-this.remoteLatest-this.remoteAdv)/2,i=o>1?Math.max(.88,1-(o-1)*.04):1;for(this.carryMs+=Math.min(t,250)*i,this.changed=!1;this.carryMs>=Oe;){if(this.tick%G===0){const s=this.frame;if(s>this.sampledFrame){if(s-(this.remoteKnown+1)>=ht){this.carryMs=0;break}const r=s+this.inputDelay;if(this.sampledFrame=s,r>this.localKnown){for(let c=this.localKnown+1;c<r;c++)this.local[c]=this.local[this.localKnown];this.local[r]=n,this.local[r-1]!==n&&(this.changed=!0),this.localKnown=r}}}this.tick++,this.carryMs-=Oe}return this.confirm(),this.changed}tuneDelay(){if(!this.rttMs)return;const t=Math.ceil((this.rttMs/2+40)/Jn);this.inputDelay=Math.min(Un,Math.max(pe,t))}get alpha(){return Math.min(1,Math.max(0,this.carryMs/Oe))}nextOf(t){const n=ne(t);return this.run(n,t.tick+1),n}predicted(){const t=ne(this.confirmed);if(this.run(t,this.tick),this.correctionX=0,this.correctionY=0,this.correctionScroll=0,this.lastShown&&this.lastShown.tick<=t.tick&&!t.dead){const n=ne(this.lastShown);if(this.run(n,this.tick),!n.dead){const o=x+Xt.PLAYER_W;let i=n.px-t.px;i-=Math.round(i/o)*o,this.correctionX=i,this.correctionY=n.py-t.py,this.correctionScroll=n.baseY-t.baseY}}return this.lastShown=t,t}run(t,n){const o=this.remoteKnown>=0?this.remote[this.remoteKnown]:!1;for(let i=t.tick;i<n;i++){const s=Math.floor(i/G),r=this.local[s]??!1,c=s<=this.remoteKnown?this.remote[s]:o;if(We(t,...this.buttons(r,c)),t.over)break}}get partnerHeld(){const t=Math.min(this.frame,this.remoteKnown);return t>=0?this.remote[t]??!1:!1}outgoing(t){const n=this.localKnown,o=Math.max(this.ackedByRemote+1,n-qn+1,0);let i="";for(let r=o;r<=n;r++)i+=this.local[r]?"1":"0";const s={from:o,bits:i,f:this.sampledFrame,ack:this.remoteKnown,adv:this.frame-this.remoteLatest};return this.pendingCheck&&(s.cf=this.pendingCheck.cf,s.h=this.pendingCheck.h),t!==void 0&&(s.ts=Math.round(t),this.lastProbe&&(s.et=this.lastProbe.ts,s.eh=Math.round(t-this.lastProbe.at))),s}receive(t,n){const o=t.f>=this.remoteLatest;if(n!==void 0&&(t.ts!==void 0&&(!this.lastProbe||t.ts>this.lastProbe.ts)&&(this.lastProbe={ts:t.ts,at:n}),t.et!==void 0&&t.eh!==void 0)){const i=n-t.et-t.eh;i>=0&&i<3e4&&(this.rttMs=this.rttMs?this.rttMs*.8+i*.2:i)}for(let i=0;i<t.bits.length;i++){const s=t.from+i;this.remote[s]===void 0&&(this.remote[s]=t.bits.charCodeAt(i)===49)}for(;this.remote[this.remoteKnown+1]!==void 0;)this.remoteKnown++;if(t.f>this.remoteLatest&&(this.remoteLatest=t.f),t.ack>this.ackedByRemote&&(this.ackedByRemote=t.ack),o&&(this.remoteAdv=t.adv),t.cf!==void 0&&t.h!==void 0){const i=this.hashes.get(t.cf);i!==void 0&&i!==t.h&&(this.desynced=!0)}this.confirm()}confirm(){const t=Math.min(this.remoteKnown,this.localKnown);for(;this.confirmedFrame<=t&&!this.confirmed.over;){const n=this.confirmedFrame,[o,i]=this.buttons(this.local[n],this.remote[n]);for(let s=0;s<G;s++)We(this.confirmed,o,i);if(this.confirmedFrame++,this.confirmedFrame%pt===0){const s=Xn(this.confirmed);this.hashes.set(this.confirmedFrame,s),this.hashes.delete(this.confirmedFrame-pt*40),this.pendingCheck={cf:this.confirmedFrame,h:s}}}}inputLog(){const t=[],n=[];for(let o=0;o<this.confirmedFrame;o++){const[i,s]=this.buttons(this.local[o],this.remote[o]);t.push(i),n.push(s)}return{L:t,R:n}}buttons(t,n){return this.role==="L"?[t,n]:[n,t]}}const zn=15e4;function gt(e){const t=[];let n=!1,o=0;for(const i of e)i===n?o++:(t.push(o),n=i,o=1);return t.push(o),t.join(".")}function yt(e,t=zn){if(typeof e!="string"||!/^\d+(\.\d+)*$/.test(e)||e.length>2e4)return null;const n=[];let o=!1;for(const i of e.split(".")){const s=Number(i);if(!Number.isSafeInteger(s)||n.length+s>t)return null;for(let r=0;r<s;r++)n.push(o);o=!o}return n}function Vn(e){if(!Number.isSafeInteger(e.seed))return null;const t=yt(e.L),n=yt(e.R);if(!t||!n||t.length!==n.length||t.length===0)return null;const o=Ee(e.seed);for(let i=0;i<t.length&&!o.over;i++)for(let s=0;s<G;s++)We(o,t[i],n[i]);return o.over?o.score:null}const Be=1420,Jt="doodleduo",Qn=10,Zn=32,mt=/^[0-9a-f]{64}$/;function O(e){return typeof e!="string"?"":e.replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,Zn)}function eo(e){let t;try{t=JSON.parse(e.content)}catch{return null}return!t||t.v!==1||!Number.isSafeInteger(t.score)||t.score<0||typeof t.L!="string"||typeof t.R!="string"||!t.pk||!mt.test(String(t.pk.L))||!mt.test(String(t.pk.R))||e.pubkey!==t.pk.L&&e.pubkey!==t.pk.R?null:{content:t,key:`${t.seed}|${t.L}|${t.R}`}}function to(e){const t={v:1,seed:e.seed,L:gt(e.log.L),R:gt(e.log.R),score:e.score,pk:{L:e.players.L.pk,R:e.players.R.pk},names:{L:O(e.players.L.name),R:O(e.players.R.name)}};return{kind:Be,content:JSON.stringify(t),tags:[["t",Jt],["p",e.partnerPk],["score",String(e.score)],["client","doodleduo"]],created_at:Math.floor(Date.now()/1e3)}}async function no(e,t){try{const n=e.kind==="neighborhood"?await te(t,{relays:[e.address],toOutbox:!1}):await te(t);return n.ok?null:`Couldn't publish: ${n.error??"publish failed"}`}catch(n){return`Couldn't publish: ${n instanceof Error?n.message:"publish failed"}`}}class oo{constructor(t){f(this,"entries",new Map);f(this,"seen",new Set);f(this,"subs",[]);this.onChange=t}open(t){this.close();const n={kinds:[Be],"#t":[Jt],limit:500};for(const o of t)try{if(o.kind==="neighborhood")this.subs.push(jt([n],i=>this.add(i),()=>{},{relay:o.address}));else{const i=me([n]);i.on("event",s=>this.add(s)),this.subs.push(i)}}catch{}}close(){for(const t of this.subs.splice(0))t.close()}addEvent(t){this.add({event:t})}top(){return[...this.entries.values()].sort((t,n)=>n.score-t.score||t.at-n.at).slice(0,Qn)}add(t){var r,c;const n=t.event;if(!n||n.kind!==Be||this.seen.has(n.id))return;this.seen.add(n.id);const o=eo(n);if(!o)return;const i=this.entries.get(o.key);if(i){i.signers.add(n.pubkey),i.at=Math.min(i.at,n.created_at),this.onChange();return}const{content:s}=o;Vn(s)===s.score&&(this.entries.set(o.key,{score:s.score,L:{pk:s.pk.L,name:O((r=s.names)==null?void 0:r.L)},R:{pk:s.pk.R,name:O((c=s.names)==null?void 0:c.R)},signers:new Set([n.pubkey]),at:n.created_at}),this.onChange())}}function qt(e,t,n){return e==="L"?{L:t,R:n}:{L:n,R:t}}function B(){const e=globalThis.napplet,t=e==null?void 0:e.webrtc;if(t&&typeof t.open=="function"&&typeof t.send=="function"&&typeof t.onEvent=="function")return t}function zt(e){return typeof e.admit=="function"}const nt=35050,H=30078,Ke="doodleduo:";let be=!1;const U="soy.app-data/1",Xe="games",le="doodleduo.game";let bt=null;function so(){return bt??(bt=(async()=>{var t,n;const e=(t=window.napplet)==null?void 0:t.shell;if(!(e!=null&&e.ready))return null;try{const o=await Promise.race([e.ready(),new Promise(c=>setTimeout(()=>c(null),2e3))]),i=(n=o==null?void 0:o.capabilities)==null?void 0:n.appData;if(!i||i.profile!==U||typeof i.scope!="string"||!i.scope)return null;const s=c=>Array.isArray(c)?c.filter(l=>typeof l=="string"):[],r=s(i.defaultRelays);return{scope:i.scope,relays:r.length?r:s(i.relays).slice(0,1)}}catch{return null}})()),bt}const Vt="wss://relay.napplet.soy";async function io(e){const t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}async function kt(){const e=[`${Ue}:35129:doodleduo`,Re,`${Ue}:doodleduo`];return Promise.all(e.map(async t=>({scope:await io(JSON.stringify([U,t])),relays:[Vt]})))}let vt=null;const Qt=new Map;function ro(e,t){const n=s=>{var r;return((r=e.tags.find(c=>c[0]===s))==null?void 0:r[1])??""},o=n("d"),i=n("status")==="closed";return{kind:H,created_at:e.created_at,tags:[["d",`${U}:${t.scope}:${Xe}:${o}`],["s",t.scope],["c",Xe],["L",U],["l",le,U],["v","1"]],content:JSON.stringify({schema:le,version:1,title:n("title")||"A game",previous:Qt.get(o)??null,deleted:i,data:i?null:{room:n("room"),status:n("status"),keyed:n("identity")==="account",expires:Number(n("expiration"))}})}}const Ue="bbb5dda0e15567979f0543407bdc2033d6f0bbb30f72512a981cfdb2f09e2747",Re=`35129:${Ue}:doodleduo`,Zt=90,ot=600;function Je(){return be?ot:Zt}const ao=200,A=(e,t)=>e.tags.find(n=>n[0]===t);function lo(e,t){var l,u,h,g,y,q,at,lt;if(e.kind===H&&((l=A(e,"L"))==null?void 0:l[1])===U)return co(e,t);if(e.kind!==nt&&e.kind!==H||!e.tags.find(ct=>ct[0]==="a"&&ct[1]===Re)||((u=A(e,"version"))==null?void 0:u[1])!=="1")return null;const o=(h=A(e,"d"))==null?void 0:h[1],i=e.kind===H?o!=null&&o.startsWith(Ke)?o.slice(Ke.length):void 0:o,s=(g=A(e,"room"))==null?void 0:g[1];if(!i||!s||s.length>128||i.length>64)return null;const r=((y=A(e,"status"))==null?void 0:y[1])??"open";if(!["open","full","closed"].includes(r))return null;const c=Number(((q=A(e,"expiration"))==null?void 0:q[1])??e.created_at+Zt);return{key:`${e.pubkey}:${i}`,game:i,room:s,host:e.pubkey,title:O((at=A(e,"title"))==null?void 0:at[1])||"A game",status:r,keyed:((lt=A(e,"identity"))==null?void 0:lt[1])==="account",place:t,createdAt:e.created_at,expires:c}}function Te(e){const t=Math.floor(Date.now()/1e3);return{kind:nt,content:"",created_at:t,tags:[["d",e.game],["a",Re,"","protocol"],["version","1"],["gate","open"],["room",e.room],["capacity","2",e.status==="open"?"1":"2"],["status",e.status],["identity",e.keyed?"account":"ephemeral"],["title",e.title],["expiration",String(t+Je())],["client","doodleduo"]]}}function Ye(e){const t=n=>{var o;return((o=e.tags.find(i=>i[0]===n))==null?void 0:o[1])??""};return{game:t("d"),room:t("room"),status:t("status"),title:t("title"),keyed:t("identity")==="account"}}function co(e,t){var u,h,g;if(((u=A(e,"c"))==null?void 0:u[1])!==Xe||((h=A(e,"l"))==null?void 0:h[1])!==le)return null;const o=(((g=A(e,"d"))==null?void 0:g[1])??"").split(":").pop()??"";let i;try{i=JSON.parse(e.content)}catch{return null}if(i.schema!==le||!o||o.length>64)return null;const s=i.data??{},r=typeof s.room=="string"?s.room:"",c=i.deleted===!0?"closed":s.status,l=typeof s.expires=="number"?s.expires:e.created_at+ot;return!r&&c!=="closed"||r.length>128||!["open","full","closed"].includes(c)?null:{key:`${e.pubkey}:${o}`,game:o,room:r,host:e.pubkey,title:O(typeof i.title=="string"?i.title:"")||"A game",status:c,keyed:s.keyed===!0,place:t,createdAt:e.created_at,expires:l}}function uo(e){return{...e,kind:H,tags:e.tags.map(t=>t[0]==="d"?["d",Ke+t[1]]:t)}}async function wt(e,t){const n=[],o=(l,u)=>(l&&n.push(`${u}: ${l.replace(/^Couldn't list the game: /,"")}`),l),i=()=>`Couldn't list the game. ${n.join(" · ")}`,s=async l=>{try{const u=e.kind==="neighborhood"?await te(l,{relays:[e.address],toOutbox:!1}):await te(l);return u.ok?null:`Couldn't list the game: ${u.error??"publish failed"}`}catch(u){return u instanceof Error?`Couldn't list the game: ${u.message}`:"Couldn't list the game."}},r=async l=>{var g;be=!0;const u=Te(Ye(t)),h=Ye(u).game;try{const y=await te(ro(u,l),{relays:l.relays,toOutbox:!1});if(!y.ok)return`Couldn't list the game: ${y.error??"publish failed"}`;const q=((g=y.event)==null?void 0:g.id)??y.eventId;return q&&Qt.set(h,q),vt=l,null}catch(y){return y instanceof Error?`Couldn't list the game: ${y.message}`:"Couldn't list the game."}};if(e.kind==="online"){const l=vt??await so();if(l)return r(l);const u=B();if(u&&!zt(u)){const h=await kt();for(const[g,y]of h.entries())if(!o(await r(y),`app-data ${g+1}`))return null}}if(!be){const l=o(await s(t),"kind 35050");if(!l)return null;if(!/kind/i.test(l))return i();be=!0,t=Te(Ye(t))}const c=o(await s(uo(t)),"kind 30078");if(!c)return null;if(!/kind/i.test(c)||e.kind!=="online"||n.some(l=>l.startsWith("app-data")))return i();for(const[l,u]of(await kt()).entries())if(!o(await r(u),`app-data ${l+1}`))return null;return i()}class fo{constructor(){f(this,"follows",new Set);f(this,"fof",new Set)}async load(t){var o;try{this.follows=new Set(await Mn())}catch{return}t();const n=[...this.follows].slice(0,ao);if(n.length!==0)try{const i=await Cn([{kinds:[3],authors:n}]);for(const s of i.events)for(const r of((o=s.event)==null?void 0:o.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 ho{constructor(t){f(this,"adverts",new Map);f(this,"subs",[]);this.onChange=t}open(t,n){this.close();const o=Math.floor(Date.now()/1e3)-ot,i={kinds:[nt,H],"#a":[Re],since:o};for(const s of t){const r=c=>this.take(c,s);try{if(s.kind==="neighborhood")this.subs.push(jt([i],r,()=>{},{relay:s.address}));else{const l=me([{kinds:[H],"#l":[le],since:o}],{relays:[Vt]});l.on("event",r),this.subs.push(l);const u=me([i]);u.on("event",r),this.subs.push(u);const h=[...n.follows,...n.fof].slice(0,500);if(h.length>0){const g=me([i],{authors:h});g.on("event",r),this.subs.push(g)}}}catch{}}}close(){for(const t of this.subs.splice(0))t.close()}take(t,n){const o=t.event;if(!o)return;const i=lo(o,n);if(!i)return;const s=this.adverts.get(i.key);s&&s.createdAt>=i.createdAt||(this.adverts.set(i.key,i),this.onChange())}list(t,n){const o=Math.floor(Date.now()/1e3),i=new Map;for(const s of this.adverts.values()){if(n.has(s.game))continue;const r=`${s.host}|${s.place.key}`,c=i.get(r);(!c||s.createdAt>c.createdAt)&&i.set(r,s)}return[...i.values()].filter(s=>s.status==="open"&&s.expires>o).map(s=>({...s,tier:t.tier(s.host)})).sort((s,r)=>s.tier-r.tier||r.createdAt-s.createdAt)}}const St=["Bouncy","Springy","Wobbly","Zippy","Jolly","Hoppy","Sneaky","Fuzzy","Lofty","Giddy","Plucky","Dizzy","Snappy","Breezy","Perky","Nimble"],Tt=["Frog","Gecko","Lemur","Otter","Kiwi","Panda","Moose","Newt","Puffin","Yak","Koala","Quokka","Ferret","Tapir","Badger","Llama"];function Y(e){const t=parseInt(e.slice(0,2),16)||0,n=parseInt(e.slice(2,4),16)||0;return`${St[t%St.length]} ${Tt[n%Tt.length]}`}function en(){const e=globalThis.napplet,t=e==null?void 0:e.neighbor;if(t&&typeof t.list=="function")return t}const po="nearby";function ge(e){return e.autoAccept&&e.name===po}const tn="https://zapstore.dev/apps/app.myco",go="qpzry9x8gf2tvdw0s3jn54khce6mua7l";function yo(e){const t=[996825010,642813549,513874426,1027748829,705979059];let n=1;for(const o of e){const i=n>>>25;n=(n&33554431)<<5^o;for(let s=0;s<5;s++)i>>>s&1&&(n^=t[s])}return n}function mo(e){if(!/^[0-9a-f]{64}$/i.test(e))return null;const t=[];let n=0,o=0;for(let l=0;l<64;l+=2)for(n=n<<8|parseInt(e.slice(l,l+2),16),o+=8;o>=5;)o-=5,t.push(n>>>o&31);o>0&&t.push(n<<5-o&31);const i="npub",s=[...[...i].map(l=>l.charCodeAt(0)>>5),0,...[...i].map(l=>l.charCodeAt(0)&31)],r=yo([...s,...t,0,0,0,0,0,0])^1,c=Array.from({length:6},(l,u)=>r>>>5*(5-u)&31);return`${i}1${[...t,...c].map(l=>go[l]).join("")}`}function xt(e){const t=mo(e.pk);return t?`nostr:${t}`:e.name}function bo(e,t){return[`Doodle Duo: we scored ${e} 🐸`,"",`◀ left button — ${xt(t.L)}`,`▶ right button — ${xt(t.R)}`,"","Two phones, one doodler, no internet.",`Beat us! Get Myco: ${tn}`].join(`
`)}function ko(e,t,n=!1){const o=/^https?:\/\/[^\s]+$/i.test(t),i=n&&/^blossom:sha256:[0-9a-f]{64}$/.test(t);return o||i?`${t}

${e}`:e}const vo={kind:"online",key:"online",label:"Online"};function wo(){var t;const e=globalThis.napplet;return typeof((t=e==null?void 0:e.outbox)==null?void 0:t.publish)=="function"}async function So(){const e=[],t=en();if(t){let n=[];try{n=await t.list()}catch{}const o=(Array.isArray(n)?n:[]).filter(r=>typeof r.address=="string"&&r.address),i=o.filter(ge),s=o.filter(r=>!ge(r)).sort((r,c)=>r.name.localeCompare(c.name));for(const r of[...i,...s])e.push({kind:"neighborhood",key:r.address,label:ge(r)?"Nearby":r.name,address:r.address,nearby:ge(r)})}return wo()&&e.push(vo),e}function To(e){return e.kind==="neighborhood"?{neighborhood:e.address}:{relays:xo}}const xo=["wss://nos.lol","wss://relay.damus.io","wss://relay.primal.net"],Lo="doodleduo",No="doodleduo/1",Mo=2;function z(){const e=crypto.getRandomValues(new Uint8Array(8));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function st(){return crypto.getRandomValues(new Uint32Array(1))[0]}function nn(e,t,n){const o=Math.min(e>>>0,t>>>0),i=Math.max(e>>>0,t>>>0);let s=2166136261;for(const r of[o,i,n>>>0])for(let c=0;c<4;c++)s=Math.imul(s^r>>>c*8&255,16777619);return s|0}const w=e=>typeof e=="number"&&Number.isFinite(e),Po=e=>typeof e=="string"&&e.length>0&&e.length<64,Ao=e=>e==="L"||e==="R",Lt=e=>e===void 0||typeof e=="string"&&e.length<=64;function Eo(e){const t=e;if(!t||typeof t!="object"||t.v!==1||!Po(t.g))return null;switch(t.t){case"join":return w(t.nonce)&&Lt(t.name)?t:null;case"accept":return Lt(t.name)?t:null;case"start":return w(t.hostNonce)&&w(t.guestNonce)&&Ao(t.hostRole)?t:null;case"in":return w(t.r)&&w(t.n)&&w(t.from)&&t.from>=0&&typeof t.bits=="string"&&t.bits.length<=512&&/^[01]*$/.test(t.bits)&&w(t.f)&&w(t.ack)&&w(t.adv)&&(t.cf===void 0||w(t.cf))&&(t.h===void 0||w(t.h))&&(t.ts===void 0||w(t.ts))&&(t.et===void 0||w(t.et))&&(t.eh===void 0||w(t.eh))?t:null;case"again":return w(t.r)&&w(t.nonce)?t:null;case"bye":return t;case"full":return w(t.n)?t:null;default:return null}}class Ce{constructor(t){f(this,"sessionId",null);f(this,"events",null);f(this,"inFlight",0);f(this,"closed",!1);f(this,"admits",!1);f(this,"v149",!1);f(this,"hostNamed",!1);f(this,"sendMs",0);f(this,"recvMs",0);this.handlers=t}static available(){return B()!==void 0}async open(t){var i;const n=B();if(!n)return"This shell has no direct connections (NAP-WEBRTC).";const o=zt(n);this.v149=o,this.admits=t.admit&&o,this.hostNamed=!!t.host&&o,this.events=n.onEvent(s=>this.onEvent(s));try{const s=o?To(t.place):void 0,{session:r}=await n.open({scope:{type:"room",room:t.room,...this.hostNamed?{peers:[t.host]}:{}},channel:Lo,protocol:No,...o?{identity:t.ephemeral?"ephemeral":"account"}:{},...this.admits?{admission:"napplet"}:{},...s?{signaling:s}:{}});return this.closed?(n.close(r.id).catch(()=>{}),null):(this.sessionId=r.id,null)}catch(s){return(i=this.events)==null||i.close(),this.events=null,s instanceof Error?`Couldn't connect: ${s.message}`:"Couldn't connect."}}onEvent(t){var n,o,i,s;if(!(!this.sessionId||t.sessionId!==this.sessionId))switch(t.type){case"request":{const{pubkey:r}=t,c=((o=(n=this.handlers).onRequest)==null?void 0:o.call(n,r))??!1;(s=(i=B())==null?void 0:i.admit)==null||s.call(i,this.sessionId,r,c).catch(()=>{});return}case"peer":{const r=t;r.state==="joined"?this.handlers.onJoined(r.pubkey):r.state==="left"?this.handlers.onLeft(r.pubkey):r.state==="failed"&&r.reason!=="rejected"&&this.handlers.onTrouble(`Couldn't reach them (${r.reason??"failed"}).`);return}case"message":{const r=t;if(typeof r.at=="number"){const l=Math.max(0,Date.now()-r.at);this.recvMs=this.recvMs?this.recvMs*.8+l*.2:l}const c=Eo(r.payload);c&&this.handlers.onMessage(c,r.from);return}case"closed":{const r=t;this.handlers.onTrouble(r.reason?`Connection ended: ${r.reason}`:"Connection ended.");return}default:return}}get canSendGame(){return this.inFlight<Mo}send(t){const n=B();if(!n||!this.sessionId)return;const o=performance.now();this.inFlight++,n.send(this.sessionId,{v:1,...t}).then(()=>{const i=performance.now()-o;this.sendMs=this.sendMs?this.sendMs*.8+i*.2:i}).catch(()=>{}).finally(()=>{this.inFlight--})}close(){var n,o;this.closed=!0,(n=this.events)==null||n.close(),this.events=null;const t=this.sessionId;this.sessionId=null,t&&((o=B())==null||o.close(t).catch(()=>{}))}}const{PLAT_W:W,PLAT_H:F,PLAYER_W:qe,PLAYER_H:Nt,SPRING_W:Mt,SPRING_H:V}=Xt,Ro="#fbf7ea",Co="rgba(120, 150, 190, 0.18)",ke="#2b2a28",ze={1:["#86c440","#4e8a1f"],2:["#5ab0e6","#2c6e9c"],3:["#b98250","#6d4524"],4:["#ffffff","#9a9a9a"]};class Pt{constructor(t){f(this,"ctx");f(this,"scale",1);f(this,"offX",0);f(this,"offY",0);this.canvas=t,this.ctx=t.getContext("2d")}resize(){const t=window.devicePixelRatio||1,n=this.canvas.getBoundingClientRect();this.canvas.width=Math.max(1,Math.round(n.width*t)),this.canvas.height=Math.max(1,Math.round(n.height*t)),this.scale=Math.min(this.canvas.width/x,this.canvas.height/k),this.offX=(this.canvas.width-x*this.scale)/2,this.offY=(this.canvas.height-k*this.scale)/2}draw(t,n,o=0){const i=this.ctx;i.setTransform(1,0,0,1,0,0),i.fillStyle=Ro,i.fillRect(0,0,this.canvas.width,this.canvas.height),i.setTransform(this.scale,0,0,this.scale,this.offX,this.offY),i.save(),i.beginPath(),i.rect(0,0,x,k),i.clip(),this.grid(t);for(const s of t.plats)this.platform(s);t.debrisOn&&this.debris(t.debrisX,t.debrisY,t.tick),t.springY>-V&&this.spring(t.springX,t.springY,t.springState===1),t.baseY<k&&(i.fillStyle="#7a6a55",i.fillRect(0,t.baseY,x,5)),this.doodler(t,n,o),i.restore(),i.fillStyle=ke,i.font="bold 22px ui-rounded, system-ui, sans-serif",i.textBaseline="top",i.fillText(String(t.score),12,10)}drawMascot(t){const n=this.ctx,o=120,i=120,s=Math.min(this.canvas.width/o,this.canvas.height/i);n.setTransform(1,0,0,1,0,0),n.clearRect(0,0,this.canvas.width,this.canvas.height),n.setTransform(s,0,0,s,(this.canvas.width-o*s)/2,(this.canvas.height-i*s)/2);const r=900,c=t%r/r,l=4*c*(1-c);this.platform({x:(o-W)/2,y:i-F-2,type:1,vx:0,flag:0,state:0});const u=$o;u.px=(o-qe)/2,u.py=i-F-2-Nt-l*62,u.vy=c<.12?-8:0,u.facing=Math.floor(t/(r*3))%2===0?1:-1,this.doodler(u,t,0)}grid(t){const n=this.ctx;n.strokeStyle=Co,n.lineWidth=1;const o=22,i=t.score*1.5%o;n.beginPath();for(let s=0;s<=x;s+=o)n.moveTo(s+.5,0),n.lineTo(s+.5,k);for(let s=i-o;s<=k;s+=o)n.moveTo(0,s+.5),n.lineTo(x,s+.5);n.stroke()}platform(t){if(t.type===3&&t.flag===1||t.type===4&&t.state===1)return;const n=this.ctx,[o,i]=ze[t.type];j(n,t.x,t.y,W,F,8),n.fillStyle=o,n.fill(),n.lineWidth=2,n.strokeStyle=i,n.stroke(),n.strokeStyle="rgba(255,255,255,0.55)",n.beginPath(),n.moveTo(t.x+8,t.y+4),n.lineTo(t.x+W-8,t.y+4),n.stroke(),t.type===3&&(n.strokeStyle=i,n.beginPath(),n.moveTo(t.x+30,t.y+2),n.lineTo(t.x+37,t.y+9),n.lineTo(t.x+33,t.y+F-2),n.stroke())}debris(t,n,o){const i=this.ctx,[s,r]=ze[3],c=Math.min(.6,o%60*.03);for(const l of[-1,1])i.save(),i.translate(t+W/2+l*18,n+F/2),i.rotate(l*c),j(i,-W/4,-F/2,W/2-2,F,6),i.fillStyle=s,i.fill(),i.lineWidth=2,i.strokeStyle=r,i.stroke(),i.restore()}spring(t,n,o){const i=this.ctx,s=o?V:V*.5,r=n+V-s;i.strokeStyle="#6b6f76",i.lineWidth=2.5,i.beginPath();const c=4;for(let l=0;l<=c*2;l++){const u=n+V-(s-4)*(l/(c*2)),h=t+(l%2===0?4:Mt-4);l===0?i.moveTo(h,u):i.lineTo(h,u)}i.stroke(),j(i,t,r-2,Mt,5,2),i.fillStyle="#9aa0a8",i.fill()}doodler(t,n,o){const i=Gn(t)?.88:1,s=n%3200<120;on(this.ctx,t.px+o+qe/2,t.py+Nt,t.facing,i,s)}}function on(e,t,n,o,i=1,s=!1){e.save(),e.translate(t,n),e.scale(o,i);const r=36,c=34,l=-r/2-4,u=-c-6;e.strokeStyle=ke,e.lineWidth=2.5,e.lineCap="round";for(let g=0;g<4;g++){const y=l+6+g*8;e.beginPath(),e.moveTo(y,u+c-2),e.lineTo(y,0),e.lineTo(y+3,0),e.stroke()}j(e,l,u,r,c,14),e.fillStyle="#c9de3f",e.fill(),e.lineWidth=2.5,e.stroke(),e.save(),j(e,l,u,r,c,14),e.clip(),e.fillStyle="#5f8f2a",e.fillRect(l,u+c-10,r,10),e.strokeStyle="#3d5f18",e.lineWidth=2;for(let g=0;g<6;g++)e.beginPath(),e.moveTo(l+g*7,u+c-10),e.lineTo(l+g*7,u+c),e.stroke();e.restore(),j(e,l,u,r,c,14),e.strokeStyle=ke,e.lineWidth=2.5,e.stroke();const h=u+11;e.beginPath(),e.moveTo(l+r-4,h-5),e.lineTo(l+r+14,h-3),e.lineTo(l+r+14,h+5),e.lineTo(l+r-4,h+7),e.closePath(),e.fillStyle="#c9de3f",e.fill(),e.stroke(),e.beginPath(),e.ellipse(l+r+14,h+1,2.5,4.5,0,0,Math.PI*2),e.fillStyle="#c9de3f",e.fill(),e.stroke(),e.fillStyle=ke;for(const g of[l+r-12,l+r-22])e.beginPath(),s?e.fillRect(g-2.5,u+8,5,1.5):e.arc(g,u+9,2.4,0,Math.PI*2),e.fill();e.restore()}const $o=ne(Ee(1));function _o(e,t,n,o){const i=ne(e),s=(r,c)=>r+(c-r)*n;if(t&&!t.dead&&!e.dead){const r=x+qe;let c=t.px-e.px;c-=Math.round(c/r)*r,i.px=e.px+c*n,i.py=s(e.py,t.py),i.baseY=s(e.baseY,t.baseY),i.springY=s(e.springY,t.springY),e.debrisOn&&t.debrisOn&&(i.debrisY=s(e.debrisY,t.debrisY));for(let l=0;l<i.plats.length;l++){const u=e.plats[l],h=t.plats[l];h&&Math.abs(h.y-u.y)<k/2&&h.type===u.type&&(i.plats[l].y=s(u.y,h.y),i.plats[l].x=s(u.x,h.x))}}if(i.px+=o.x,i.py+=o.y,o.scroll){i.baseY+=o.scroll,i.springY+=o.scroll,i.debrisY+=o.scroll;for(const r of i.plats)r.y+=o.scroll}return i}function j(e,t,n,o,i,s){const r=Math.min(s,o/2,i/2);e.beginPath(),e.moveTo(t+r,n),e.arcTo(t+o,n,t+o,n+i,r),e.arcTo(t+o,n+i,t,n+i,r),e.arcTo(t,n+i,t,n,r),e.arcTo(t,n,t+o,n,r),e.closePath()}function At(e,t,n,o,i,s){const[r,c]=ze[s];e.save(),j(e,t,n,o,i,i/2),e.fillStyle=r,e.fill(),e.lineWidth=Math.max(2,i/7),e.strokeStyle=c,e.stroke(),e.strokeStyle="rgba(255,255,255,0.55)",e.lineCap="round",e.beginPath(),e.moveTo(t+i/2,n+i*.28),e.lineTo(t+o-i/2,n+i*.28),e.stroke(),e.restore()}const Io="napplet:composer/open";function sn(){var t;const e=globalThis.napplet;return typeof((t=e==null?void 0:e.intent)==null?void 0:t.open)=="function"}const rn=sn;async function Oo(e){if(!sn())return"This shell cannot open a note composer.";try{const t=await In("composer",{content:e},{convention:Io});return t.ok?null:t.error==="no handler"?"No note composer installed. Get Composer in Myco to share.":t.error==="user cancelled"?null:`Couldn't open the composer: ${t.error??"unknown error"}`}catch(t){return t instanceof Error?`Couldn't open the composer: ${t.message}`:"Couldn't open the composer."}}const Yo=9e4;function it(){var t;const e=globalThis.napplet;return typeof((t=e==null?void 0:e.upload)==null?void 0:t.upload)=="function"}function Do(e){return e.status!=="pending"&&e.status!=="uploading"?Promise.resolve(e):new Promise(t=>{let n=null;const o=s=>{clearTimeout(i),n==null||n.close(),t(s)},i=setTimeout(()=>o({...e,ok:!1,status:"failed",error:"timed out"}),Yo);try{n=Bt.onStatus(s=>{s.uploadId===e.uploadId&&s.status!=="pending"&&s.status!=="uploading"&&o(s)})}catch{o({...e,ok:!1,status:"failed",error:"no status from the shell"})}})}const Fo="blossom-local";async function Go(e,t){if(!it())return{error:"This shell can't upload images."};const n=async o=>Do(await Bt.upload({data:e,mimeType:"image/png",filename:`doodleduo-${t}.png`,caption:`Doodle Duo: we scored ${t}`,...o?{rail:o}:{}}));try{const o=await n();if(o.status==="cancelled")return{error:"",cancelled:!0};if(o.ok&&o.status==="complete"&&o.url)return{url:o.url,local:!1};const i=await n(Fo).catch(()=>null);return i!=null&&i.ok&&i.status==="complete"&&i.url?{url:i.url,local:!0}:{error:`Couldn't upload the image: ${o.error??"no URL came back"}`}}catch(o){return{error:o instanceof Error?`Couldn't upload the image: ${o.message}`:"Couldn't upload the image."}}}const m=1080,P=1620,oe="#fbf7ea",T="#2b2a28",Et="rgba(120, 150, 190, 0.22)",Ho="#c9de3f",jo="rgba(134, 196, 64, 0.26)",Wo="rgba(90, 176, 230, 0.26)",Bo="#4e8a1f",Ko="#2c6e9c",Xo='ui-rounded, "SF Pro Rounded", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif',D=280,xe=7,Z=920,b={x:540,y:Z-29*xe,r:84},se=b.x-b.r+8-30.5*xe,K=1536,ve=m-se,Uo=-.17,Jo=e=>b.x+Uo*(e-b.y);function qo(){const e=[],t=P-D;for(let n=0;n<=120;n++){const o=D+t*n/120,i=Math.sin((o-D)/34)*14;e.push([Jo(o)+i,o])}return e}function C(e,t){return`${e} ${t}px ${Xo}`}function De(e,t,n,o,i,s){e.beginPath(),e.moveTo(t+s,n),e.arcTo(t+o,n,t+o,n+i,s),e.arcTo(t+o,n+i,t,n+i,s),e.arcTo(t,n+i,t,n,s),e.arcTo(t,n,t+o,n,s),e.closePath()}function zo(e,t,n){if(e.measureText(t).width<=n)return t;const o=[...t];for(;o.length>1&&e.measureText(o.join("")+"…").width>n;)o.pop();return o.join("").trimEnd()+"…"}function Fe(e,t,n,o,i){e.beginPath();for(let s=0;s<8;s++){const r=Math.PI/4*s-Math.PI/2,c=s%2===0?o:o*.32,l=t+Math.cos(r)*c,u=n+Math.sin(r)*c;s===0?e.moveTo(l,u):e.lineTo(l,u)}e.closePath(),e.fillStyle=i,e.fill(),e.lineWidth=4,e.strokeStyle=T,e.stroke()}function an(e,t,n,o,i,s){e.lineJoin="round",e.fillStyle=T,e.fillText(t,n+s*.9,o+s*.9),e.lineWidth=s,e.strokeStyle=T,e.strokeText(t,n,o),e.fillStyle=i,e.fillText(t,n,o)}function Vo(e){e.save(),e.fillStyle=oe,e.fillRect(0,0,m,P);const t=qo();e.beginPath(),e.moveTo(0,D);for(const[s,r]of t)e.lineTo(s,r);e.lineTo(0,P),e.closePath(),e.fillStyle=jo,e.fill(),e.beginPath(),e.moveTo(m,D);for(const[s,r]of t)e.lineTo(s,r);e.lineTo(m,P),e.closePath(),e.fillStyle=Wo,e.fill();for(const[s,r,c]of[[se,"rgba(134, 196, 64, 0.22)",-1],[ve,"rgba(90, 176, 230, 0.22)",1]]){if(e.save(),e.beginPath(),c<0){e.moveTo(0,D);for(const[u,h]of t)e.lineTo(u,h);e.lineTo(0,P)}else{e.moveTo(m,D);for(const[u,h]of t)e.lineTo(u,h);e.lineTo(m,P)}e.closePath(),e.clip(),e.fillStyle=r;const l=Z-130;for(let u=0;u<18;u++){const h=Math.PI*2*u/18,g=h+Math.PI/18;e.beginPath(),e.moveTo(s,l),e.lineTo(s+Math.cos(h)*900,l+Math.sin(h)*900),e.lineTo(s+Math.cos(g)*900,l+Math.sin(g)*900),e.closePath(),e.fill()}e.restore()}e.strokeStyle=Et,e.lineWidth=2,e.beginPath();const n=44;for(let s=n/2;s<=m;s+=n)e.moveTo(s,0),e.lineTo(s,P);for(let s=n/2;s<=P;s+=n)e.moveTo(0,s),e.lineTo(m,s);e.stroke(),e.lineCap="round",e.lineJoin="round";for(const[s,r]of[[30,oe],[9,T]])e.beginPath(),t.forEach(([c,l],u)=>u===0?e.moveTo(c,l):e.lineTo(c,l)),e.lineWidth=s,e.strokeStyle=r,e.stroke();const o=330,i=46;At(e,se-190,Z,o,i,1),At(e,ve-o+190,Z,o,i,2);for(const[s,r]of[[se,1],[ve,-1]])e.save(),e.translate(s,Z),e.scale(xe,xe),on(e,0,0,r),e.restore();e.save(),e.translate(b.x,b.y),e.rotate(-.08),e.fillStyle=T,e.beginPath(),e.arc(8,8,b.r,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(0,0,b.r,0,Math.PI*2),e.fillStyle="#ffd84a",e.fill(),e.lineWidth=9,e.strokeStyle=T,e.stroke(),e.font=C(900,120),e.textAlign="center",e.textBaseline="middle",e.fillStyle=T,e.fillText("&",0,8),e.restore(),Fe(e,b.x-128,b.y-150,30,"#ffd84a"),Fe(e,b.x+132,b.y-128,22,"#ffffff"),Fe(e,b.x-40,b.y-236,18,"#ffd84a"),e.strokeStyle=T,e.lineWidth=7,e.lineCap="round";for(const[s,r,c]of[[-2.2,108,142],[-1.75,112,152],[-1.25,108,140]])e.beginPath(),e.moveTo(b.x+Math.cos(s)*r,b.y+Math.sin(s)*r),e.lineTo(b.x+Math.cos(s)*c,b.y+Math.sin(s)*c),e.stroke();e.textAlign="center",e.textBaseline="alphabetic",e.save(),e.translate(m/2,176),e.rotate(-.03),e.font=C(900,156),an(e,"Doodle Duo",0,0,Ho,12),e.restore(),e.font=C(700,40),e.fillStyle="rgba(43, 42, 40, 0.72)",e.fillText("two phones · one doodler · one team",m/2,252),e.fillStyle=oe,e.fillRect(0,K,m,P-K),e.strokeStyle=Et,e.lineWidth=2,e.beginPath();for(let s=n/2;s<=m;s+=n)e.moveTo(s,K),e.lineTo(s,P);for(let s=n/2;s<=P;s+=n)s<K||(e.moveTo(0,s),e.lineTo(m,s));e.stroke(),e.fillStyle=T,e.fillRect(0,K,m,6),e.fillRect(0,D-6,m,6),e.restore()}function Qo(e,t){e.save(),e.textAlign="center",e.textBaseline="alphabetic";const n=1052;for(const[c,l,u,h]of[[se-10,t.left,"◀ LEFT",Bo],[ve+10,t.right,"RIGHT ▶",Ko]]){e.font=C(800,62);const g=zo(e,l,380);e.lineJoin="round",e.lineWidth=12,e.strokeStyle=oe,e.strokeText(g,c,n),e.fillStyle=T,e.fillText(g,c,n),e.font=C(800,36);const y=e.measureText(u).width+48;De(e,c-y/2,n+22,y,58,29),e.fillStyle=h,e.fill(),e.lineWidth=4,e.strokeStyle=T,e.stroke(),e.fillStyle="#ffffff",e.fillText(u,c,n+64)}const o=680,i=300;e.save(),e.translate(m/2,1320),e.rotate(-.025),De(e,-o/2+12,-i/2+12,o,i,36),e.fillStyle=T,e.fill(),De(e,-o/2,-i/2,o,i,36),e.fillStyle=oe,e.fill(),e.lineWidth=8,e.strokeStyle=T,e.stroke(),e.font=C(800,46),e.fillStyle="rgba(43, 42, 40, 0.75)",e.fillText("WE  SCORED",0,-i/2+74);let s=200;const r=String(t.score);for(e.font=C(900,s);e.measureText(r).width>o-80&&s>60;)s-=8,e.font=C(900,s);an(e,r,0,38+s*.36,"#ffd84a",12),e.restore(),e.font=C(800,40),e.fillStyle=T,e.fillText("Beat us! Play Doodle Duo on Myco",m/2,K+54),e.restore()}function Zo(e,t){e.setTransform(1,0,0,1,0,0),Vo(e),Qo(e,t)}function es(e,t,n){return e==="L"?{left:t,right:n}:{left:n,right:t}}function ts(e,t){e.width=m,e.height=P;const n=e.getContext("2d");n&&Zo(n,t)}function ns(e){return new Promise(t=>{try{e.toBlob(n=>t(n),"image/png")}catch{t(null)}})}const os=3e4,ss=1300,is=3e4,Rt=15e3,rs=1200,as=250,ls=110,cs=500,ds=12e3,p=e=>document.getElementById(e),d={app:p("app"),guard:p("guard"),lobby:p("lobby"),waiting:p("waiting"),play:p("play"),create:p("create"),picker:p("picker"),places:p("places"),pickerCancel:p("pickerCancel"),mascot:p("mascot"),games:p("games"),noGames:p("noGames"),board:p("board"),noScores:p("noScores"),spinner:p("spinner"),pickSide:p("pickSide"),pickL:p("pickL"),pickR:p("pickR"),lobbyStatus:p("lobbyStatus"),waitingText:p("waitingText"),waitingSub:p("waitingSub"),cancel:p("cancel"),canvas:p("canvas"),pad:p("pad"),padArrow:p("padArrow"),youBadge:p("youBadge"),partnerBadge:p("partnerBadge"),banner:p("banner"),overlay:p("overlay"),overlayTitle:p("overlayTitle"),overlayText:p("overlayText"),again:p("again"),offer:p("offer"),postYes:p("postYes"),postNo:p("postNo"),shareCard:p("shareCard"),publish:p("publish"),shareNote:p("shareNote"),leave:p("leave")},ln=e=>e==="L"?"R":"L",us=e=>e==="L"?"◀ Left":"Right ▶",Ct=e=>e==="L"?"◀":"▶";let a={kind:"lobby"},Le="",$=!1,E=null,R=null,I=null,N=null;const Ne=new fo;let L=[];const v={pk:"",name:""},cn=new Set;function rt(e){d.lobby.classList.toggle("hidden",e!=="lobby"),d.waiting.classList.toggle("hidden",e!=="waiting"),d.play.classList.toggle("hidden",e!=="play"),e!=="lobby"&&d.picker.classList.add("hidden")}function fe(e=""){a={kind:"lobby"},Le=e,$=!1,rt("lobby"),R==null||R.resize(),Me(),gn(),yn()}function $t(e,t){return O(e)||Y(t)}function _(e,t,n=!1){d.waitingText.textContent=e,d.waitingSub.textContent=t,d.pickSide.classList.toggle("hidden",!n),d.spinner.classList.toggle("hidden",n),rt("waiting")}const we=e=>e.kind==="online"?"online":`in ${e.label}`;function fs(){if(L.length===0){d.lobbyStatus.textContent="Nowhere to list a game: no neighborhoods and no relays.";return}if(L.length===1){_t(L[0]);return}d.places.replaceChildren(...L.map(e=>{const t=document.createElement("button");return t.type="button",t.className="sketch-btn",t.textContent=e.kind==="online"?"🌍 Online":e.nearby?"📡 Nearby":`🏠 ${e.label}`,t.addEventListener("click",()=>{d.picker.classList.add("hidden"),_t(e)}),t})),d.picker.classList.remove("hidden")}async function _t(e){if(a.kind!=="lobby")return;const t=z(),n=z()+z()+z()+z();cn.add(t);const o=new Ce({onRequest:r=>a.kind!=="hosting"||a.link!==o||a.guest?!1:(a.guest={pubkey:r,nonce:null,name:Y(r),lastHeard:performance.now()},_("Someone is joining…",`Connecting ${we(e)}.`),!0),onJoined:r=>{o.admits||a.kind==="lobby"||a.link!==o||a.kind==="hosting"&&!a.guest&&(a.guest={pubkey:r,nonce:null,name:Y(r),lastHeard:performance.now()},_("Someone is joining…",`Connecting ${we(e)}.`))},onLeft:r=>hn(o,r),onMessage:(r,c)=>fn(o,r,c),onTrouble:r=>pn(o,r)}),i={kind:"hosting",g:t,room:n,place:e,nonce:st(),link:o,lastAdvert:0,guest:null};a=i,_("Setting up…","");const s=await o.open({place:e,room:n,admit:!0});if(a!==i)return o.close();if(s)return o.close(),fe(s);_("Waiting for someone to join…",`Your game is listed ${we(e)}. You pick a side once someone joins.`),await J(i,"open")}function It(){return`${v.name||Y(v.pk)}'s game`}async function J(e,t){if(e.nextAdvert=t,!e.advertising){e.advertising=!0;try{for(;e.nextAdvert;){const n=e.nextAdvert;e.nextAdvert=null;let o=await wt(e.place,Te({game:e.g,room:e.room,status:n,title:It(),keyed:e.link.v149}));for(let i=0;o&&/retry|incomplete|busy/i.test(o)&&i<3&&a===e&&(await new Promise(s=>setTimeout(s,4e3)),!e.nextAdvert);i++)o=await wt(e.place,Te({game:e.g,room:e.room,status:n,title:It(),keyed:e.link.v149}));o&&a===e&&!e.guest&&_("Waiting for someone to join…",o)}}finally{e.advertising=!1,e.lastAdvert=performance.now()}}}function Ot(e){if(a.kind!=="hosting"||!a.guest||a.guest.nonce===null)return;const t=a,n=t.guest;t.link.send({t:"start",g:t.g,hostNonce:t.nonce,guestNonce:n.nonce,hostRole:e}),J(t,"full"),dn({g:t.g,place:t.place,link:t.link,role:e,isHost:!0,partnerName:n.name,partnerPubkey:n.pubkey,hostNonce:t.nonce,guestNonce:n.nonce})}async function hs(e){if(a.kind!=="lobby")return;const t=new Ce({onJoined:s=>{a.kind==="joining"&&a.link===t&&!t.hostNamed&&!a.connected&&(a.hostPubkey=s),a.kind==="joining"&&a.link===t&&s===a.hostPubkey&&(a.connected=!0,a.lastJoin=0)},onLeft:s=>hn(t,s),onMessage:(s,r)=>fn(t,s,r),onTrouble:s=>pn(t,s)}),n={kind:"joining",g:e.game,place:e.place,link:t,nonce:st(),hostName:e.title.replace(/'s game$/,""),hostPubkey:e.host,started:performance.now(),connected:!1,lastJoin:0,acceptedAt:0};a=n,_(`Joining ${e.title}…`,`Connecting ${we(e.place)}.`);const o=!!v.pk&&e.host===v.pk,i=await t.open({place:e.place,room:e.room,host:e.keyed?e.host:void 0,admit:!1,ephemeral:o});if(a!==n)return t.close();i&&(t.close(),fe(i))}function Yt(){if((a.kind==="playing"||a.kind==="joining"||a.kind==="hosting"&&a.guest)&&a.link.send({t:"bye",g:a.g}),a.kind==="hosting"&&J(a,"closed"),a.kind!=="lobby"){const e=a.link;window.setTimeout(()=>e.close(),300)}fe()}function dn(e){const t=e.isHost?e.hostNonce:e.guestNonce,n=e.isHost?e.guestNonce:e.hostNonce;a={kind:"playing",g:e.g,place:e.place,link:e.link,role:e.role,isHost:e.isHost,partnerName:e.partnerName,partnerPubkey:e.partnerPubkey,round:0,mine:new Map([[0,t]]),theirs:new Map([[0,n]]),session:new Ut(nn(e.hostNonce,e.guestNonce,0),e.role),ready:!1,lastAgain:0,lastSend:0,sendPending:!1,lastHeard:performance.now(),partnerGone:null,overShown:!1,hostNonce:e.hostNonce,guestNonce:e.guestNonce,published:!1,offer:"none"},d.youBadge.textContent=`You: ${us(e.role)}`,d.padArrow.textContent=e.role==="L"?"◀":"▶",d.pad.classList.toggle("left",e.role==="L"),d.pad.classList.toggle("right",e.role==="R"),$=!1,rt("play"),E==null||E.resize(),M()}function Ve(e){const t=e.round+1,n=e.mine.get(t),o=e.theirs.get(t);n===void 0||o===void 0||!e.session.over||(e.round=t,e.session=new Ut(nn(n,o,t),e.role),e.ready=!1,e.lastSend=0,e.overShown=!1,e.published=!1,e.offer="none",d.shareNote.classList.add("hidden"),M())}let ie="",ee="",Qe=!1;const ps=()=>rn()&&it();function un(e){const t=e.session.confirmedState.score,n=`${e.g}:${e.round}:${t}`;if(n===ie)return;ie=n,ee="",Qe=!1;const o=v.name||Y(v.pk);ts(d.shareCard,{score:t,...es(e.role,o,e.partnerName)})}async function gs(){if(a.kind!=="playing"||!a.session.over)return;const e=a,t=e.session.confirmedState.score,n=v.pk;let o=bo(t,qt(e.role,{pk:n,name:v.name||Y(n)},{pk:e.partnerPubkey,name:e.partnerName})),i="";if(d.postYes.disabled=!0,d.postNo.disabled=!0,d.shareNote.classList.add("hidden"),it()){un(e);const r=ie;if(!ee){d.postYes.textContent="Uploading…";const c=await ns(d.shareCard),l=c?await Go(c,t):{error:"Couldn't draw the score image."};if("url"in l)r===ie&&(ee=l.url,Qe=l.local);else if(l.cancelled){d.postYes.textContent="Yes, post it",d.postYes.disabled=!1,d.postNo.disabled=!1;return}else i=`${l.error} Posting without the image.`}ee&&r===ie&&(o=ko(o,ee,Qe))}d.postYes.textContent="Opening…";const s=await Oo(o);d.postYes.textContent="Yes, post it",d.postYes.disabled=!1,d.postNo.disabled=!1,s||(e.offer="done"),d.shareNote.textContent=s??i,d.shareNote.classList.toggle("hidden",!(s??i)),M()}async function ys(){if(a.kind!=="playing"||!a.session.over||a.published)return;const e=a;v.pk||await mn();const t=v.pk;if(!t){d.shareNote.textContent="Couldn't tell who you are, so the score can't be signed for you.",d.shareNote.classList.remove("hidden");return}const n=to({seed:e.session.seed,log:e.session.inputLog(),score:e.session.confirmedState.score,players:qt(e.role,{pk:t,name:v.name||Y(t)},{pk:e.partnerPubkey,name:e.partnerName}),partnerPk:e.partnerPubkey});d.publish.disabled=!0;const o=await no(e.place,n);if(d.publish.disabled=!1,o){d.shareNote.textContent=o,d.shareNote.classList.remove("hidden");return}e.published=!0,e.offer=rn()?"asking":"done",M()}function ms(){a.kind!=="playing"||!a.session.over||(a.mine.has(a.round+1)||a.mine.set(a.round+1,st()),a.ready=!0,a.lastAgain=0,M())}function fn(e,t,n){var i;if(a.kind==="lobby"||a.link!==e||t.g!==a.g)return;const o=performance.now();switch(a.kind){case"hosting":{const s=a;if(!s.guest||n!==s.guest.pubkey){Dt(e,t,n,(i=s.guest)==null?void 0:i.pubkey);return}s.guest.lastHeard=o,t.t==="join"?(s.guest.nonce===null&&(s.guest.nonce=t.nonce,s.guest.name=$t(t.name,n),_(`${s.guest.name} joined!`,"Pick your side. They get the other one.",!0)),s.link.send({t:"accept",g:s.g,name:v.name||void 0})):t.t==="bye"&&$e(s,"They left. Your game is open again.");return}case"joining":{const s=a;if(n!==s.hostPubkey)return;t.t==="accept"?(s.acceptedAt||(s.hostName=$t(t.name,n),_(`${s.hostName} is picking sides…`,"You'll get the other one.")),s.acceptedAt=o):t.t==="start"&&t.guestNonce===s.nonce?dn({g:s.g,place:s.place,link:s.link,role:ln(t.hostRole),isHost:!1,partnerName:s.hostName,partnerPubkey:s.hostPubkey,hostNonce:t.hostNonce,guestNonce:s.nonce}):t.t==="bye"?ce(s.link,`${s.hostName} cancelled the game.`):t.t==="full"&&t.n===s.nonce&&ce(s.link,"Someone else joined first.");return}case"playing":n===a.partnerPubkey?bs(a,t,o):Dt(e,t,n,a.partnerPubkey);return}}function bs(e,t,n){switch(e.lastHeard=n,t.t){case"join":e.isHost&&e.link.send({t:"start",g:e.g,hostNonce:e.hostNonce,guestNonce:e.guestNonce,hostRole:e.role});return;case"in":t.r===e.round?e.session.receive(t,n):t.r===e.round+1&&(e.theirs.has(t.r)||e.theirs.set(t.r,t.n),Ve(e),t.r===e.round&&e.session.receive(t,n)),e.partnerGone&&(e.partnerGone=null,M());return;case"again":t.r===e.round&&!e.theirs.has(e.round+1)&&(e.theirs.set(e.round+1,t.nonce),M(),Ve(e));return;case"bye":e.partnerGone=`${e.partnerName} left the game.`,M();return;default:return}}function $e(e,t){e.guest=null,_("Waiting for someone to join…",t),J(e,"open")}function Dt(e,t,n,o){e.admits||t.t!=="join"||!o||n===o||e.send({t:"full",g:t.g,n:t.nonce})}function hn(e,t){var n;a.kind==="lobby"||a.link!==e||(a.kind==="hosting"&&((n=a.guest)==null?void 0:n.pubkey)===t?$e(a,"They went away. Your game is open again."):a.kind==="joining"&&t===a.hostPubkey?ce(e,`Lost the connection to ${a.hostName}.`):a.kind==="playing"&&t===a.partnerPubkey&&!a.partnerGone&&(a.partnerGone=`Lost the connection to ${a.partnerName}.`,M()))}function pn(e,t){a.kind==="lobby"||a.link!==e||(a.kind==="joining"?ce(e,t):a.kind==="hosting"&&a.guest?$e(a,t):a.kind==="playing"&&!a.partnerGone&&(a.partnerGone=t,M()))}function ce(e,t){e.close(),fe(t)}function Ft(e,t){switch(a.kind){case"lobby":return;case"hosting":{const n=a;n.guest&&n.guest.nonce!==null&&e-n.guest.lastHeard>Rt&&$e(n,"They went quiet. Your game is open again.");const o=Je()>90?Je()*800:os;!n.guest&&!n.advertising&&n.lastAdvert&&e-n.lastAdvert>=o&&J(n,"open");return}case"joining":{const n=a;if(n.acceptedAt?e-n.acceptedAt>Rt:e-n.started>is){ce(n.link,`No answer from ${n.hostName}.`);return}n.connected&&e-n.lastJoin>=ss&&(n.lastJoin=e,n.link.send({t:"join",g:n.g,nonce:n.nonce,name:v.name||void 0}));return}case"playing":{const n=a;n.session.tuneDelay();const o=n.session.advance(t,$&&!n.session.over),i=n.session.over?cs:as;(o||e-n.lastSend>=i)&&(n.sendPending=!0),n.sendPending&&n.link.canSendGame&&(n.sendPending=!1,n.lastSend=e,n.link.send({t:"in",g:n.g,r:n.round,n:n.mine.get(n.round),...n.session.outgoing(performance.now())})),n.ready&&e-n.lastAgain>=rs&&(n.lastAgain=e,n.link.send({t:"again",g:n.g,r:n.round,nonce:n.mine.get(n.round+1)})),n.session.over!==n.overShown&&(n.overShown=n.session.over,M()),!n.partnerGone&&e-n.lastHeard>ds&&(n.partnerGone=`Nothing heard from ${n.partnerName} for a while.`,M()),Ve(n);return}}}let ye=0,Gt=0,Ge=0;const S={x:0,y:0,scroll:0};function ks(e){const t=Ge?e-Ge:0;if(Ge=e,a.kind==="lobby"&&(R==null||R.drawMascot(e)),a.kind==="playing"&&E){const n=a,o=n.session.over,i=o?n.session.confirmedState:n.session.predicted(),s=Math.exp(-t/ls);o?S.x=S.y=S.scroll=0:(S.x=(S.x+n.session.correctionX)*s,S.y=(S.y+n.session.correctionY)*s,S.scroll=(S.scroll+n.session.correctionScroll)*s,Math.abs(S.x)<.3&&(S.x=0),Math.abs(S.y)<.3&&(S.y=0),Math.abs(S.scroll)<.3&&(S.scroll=0));const r=o?null:n.session.nextOf(i);E.draw(_o(i,r,o?0:n.session.alpha,S),e),d.pad.classList.toggle("held",$&&!n.session.over);const c=n.session.partnerHeld&&!n.session.over,l=n.session.rttMs?` ${Math.round(n.session.rttMs)} ms`:"";d.partnerBadge.textContent=`${n.partnerName}: ${Ct(ln(n.role))}${l}`;const u=n.link.sendMs?` ${Math.round(n.link.sendMs)}/${Math.round(n.link.recvMs)} ms`:"";d.youBadge.textContent=`You: ${Ct(n.role)}${u}`,e-Gt>5e3&&n.session.rttMs&&(Gt=e,console.info(`[doodleduo] rtt ${Math.round(n.session.rttMs)}ms send ${Math.round(n.link.sendMs)}ms recv ${Math.round(n.link.recvMs)}ms`)),d.partnerBadge.classList.toggle("lit",c);let h="";n.session.stalled?(ye||(ye=e),e-ye>400&&(h=`Waiting for ${n.partnerName}…`)):ye=0,n.session.desynced&&(h="Out of sync — finish this round and play again."),d.banner.textContent=h,d.banner.classList.toggle("hidden",h==="")}}function M(){if(a.kind!=="playing")return;const e=a;if(e.partnerGone){d.overlayTitle.textContent="Partner gone",d.overlayText.textContent=e.partnerGone,d.again.classList.add("hidden"),d.offer.classList.add("hidden"),d.publish.classList.add("hidden"),d.shareNote.classList.add("hidden"),d.overlay.classList.remove("hidden");return}if(!e.session.over){d.overlay.classList.add("hidden");return}const t=e.session.confirmedState.score,n=e.theirs.has(e.round+1);d.overlayTitle.textContent="Game over!",d.overlayText.textContent=`You two scored ${t}. `+(e.ready?n?"Starting…":`Waiting for ${e.partnerName}…`:n?`${e.partnerName} wants another go.`:""),d.again.classList.remove("hidden"),d.again.disabled=e.ready,d.again.textContent=e.ready?"Ready ✓":"Play again";const o=e.offer==="asking";d.offer.classList.toggle("hidden",!o);const i=o&&ps();i&&un(e),d.shareCard.classList.toggle("hidden",!i),d.publish.classList.toggle("hidden",t===0),d.publish.disabled=e.published,d.publish.textContent=e.published?"🏆 Published ✓":"🏆 Publish score",d.overlay.classList.remove("hidden")}function gn(){const e=I?I.top():[];d.board.replaceChildren();for(const t of e){const n=document.createElement("li"),o=v.pk!==""&&(t.L.pk===v.pk||t.R.pk===v.pk);n.className=o?"entry mine":"entry";const i=document.createElement("span");i.className="score",i.textContent=String(t.score);const s=document.createElement("span");if(s.className="pair",s.textContent=`${t.L.name||Y(t.L.pk)} ◀ ▶ ${t.R.name||Y(t.R.pk)}`,n.append(i,s),t.signers.has(t.L.pk)&&t.signers.has(t.R.pk)){const r=document.createElement("span");r.className="both",r.title="Published by both players",r.textContent="✓✓",n.append(r)}d.board.append(n)}d.noScores.classList.toggle("hidden",e.length>0)}const vs=["follows","friend of a friend",""];function ws(e){const t=Math.max(0,Math.floor(Date.now()/1e3)-e);return t<60?`${t} s ago`:t<3600?`${Math.floor(t/60)} m ago`:`${Math.floor(t/3600)} h ago`}function Me(){d.games.replaceChildren();const e=N?N.list(Ne,cn):[];for(const t of e){const n=document.createElement("li");n.className="game";const o=document.createElement("span");o.className="who",o.textContent=t.title;const i=document.createElement("span");i.className="where";const s=vs[t.tier];i.textContent=[t.place.kind==="online"?"Online":t.place.label,s,ws(t.createdAt)].filter(Boolean).join(" · ");const r=document.createElement("button");r.type="button",r.className="sketch-btn",r.textContent="Join",r.addEventListener("click",()=>void hs(t)),n.append(o,i,r),d.games.append(n)}d.noGames.classList.toggle("hidden",e.length>0),Le&&(d.lobbyStatus.textContent=Le)}function yn(){if(!(Le&&a.kind==="lobby"))if(!Ce.available())d.lobbyStatus.textContent=`This shell has no direct connections, so Doodle Duo can't connect two phones. Open it in Myco (${tn}).`;else if(L.length===0)d.lobbyStatus.textContent="No neighborhoods and no relays here, so there is nowhere to find a partner.";else{const e=L.map(n=>n.label),t=e.length>1?`${e.slice(0,-1).join(", ")} and ${e.at(-1)}`:e[0];d.lobbyStatus.textContent=`Looking for games: ${t}.`}}async function He(){const e=await So();e.length===L.length&&e.every((n,o)=>n.key===L[o].key)&&N||(L=e,N==null||N.open(L,Ne),I==null||I.open(L),d.create.disabled=L.length===0||!Ce.available(),a.kind==="lobby"&&(Me(),yn()))}const Q=new Set;function Ss(){const e=o=>{o.target.closest("button")||(Q.add(o.pointerId),$=!0,o.preventDefault())},t=o=>{Q.delete(o.pointerId),$=Q.size>0};d.play.addEventListener("pointerdown",e),window.addEventListener("pointerup",t),window.addEventListener("pointercancel",t),d.play.addEventListener("contextmenu",o=>o.preventDefault());const n=o=>a.kind!=="playing"?!1:o.key===" "?!0:a.role==="L"?o.key==="ArrowLeft"||o.key==="a":o.key==="ArrowRight"||o.key==="d";window.addEventListener("keydown",o=>{n(o)&&(o.preventDefault(),$=!0)}),window.addEventListener("keyup",o=>{n(o)&&($=Q.size>0)}),window.addEventListener("blur",()=>{Q.clear(),$=!1})}let Se=null;function Ht(e){const t=document.documentElement.style;t.setProperty("--bg",e.colors.background),t.setProperty("--text",e.colors.text),t.setProperty("--primary",e.colors.primary)}async function mn(){try{Pe("identity","getPublicKey")&&(v.pk=await Ln())}catch{}try{if(Pe("identity","getProfile")){const e=await Nn();v.name=O(e==null?void 0:e.displayName)||O(e==null?void 0:e.name)}}catch{}}function Pe(e,t){var o;const n=globalThis.napplet;return typeof((o=n==null?void 0:n[e])==null?void 0:o[t])=="function"}function Ts(){try{Pe("theme","get")&&An().then(Ht).catch(()=>{}),Pe("theme","onChanged")&&(Se=En(Ht))}catch{}}function xs(){return window.__NAPPLET_ALLOW_STANDALONE__===!0?!0:!!document.querySelector('meta[name="napplet-allow-standalone"]')}function Ls(){var o,i;if(!xs()&&!globalThis.napplet){d.guard.classList.remove("hidden"),d.app.classList.add("hidden");return}Ts(),Ss(),E=new Pt(d.canvas),window.addEventListener("resize",()=>E==null?void 0:E.resize()),R=new Pt(d.mascot),window.addEventListener("resize",()=>R==null?void 0:R.resize()),d.create.addEventListener("click",fs),d.pickerCancel.addEventListener("click",()=>d.picker.classList.add("hidden")),d.pickL.addEventListener("click",()=>Ot("L")),d.pickR.addEventListener("click",()=>Ot("R")),d.cancel.addEventListener("click",Yt),d.again.addEventListener("click",ms),d.postYes.addEventListener("click",()=>void gs()),d.postNo.addEventListener("click",()=>{a.kind==="playing"&&(a.offer="done",M())}),d.publish.addEventListener("click",()=>void ys()),d.leave.addEventListener("click",Yt);const e=()=>{a.kind==="lobby"&&(Me(),gn())};N=new ho(e),I=new oo(e),mn().then(()=>{e(),Ne.load(()=>{N==null||N.open(L,Ne),e()})}),He(),(i=(o=en())==null?void 0:o.onEvent)==null||i.call(o,s=>{s.type==="neighborhood"&&He()}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&He()}),window.setInterval(()=>{a.kind==="lobby"&&document.visibilityState==="visible"&&Me()},5e3),fe();let t=performance.now();const n=s=>{const r=s-t;t=s,Ft(s,r),ks(s),requestAnimationFrame(n)};requestAnimationFrame(n),window.setInterval(()=>{document.visibilityState==="hidden"&&a.kind!=="lobby"&&Ft(performance.now(),0)},250),E.resize(),E.draw(Ee(1),0)}window.addEventListener("beforeunload",()=>{a.kind!=="lobby"&&(a.link.send({t:"bye",g:a.g}),a.kind==="hosting"&&J(a,"closed"),a.link.close()),N==null||N.close(),I==null||I.close(),Se==null||Se.close()});Ls();</script>
    <style rel="stylesheet" crossorigin>:root{--bg: #fbf7ea;--text: #2b2a28;--primary: #5f8f2a;--muted: color-mix(in srgb, var(--text) 60%, transparent);--card: color-mix(in srgb, var(--bg) 92%, var(--text));--line: color-mix(in srgb, var(--text) 16%, transparent);color-scheme:light dark;font-family:ui-rounded,SF Pro Rounded,system-ui,-apple-system,Segoe UI,sans-serif}*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--text);overscroll-behavior:none}body{-webkit-tap-highlight-color:transparent;user-select:none;-webkit-user-select:none}.hidden{display:none!important}.app{height:100dvh;background:var(--bg);color:var(--text)}.screen{height:100%}button{font:inherit;color:inherit;cursor:pointer;border:none;touch-action:manipulation}button:disabled{opacity:.55;cursor:default}.primary{background:var(--primary);color:#fff;border-radius:999px;padding:.6rem 1.1rem;font-weight:700}.secondary{background:transparent;border:2px solid var(--line);border-radius:999px;padding:.55rem 1.1rem;font-weight:600}.lobby,.waiting{--ink: var(--text);--grid: color-mix(in srgb, var(--text) 9%, transparent);background-color:var(--bg);background-image:linear-gradient(var(--grid) 1px,transparent 1px),linear-gradient(90deg,var(--grid) 1px,transparent 1px);background-size:22px 22px}.lobby{display:flex;flex-direction:column;gap:1.2rem;padding:clamp(1rem,5vw,2rem);overflow-y:auto}.lobby>*{width:100%;max-width:34rem;margin-inline:auto}.hero{display:flex;align-items:center;gap:.6rem}.mascot{width:6.5rem;height:6.5rem;flex:0 0 auto}.hero h1{margin:0;font-size:clamp(2.1rem,10vw,3rem);letter-spacing:-.03em;color:var(--primary);transform:rotate(-2deg);text-shadow:2px 2px 0 color-mix(in srgb,var(--text) 18%,transparent)}.tagline{margin:.2rem 0 0;color:var(--muted)}.sketch-btn{background:var(--primary);color:#fff;font-weight:800;padding:.55rem 1.1rem;border:2.5px solid var(--ink);border-radius:255px 15px 225px/15px 225px 15px 255px;box-shadow:3px 3px 0 var(--ink);transition:transform 60ms,box-shadow 60ms}.sketch-btn:active:not(:disabled){transform:translate(2px,2px);box-shadow:1px 1px 0 var(--ink)}.sketch-btn.big{font-size:1.3rem;padding:1rem 1.2rem}.panel{padding:.9rem 1rem;background:color-mix(in srgb,var(--bg) 88%,transparent);border:2px solid color-mix(in srgb,var(--text) 70%,transparent);border-radius:18px 4px 16px 6px/6px 16px 4px 18px}.label{margin:0 0 .6rem;font-size:.8rem;font-weight:800;text-transform:uppercase;letter-spacing:.08em;color:var(--muted)}.games{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:.5rem}.game{display:flex;align-items:center;justify-content:space-between;gap:.75rem}.who{font-weight:700}.game .where{flex:1;font-size:.85em;color:var(--muted)}.places{display:flex;flex-direction:column;gap:.5rem;margin-bottom:.75rem}.board{margin:0;padding:0;list-style:none;counter-reset:rank;display:flex;flex-direction:column;gap:.35rem}.entry{counter-increment:rank;display:flex;align-items:baseline;gap:.6rem;padding:.3rem .4rem;border-radius:8px}.entry:before{content:counter(rank) ".";width:1.6rem;color:var(--muted);font-weight:700}.entry.mine{background:color-mix(in srgb,var(--primary) 16%,transparent)}.entry .score{min-width:3.5rem;font-weight:900;font-size:1.1rem;color:var(--primary)}.entry .pair{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entry .both{color:var(--primary);font-weight:800}.empty{margin:0;color:var(--muted)}.status{display:block;margin-top:auto;font-size:.9rem;color:var(--muted)}.waiting{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.8rem;padding:2rem;text-align:center}.waiting-text{margin:0;font-size:1.3rem;font-weight:700}.waiting-sub{margin:0 0 1rem;color:var(--muted)}.pick-side{display:grid;grid-template-columns:1fr 1fr;gap:.8rem;width:min(24rem,100%);margin-bottom:1rem}.spinner{width:3rem;height:3rem;border-radius:50%;border:4px solid var(--line);border-top-color:var(--primary);animation:spin .9s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}.play{position:relative;display:flex;flex-direction:column;touch-action:none;background:#fbf7ea}.hud{display:flex;justify-content:space-between;gap:.5rem;padding:.5rem .75rem;background:var(--bg)}.badge{font-size:.85rem;font-weight:700;padding:.25rem .65rem;border-radius:999px;background:var(--card);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.badge.you{background:var(--primary);color:#fff}.badge.partner.lit{background:#f2b631;color:#2b2a28}.canvas{flex:1;width:100%;min-height:0;display:block}.pad{flex:0 0 auto;height:clamp(4.5rem,16vh,7rem);display:flex;align-items:center;font-size:clamp(2.4rem,10vh,4rem);color:color-mix(in srgb,var(--primary) 80%,#000);background:color-mix(in srgb,var(--primary) 18%,#fbf7ea);border-top:3px solid color-mix(in srgb,var(--primary) 40%,transparent);padding:0 1.5rem;transition:background 60ms}.pad.left{justify-content:flex-start}.pad.right{justify-content:flex-end}.pad.held{background:color-mix(in srgb,var(--primary) 55%,#fbf7ea);color:#fff}.banner{position:absolute;top:3rem;left:50%;transform:translate(-50%);padding:.4rem .9rem;border-radius:999px;background:#2b2a28d9;color:#fff;font-size:.9rem;font-weight:600;pointer-events:none;white-space:nowrap}.overlay{position:absolute;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;padding:1.5rem;background:#14141459}.card{width:min(22rem,100%);padding:1.4rem;border-radius:1.2rem;background:var(--bg);color:var(--text);text-align:center;box-shadow:0 10px 30px #00000040}.card h2{margin:0 0 .4rem}.card p{margin:0 0 1.1rem;color:var(--muted);min-height:1.2em}.card-actions{display:flex;justify-content:center;gap:.6rem}.share{margin-top:.9rem;background:transparent;color:var(--primary);font-weight:700;padding:.4rem .8rem;border-radius:999px}.card-extras{display:flex;flex-wrap:wrap;justify-content:center;gap:.2rem;margin-top:.6rem}.card-extras .share{margin-top:0}.share-card{display:block;height:min(9.5rem,22vh);aspect-ratio:2 / 3;margin:.2rem auto .4rem;border-radius:.5rem;border:2px solid var(--text);box-shadow:3px 3px color-mix(in srgb,var(--text) 70%,transparent);transform:rotate(-2deg)}.share-note{margin:.4rem 0 0!important;font-size:.85rem}.guard{position:fixed;top:0;right:0;bottom:0;left:0;display:flex;align-items:center;justify-content:center;padding:1.5rem;background:var(--bg)}.guard-card{max-width:26rem;text-align:center}.offer{margin-top:.8rem;padding-top:.8rem;border-top:1px dashed var(--line)}.offer-ask{margin:.4rem 0 .7rem!important;font-weight:700;color:var(--text)!important}</style>
  </head>
  <body>
    <main id="app" class="app">
      <!-- Lobby: create a game, join one nearby, see the best climbs. -->
      <section id="lobby" class="screen lobby">
        <header class="hero">
          <canvas id="mascot" class="mascot" aria-hidden="true"></canvas>
          <div>
            <h1>Doodle Duo</h1>
            <p class="tagline">Two phones. One doodler. One button each.</p>
          </div>
        </header>

        <button id="create" class="sketch-btn big" type="button">✏️ Create a game</button>

        <!-- Where the new game is listed: one of your neighborhoods, or online. -->
        <div id="picker" class="panel picker hidden">
          <h2 class="label">Where should people find it?</h2>
          <div id="places" class="places"></div>
          <button id="pickerCancel" class="secondary" type="button">Cancel</button>
        </div>

        <section class="panel">
          <h2 class="label">Open games</h2>
          <ul id="games" class="games"></ul>
          <p id="noGames" class="empty">Nobody's waiting yet. Create one, or ask a friend to.</p>
        </section>

        <section class="panel">
          <h2 class="label">🏆 Best climbs</h2>
          <ol id="board" class="board"></ol>
          <p id="noScores" class="empty">No scores yet. Publish one after a round.</p>
        </section>

        <output id="lobbyStatus" class="status" aria-live="polite">Connecting…</output>
      </section>

      <!-- Waiting: hosting (then picking a side), or joining. -->
      <section id="waiting" class="screen waiting hidden">
        <div id="spinner" class="spinner" aria-hidden="true"></div>
        <p id="waitingText" class="waiting-text">Waiting…</p>
        <p id="waitingSub" class="waiting-sub"></p>
        <div id="pickSide" class="pick-side hidden">
          <button id="pickL" class="sketch-btn big" type="button">◀ Left</button>
          <button id="pickR" class="sketch-btn big" type="button">Right ▶</button>
        </div>
        <button id="cancel" class="secondary" type="button">Cancel</button>
      </section>

      <!-- Playing: the whole screen is your one button. -->
      <section id="play" class="screen play hidden">
        <div class="hud">
          <span id="youBadge" class="badge you"></span>
          <span id="partnerBadge" class="badge partner"></span>
        </div>
        <canvas id="canvas" class="canvas"></canvas>
        <div id="pad" class="pad" aria-hidden="true"><span id="padArrow"></span></div>

        <div id="banner" class="banner hidden"></div>

        <div id="overlay" class="overlay hidden">
          <div class="card">
            <h2 id="overlayTitle"></h2>
            <p id="overlayText"></p>
            <div class="card-actions">
              <button id="again" class="primary" type="button">Play again</button>
              <button id="leave" class="secondary" type="button">Leave</button>
            </div>
            <div class="card-extras">
              <button id="publish" class="share" type="button">🏆 Publish score</button>
            </div>
            <div id="offer" class="offer hidden">
              <canvas id="shareCard" class="share-card hidden" aria-label="Score image preview"></canvas>
              <p class="offer-ask">Post it as a note too?</p>
              <div class="card-actions">
                <button id="postYes" class="primary" type="button">Yes, post it</button>
                <button id="postNo" class="secondary" type="button">No thanks</button>
              </div>
            </div>
            <p id="shareNote" class="share-note hidden"></p>
          </div>
        </div>
      </section>
    </main>

    <div id="guard" class="guard hidden" role="alert">
      <div class="guard-card">
        <h1>Doodle Duo needs a napplet runtime</h1>
        <p>
          This is a NIP-5D napplet. Open it inside a napplet shell with direct
          connections (NAP-WEBRTC) — it cannot run as a standalone page.
        </p>
      </div>
    </div>

  </body>
</html>