puzzle/build/public/assets/index.93936dee.js

1 line
68 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import{d as e,c as t,a as n,w as l,b as o,r as a,o as s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),M=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:l((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:l((()=>[M])),_:1})])])):o("",!0),n(g)])};const E=864e5,D=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const l=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${l}m ${Math.floor(e/1e3)}s`};var N=1,_=1e3,V=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},O=(e,t)=>D(t-e),B=D,U=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",l=e,o=t||V();return`${n} ${O(l,o)}`}}});const R={class:"game-info-text"},$=n("br",null,null,-1),G=n("br",null,null,-1),L=n("br",null,null,-1),F=i(" ↪️ Watch replay ");U.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:l((()=>[n("span",R,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),$,i(" 👥 "+r(e.game.players),1),G,i(" "+r(e.time(e.game.started,e.game.finished)),1),L])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:l((()=>[F])),_:1},8,["to"])):o("",!0)],4)};var j=e({components:{GameTeaser:U},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await fetch("/api/index-data"),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const W=n("h1",null,"Running games",-1),K=n("h1",null,"Finished games",-1);j.render=function(e,l,o,i,r,u){const p=a("game-teaser");return s(),t("div",null,[W,(s(!0),t(d,null,c(e.gamesRunning,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128)),K,(s(!0),t(d,null,c(e.gamesFinished,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128))])};var H=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});H.render=function(e,l,o,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:l[2]||(l[2]=(...t)=>e.onClick&&e.onClick(...t))},[n("div",{class:"btn edit",onClick:l[1]||(l[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var Y=e({name:"image-library",components:{ImageTeaser:H},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});Y.render=function(e,n,l,o,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,l)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:l},null,8,["image","onClick","onEditClick"])))),128))])};class q{constructor(e){this.rand_high=e||3735929054,this.rand_low=1231121986^e}random(e,t){this.rand_high=(this.rand_high<<16)+(this.rand_high>>16)+this.rand_low&4294967295,this.rand_low=this.rand_low+this.rand_high&4294967295;return e+(this.rand_high>>>0)/4294967295*(t-e+1)|0}choice(e){return e[this.random(0,e.length-1)]}shuffle(e){const t=e.slice();for(let n=0;n<=t.length-2;n++){const e=this.random(n,t.length-1),l=t[n];t[n]=t[e],t[e]=l}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new q(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const Q=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},Z=(...e)=>{const t=t=>(...n)=>{const l=new Date,o=Q(l.getHours(),"00"),a=Q(l.getMinutes(),"00"),s=Q(l.getSeconds(),"00");console[t](`${o}:${a}:${s}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var X={hash:e=>{let t=0;for(let n=0;n<e.length;n++){t=(t<<5)-t+e.charCodeAt(n),t|=0}return t},slug:e=>{let t=e.toLowerCase();return t=t.replace(/[^a-z0-9]+/g,"-"),t=t.replace(/^-|-$/,""),t},uniqId:()=>Date.now().toString(36)+Math.random().toString(36).substring(2),encodeShape:function(e){return e.top+1<<0|e.right+1<<2|e.bottom+1<<4|e.left+1<<6},decodeShape:function(e){return{top:(e>>0&3)-1,right:(e>>2&3)-1,bottom:(e>>4&3)-1,left:(e>>6&3)-1}},encodePiece:function(e){return[e.idx,e.pos.x,e.pos.y,e.z,e.owner,e.group]},decodePiece:function(e){return{idx:e[0],pos:{x:e[1],y:e[2]},z:e[3],owner:e[4],group:e[5]}},encodePlayer:function(e){return[e.id,e.x,e.y,e.d,e.name,e.color,e.bgcolor,e.points,e.ts]},decodePlayer:function(e){return{id:e[0],x:e[1],y:e[2],d:e[3],name:e[4],color:e[5],bgcolor:e[6],points:e[7],ts:e[8]}},encodeGame:function(e){return[e.id,e.rng.type||"",q.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode,e.shapeMode,e.snapMode]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:q.unserialize(e[2])},puzzle:e[3],players:e[4],evtInfos:e[5],scoreMode:e[6],shapeMode:e[7],snapMode:e[8]}},coordByPieceIdx:function(e,t){const n=e.width/e.tileSize;return{x:t%n,y:Math.floor(t/n)}},asQueryArgs:function(e){const t=[];for(const n in e){const l=[n,e[n]].map(encodeURIComponent);t.push(l.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const J={name:"responsive-image",props:{src:String,title:{type:String,default:""},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},computed:{style(){return{display:"inline-block",verticalAlign:"text-bottom",backgroundImage:`url('${this.src}')`,backgroundRepeat:"no-repeat",backgroundSize:"contain",backgroundPosition:"center",width:this.width,height:this.height}}}};J.render=function(e,n,l,o,a,i){return s(),t("div",{style:i.style,title:l.title},null,12,["title"])};var ee=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.idx<this.autocomplete.values.length-1&&this.autocomplete.idx++,e.stopPropagation(),!1):"ArrowUp"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.idx>0&&this.autocomplete.idx--,e.stopPropagation(),!1):","===e.key?(this.add(),e.stopPropagation(),!1):void(this.input&&this.autocompleteTags?(this.autocomplete.values=this.autocompleteTags(this.input,this.values),this.autocomplete.idx=-1):(this.autocomplete.values=[],this.autocomplete.idx=-1))},addVal(e){const t=e.replace(/,/g,"").trim();t&&(this.values.includes(t)||this.values.push(t),this.input="",this.autocomplete.values=[],this.autocomplete.idx=-1,this.$emit("update:modelValue",this.values),this.$refs.input.focus())},add(){const e=this.autocomplete.idx>=0?this.autocomplete.values[this.autocomplete.idx]:this.input;this.addVal(e)},rm(e){this.values=this.values.filter((t=>t!==e)),this.$emit("update:modelValue",this.values)}}});const te=m();y("data-v-a4fa5e7e");const ne={key:0,class:"autocomplete"};f();const le=te(((e,l,a,i,u,m)=>(s(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.input=t),placeholder:"Plants, People",onChange:l[2]||(l[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:l[3]||(l[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:l[4]||(l[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(s(),t("div",ne,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,l)=>(s(),t("li",{key:l,class:{active:l===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):o("",!0),(s(!0),t(d,null,c(e.values,((n,l)=>(s(),t("span",{key:l,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ee.render=le,ee.__scopeId="data-v-a4fa5e7e";const oe=Z("NewImageDialog.vue");var ae=e({name:"new-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const l=n[0];return l.type.startsWith("image/")?l:null},onFileSelect(e){const t=e.target;if(!t.files)return;const n=t.files[0];n&&this.preview(n)},preview(e){const t=new FileReader;t.readAsDataURL(e),t.onload=t=>{this.previewUrl=t.target.result,this.file=e}},postToGallery(){this.$emit("postToGalleryClick",{file:this.file,title:this.title,tags:this.tags})},setupGameClick(){this.$emit("setupGameClick",{file:this.file,title:this.title,tags:this.tags})},onDrop(e){this.droppable=!1;const t=this.imageFromDragEvt(e);if(!t)return!1;const n=t.getAsFile();return!!n&&(this.file=n,this.preview(n),e.preventDefault(),!1)},onDragover(e){return!!this.imageFromDragEvt(e)&&(this.droppable=!0,e.preventDefault(),!1)},onDragleave(){oe.info("onDragleave"),this.droppable=!1}}});const se=n("div",{class:"drop-target"},null,-1),ie={key:0,class:"has-image"},re={key:1},de={class:"upload"},ce=n("span",{class:"btn"},"Upload File",-1),ue={class:"area-settings"},pe=n("td",null,[n("label",null,"Title")],-1),ge=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),he=n("td",null,[n("label",null,"Tags")],-1),me={class:"area-buttons"},ye=i("🖼️ Post to gallery"),fe=i("🧩 Post to gallery "),ve=n("br",null,null,-1),we=i(" + set up game");ae.render=function(e,l,o,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),t("div",{class:"overlay new-image-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:l[3]||(l[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:l[4]||(l[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:l[5]||(l[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[se,e.previewUrl?(s(),t("div",ie,[n("span",{class:"remove btn",onClick:l[1]||(l[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",re,[n("label",de,[n("input",{type:"file",style:{display:"none"},onChange:l[2]||(l[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ce])]))],34),n("div",ue,[n("table",null,[n("tr",null,[pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[6]||(l[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),ge,n("tr",null,[he,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":l[7]||(l[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",me,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:l[8]||(l[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ye],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:l[9]||(l[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[fe,ve,we],64))],8,["disabled"])])])])};var be=e({name:"edit-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{image:{type:Object,required:!0},autocompleteTags:{type:Function}},emits:{bgclick:null,saveClick:null},data:()=>({title:"",tags:[]}),created(){this.title=this.image.title,this.tags=this.image.tags.map((e=>e.title))},methods:{saveImage(){this.$emit("saveClick",{id:this.image.id,title:this.title,tags:this.tags})}}});const Ce={class:"area-image"},xe={class:"has-image"},ke={class:"area-settings"},Pe=n("td",null,[n("label",null,"Title")],-1),Ae=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),Se=n("td",null,[n("label",null,"Tags")],-1),ze={class:"area-buttons"};var Te,Ie,Me,Ee,De,Ne,_e,Ve;be.render=function(e,l,o,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),t("div",{class:"overlay edit-image-dialog",onClick:l[5]||(l[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[4]||(l[4]=u((()=>{}),["stop"]))},[n("div",Ce,[n("div",xe,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",ke,[n("table",null,[n("tr",null,[Pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ae,n("tr",null,[Se,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":l[2]||(l[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",ze,[n("button",{class:"btn",onClick:l[3]||(l[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Ie=Te||(Te={}))[Ie.Flat=0]="Flat",Ie[Ie.Out=1]="Out",Ie[Ie.In=-1]="In",(Ee=Me||(Me={}))[Ee.FINAL=0]="FINAL",Ee[Ee.ANY=1]="ANY",(Ne=De||(De={}))[Ne.NORMAL=0]="NORMAL",Ne[Ne.ANY=1]="ANY",Ne[Ne.FLAT=2]="FLAT",(Ve=_e||(_e={}))[Ve.NORMAL=0]="NORMAL",Ve[Ve.REAL=1]="REAL";var Oe=e({name:"new-game-dialog",components:{ResponsiveImage:J},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Me.ANY,shapeMode:De.NORMAL,snapMode:_e.NORMAL}),methods:{onNewGameClick(){this.$emit("newGame",{tiles:this.tilesInt,image:this.image,scoreMode:this.scoreModeInt,shapeMode:this.shapeModeInt,snapMode:this.snapModeInt})}},computed:{canStartNewGame(){return!!(this.tilesInt&&this.image&&this.image.url&&[0,1].includes(this.scoreModeInt))},scoreModeInt(){return parseInt(`${this.scoreMode}`,10)},shapeModeInt(){return parseInt(`${this.shapeMode}`,10)},snapModeInt(){return parseInt(`${this.snapMode}`,10)},tilesInt(){return parseInt(`${this.tiles}`,10)}}});const Be={class:"area-image"},Ue={class:"has-image"},Re={key:0,class:"image-title"},$e={key:0,class:"image-title-title"},Ge={key:1,class:"image-title-dim"},Le={class:"area-settings"},Fe=n("td",null,[n("label",null,"Pieces")],-1),je=n("td",null,[n("label",null,"Scoring: ")],-1),We=i(" Any (Score when pieces are connected to each other or on final location)"),Ke=n("br",null,null,-1),He=i(" Final (Score when pieces are put to their final location)"),Ye=n("td",null,[n("label",null,"Shapes: ")],-1),qe=i(" Normal"),Qe=n("br",null,null,-1),Ze=i(" Any (flat pieces can occur anywhere)"),Xe=n("br",null,null,-1),Je=i(" Flat (all pieces flat on all sides)"),et=n("td",null,[n("label",null,"Snapping: ")],-1),tt=i(" Normal (pieces snap to final destination and to each other)"),nt=n("br",null,null,-1),lt=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ot={class:"area-buttons"};Oe.render=function(e,l,i,d,c,h){const m=a("responsive-image");return s(),t("div",{class:"overlay new-game-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",Be,[n("div",Ue,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",Re,[e.image.title?(s(),t("span",$e,'"'+r(e.image.title)+'"',1)):o("",!0),e.image.width||e.image.height?(s(),t("span",Ge,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):o("",!0)])):o("",!0)]),n("div",Le,[n("table",null,[n("tr",null,[Fe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[je,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[2]||(l[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),We]),Ke,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[3]||(l[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),He])])]),n("tr",null,[Ye,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[4]||(l[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),qe]),Qe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[5]||(l[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),Ze]),Xe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[6]||(l[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),Je])])]),n("tr",null,[et,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[7]||(l[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),tt]),nt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[8]||(l[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),lt])])])])]),n("div",ot,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:l[9]||(l[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};const at=async(e,t,n)=>new Promise(((l,o)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.addEventListener("load",(function(e){l({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){o(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body)}));var st=(e,t)=>at("post",e,t),it=e({components:{ImageLibrary:Y,NewImageDialog:ae,EditImageDialog:be,NewGameDialog:Oe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await fetch(`/api/newgame-data${X.asQueryArgs(this.filters)}`),t=await e.json();this.images=t.images,this.tags=t.tags},async filtersChanged(){await this.loadImages()},onImageClicked(e){this.image=e,this.dialog="new-game"},onImageEditClicked(e){this.image=e,this.dialog="edit-image"},async uploadImage(e){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await st("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await fetch("/api/save-image",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({id:e.id,title:e.title,tags:e.tags})});return await t.json()},async onSaveImageClick(e){await this.saveImage(e),this.dialog="",await this.loadImages()},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await fetch("/api/newgame",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)});if(200===t.status){const e=await t.json();this.$router.push({name:"game",params:{id:e.id}})}}}});const rt={class:"upload-image-teaser"},dt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ct={key:0},ut=i(" Tags: "),pt=i(" Sort by: "),gt=n("option",{value:"date_desc"},"Newest first",-1),ht=n("option",{value:"date_asc"},"Oldest first",-1),mt=n("option",{value:"alpha_asc"},"A-Z",-1),yt=n("option",{value:"alpha_desc"},"Z-A",-1);it.render=function(e,l,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",rt,[n("div",{class:"btn btn-big",onClick:l[1]||(l[1]=t=>e.dialog="new-image")},"Upload your image"),dt]),n("div",null,[e.tags.length>0?(s(),t("label",ct,[ut,(s(!0),t(d,null,c(e.relevantTags,((n,l)=>(s(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:l,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):o("",!0),n("label",null,[pt,p(n("select",{"onUpdate:modelValue":l[2]||(l[2]=t=>e.filters.sort=t),onChange:l[3]||(l[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[gt,ht,mt,yt],544),[[w,e.filters.sort]])])]),n(m,{images:e.images,onImageClicked:e.onImageClicked,onImageEditClicked:e.onImageEditClicked},null,8,["images","onImageClicked","onImageEditClicked"]),"new-image"===e.dialog?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:l[4]||(l[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):o("",!0),"edit-image"===e.dialog?(s(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:l[5]||(l[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):o("",!0),e.image&&"new-game"===e.dialog?(s(),t(v,{key:2,onBgclick:l[6]||(l[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):o("",!0)])};var ft=e({name:"scores",props:{activePlayers:{type:Array,required:!0},idlePlayers:{type:Array,required:!0}},computed:{actives(){return this.activePlayers.sort(((e,t)=>t.points-e.points)),this.activePlayers},idles(){return this.idlePlayers.sort(((e,t)=>t.points-e.points)),this.idlePlayers}}});const vt={class:"scores"},wt=n("div",null,"Scores",-1),bt=n("td",null,"⚡",-1),Ct=n("td",null,"💤",-1);ft.render=function(e,l,o,a,i,u){return s(),t("div",vt,[wt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[bt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[Ct,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var xt=e({name:"puzzle-status",props:{finished:{type:Boolean,required:!0},duration:{type:Number,required:!0},piecesDone:{type:Number,required:!0},piecesTotal:{type:Number,required:!0}},computed:{icon(){return this.finished?"🏁":"⏳"},durationStr(){return B(this.duration)}}});const kt={class:"timer"};xt.render=function(e,l,o,a,i,d){return s(),t("div",kt,[n("div",null," 🧩 "+r(e.piecesDone)+"/"+r(e.piecesTotal),1),n("div",null,r(e.icon)+" "+r(e.durationStr),1),b(e.$slots,"default")])};var Pt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const At=m();y("data-v-4d56fc17");const St=n("td",null,[n("label",null,"Background: ")],-1),zt=n("td",null,[n("label",null,"Color: ")],-1),Tt=n("td",null,[n("label",null,"Name: ")],-1),It=n("td",null,[n("label",null,"Sounds: ")],-1),Mt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Et={class:"sound-volume"},Dt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Nt=At(((e,l,o,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:l[10]||(l[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:l[9]||(l[9]=u((()=>{}),["stop"]))},[n("tr",null,[St,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[1]||(l[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[zt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[2]||(l[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[Tt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":l[3]||(l[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[It,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[4]||(l[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Mt,n("td",Et,[n("span",{onClick:l[5]||(l[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:l[6]||(l[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:l[7]||(l[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[8]||(l[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));Pt.render=Nt,Pt.__scopeId="data-v-4d56fc17";var _t=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const Vt={class:"preview"};_t.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay",onClick:l[1]||(l[1]=t=>e.$emit("bgclick"))},[n("div",Vt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Ot=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Me.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Me.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case De.FLAT:return["Flat","all pieces flat on all sides"];case De.ANY:return["Any","flat pieces can occur anywhere"];case De.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case _e.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case _e.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Bt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ut=n("td",null,"Image Title: ",-1),Rt=n("td",null,"Snap Mode: ",-1),$t=n("td",null,"Shape Mode: ",-1),Gt=n("td",null,"Score Mode: ",-1);Ot.render=function(e,l,o,a,i,d){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Bt,n("tr",null,[Ut,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[Rt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[$t,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Gt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Lt=1,Ft=4,jt=2,Wt=3,Kt=2,Ht=4,Yt=3,qt=9,Qt=1,Zt=2,Xt=3,Jt=4,en=5,tn=6,nn=7,ln=8,on=10,an=11,sn=12,rn=13,dn=14,cn=15,un=16,pn=1,gn=2,hn=3;const mn=Z("Communication.js");let yn,fn=[],vn=e=>{fn.push(e)},wn=[],bn=e=>{wn.push(e)};let Cn=0;const xn=e=>{Cn!==e&&(Cn=e,bn(e))};function kn(e){if(2===Cn)try{yn.send(JSON.stringify(e))}catch(t){mn.info("unable to send message.. maybe because ws is invalid?")}}let Pn,An;var Sn={connect:function(e,t,n){return Pn=0,An={},xn(3),new Promise((l=>{yn=new WebSocket(e,n+"|"+t),yn.onopen=()=>{xn(2),kn([Wt])},yn.onmessage=e=>{const t=JSON.parse(e.data),o=t[0];if(o===Ft){const e=t[1];l(e)}else{if(o!==Lt)throw`[ 2021-05-09 invalid connect msgType ${o} ]`;{const e=t[1],l=t[2];if(e===n&&An[l])return void delete An[l];vn(t)}}},yn.onerror=()=>{throw xn(1),"[ 2021-05-15 onerror ]"},yn.onclose=e=>{4e3===e.code||1001===e.code?xn(4):xn(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},l=await fetch(`/api/replay-data${X.asQueryArgs(n)}`);return await l.json()},disconnect:function(){yn&&yn.close(4e3),Pn=0,An={}},sendClientEvent:function(e){Pn++,An[Pn]=e,kn([jt,Pn,An[Pn]])},onServerChange:function(e){vn=e;for(const t of fn)vn(t);fn=[]},onConnectionStateChange:function(e){bn=e;for(const t of wn)bn(t);wn=[]},CODE_CUSTOM_DISCONNECT:4e3,CONN_STATE_NOT_CONNECTED:0,CONN_STATE_DISCONNECTED:1,CONN_STATE_CLOSED:4,CONN_STATE_CONNECTED:2,CONN_STATE_CONNECTING:3},zn=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===Sn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===Sn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const Tn={key:0,class:"overlay connection-lost"},In={key:0,class:"overlay-content"},Mn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),En={key:1,class:"overlay-content"},Dn=n("div",null,"Connecting...",-1);zn.render=function(e,l,a,i,r,d){return e.show?(s(),t("div",Tn,[e.lostConnection?(s(),t("div",In,[Mn,n("span",{class:"btn",onClick:l[1]||(l[1]=t=>e.$emit("reconnect"))},"Reconnect")])):o("",!0),e.connecting?(s(),t("div",En,[Dn])):o("",!0)])):o("",!0)};var Nn=e({name:"help-overlay",emits:{bgclick:null}});const _n=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Vn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),On=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),Bn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Un=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Rn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),$n=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),Gn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Ln=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Fn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),jn=n("tr",null,[n("td",null,"🧩❓ Toggle loose pieces:"),n("td",null,[n("div",null,[n("kbd",null,"G")])])],-1),Wn=n("tr",null,[n("td",null,"👤 Toggle player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Kn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),Hn=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),Yn=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),qn=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);Nn.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[_n,Vn,On,Bn,Un,Rn,$n,Gn,Ln,Fn,jn,Wn,Kn,Hn,Yn,qn])])};var Qn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),Zn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),Xn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Jn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),el=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function tl(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var nl={createCanvas:tl,loadImageToBitmap:async function(e){return new Promise((t=>{const n=new Image;n.onload=()=>{createImageBitmap(n).then(t)},n.src=e}))},resizeBitmap:async function(e,t,n){const l=tl(t,n);return l.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(l)},colorizedCanvas:function(e,t,n){const l=tl(e.width,e.height),o=l.getContext("2d");return o.save(),o.drawImage(t,0,0),o.fillStyle=n,o.globalCompositeOperation="source-in",o.fillRect(0,0,t.width,t.height),o.restore(),o.save(),o.globalCompositeOperation="destination-over",o.drawImage(e,0,0),o.restore(),l}};const ll=Z("Debug.js");let ol=0,al=0;var sl=e=>{ol=performance.now(),al=e},il=e=>{const t=performance.now(),n=t-ol;n>al&&ll.log(e+": "+n),ol=t};function rl(e,t){const n=e.x-t.x,l=e.y-t.y;return Math.sqrt(n*n+l*l)}function dl(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var cl={pointSub:function(e,t){return{x:e.x-t.x,y:e.y-t.y}},pointAdd:function(e,t){return{x:e.x+t.x,y:e.y+t.y}},pointDistance:rl,pointInBounds:function(e,t){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h},rectCenter:dl,rectMoved:function(e,t,n){return{x:e.x+t,y:e.y+n,w:e.w,h:e.h}},rectCenterDistance:function(e,t){return rl(dl(e),dl(t))},rectsOverlap:function(e,t){return!(t.x>e.x+e.w||e.x>t.x+t.w||t.y>e.y+e.h||e.y>t.y+t.h)}};const ul=Z("PuzzleGraphics.js");function pl(e,t){const n=X.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var gl={loadPuzzleBitmaps:async function(e){const t=await nl.loadImageToBitmap(e.info.imageUrl),n=await nl.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){ul.log("start createPuzzleTileBitmaps");const l=n.tileSize,o=n.tileMarginWidth,a=n.tileDrawSize,s=l/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:o,y:o},r=cl.pointAdd(a,{x:l,y:0}),c=cl.pointAdd(r,{x:0,y:l}),u=cl.pointSub(c,{x:l,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let l=0;l<i.length/6;l++){const t=cl.pointAdd(a,{x:i[6*l+0]*s,y:e.top*i[6*l+1]*s}),o=cl.pointAdd(a,{x:i[6*l+2]*s,y:e.top*i[6*l+3]*s}),r=cl.pointAdd(a,{x:i[6*l+4]*s,y:e.top*i[6*l+5]*s});n.bezierCurveTo(t.x,t.y,o.x,o.y,r.x,r.y)}else n.lineTo(r.x,r.y);if(0!==e.right)for(let l=0;l<i.length/6;l++){const t=cl.pointAdd(r,{x:-e.right*i[6*l+1]*s,y:i[6*l+0]*s}),o=cl.pointAdd(r,{x:-e.right*i[6*l+3]*s,y:i[6*l+2]*s}),a=cl.pointAdd(r,{x:-e.right*i[6*l+5]*s,y:i[6*l+4]*s});n.bezierCurveTo(t.x,t.y,o.x,o.y,a.x,a.y)}else n.lineTo(c.x,c.y);if(0!==e.bottom)for(let l=0;l<i.length/6;l++){const t=cl.pointSub(c,{x:i[6*l+0]*s,y:e.bottom*i[6*l+1]*s}),o=cl.pointSub(c,{x:i[6*l+2]*s,y:e.bottom*i[6*l+3]*s}),a=cl.pointSub(c,{x:i[6*l+4]*s,y:e.bottom*i[6*l+5]*s});n.bezierCurveTo(t.x,t.y,o.x,o.y,a.x,a.y)}else n.lineTo(u.x,u.y);if(0!==e.left)for(let l=0;l<i.length/6;l++){const t=cl.pointSub(u,{x:-e.left*i[6*l+1]*s,y:i[6*l+0]*s}),o=cl.pointSub(u,{x:-e.left*i[6*l+3]*s,y:i[6*l+2]*s}),a=cl.pointSub(u,{x:-e.left*i[6*l+5]*s,y:i[6*l+4]*s});n.bezierCurveTo(t.x,t.y,o.x,o.y,a.x,a.y)}else n.lineTo(a.x,a.y);return d[t]=n,n}const u=nl.createCanvas(a,a),p=u.getContext("2d"),g=nl.createCanvas(a,a),h=g.getContext("2d");for(const m of t){const t=X.decodePiece(m),l=pl(n,t.idx),s=c(X.decodeShape(n.shapes[t.idx]));p.clearRect(0,0,a,a),p.save(),p.lineWidth=2,p.stroke(s),p.globalCompositeOperation="source-in",p.drawImage(e,l.x-o,l.y-o,a,a,0,0,a,a),p.restore(),p.save(),p.globalCompositeOperation="source-in",p.globalAlpha=.2,p.fillStyle="black",p.fillRect(0,0,u.width,u.height),p.restore(),p.save(),p.clip(s),p.drawImage(e,l.x-o,l.y-o,a,a,0,0,a,a),p.restore(),p.save(),p.clip(s),p.strokeStyle="rgba(0,0,0,.4)",p.lineWidth=0,p.shadowColor="black",p.shadowBlur=2,p.shadowOffsetX=-1,p.shadowOffsetY=-1,p.stroke(s),p.restore(),p.save(),p.clip(s),p.strokeStyle="rgba(255,255,255,.4)",p.lineWidth=0,p.shadowColor="white",p.shadowBlur=2,p.shadowOffsetX=1,p.shadowOffsetY=1,p.stroke(s),p.restore(),h.clearRect(0,0,a,a),h.save(),h.lineWidth=1,h.stroke(s),h.globalCompositeOperation="source-in",h.drawImage(e,l.x-o,l.y-o,a,a,0,0,a,a),h.restore(),p.drawImage(g,0,0),r[t.idx]=await createImageBitmap(u)}return ul.log("end createPuzzleTileBitmaps"),r}(n,e.tiles,e.info)}};const hl={};function ml(e,t){let n=0;for(const l of hl[e].players){if(X.decodePlayer(l).id===t)return n;n++}return-1}function yl(e,t){const n=ml(e,t);return-1===n?null:X.decodePlayer(hl[e].players[n])}function fl(e,t,n){const l=ml(e,t);-1===l?hl[e].players.push(X.encodePlayer(n)):hl[e].players[l]=X.encodePlayer(n)}function vl(e,t){return-1!==ml(e,t)}function wl(e){return hl[e]?hl[e].players.map(X.decodePlayer):[]}function bl(e){return hl[e].puzzle.tiles.length}function Cl(e){return hl[e].scoreMode}function xl(e){return hl[e].snapMode}function kl(e){return Pl(e)===bl(e)}function Pl(e){let t=0;for(const n of hl[e].puzzle.tiles)-1===X.decodePiece(n).owner&&t++;return t}function Al(e,t,n){const l=yl(e,t);if(null!==l){for(const e of Object.keys(n))l[e]=n[e];fl(e,t,l)}}function Sl(e,t){for(const n of Object.keys(t))hl[e].puzzle.data[n]=t[n]}function zl(e,t,n){for(const l of Object.keys(n)){const o=X.decodePiece(hl[e].puzzle.tiles[t]);o[l]=n[l],hl[e].puzzle.tiles[t]=X.encodePiece(o)}}const Tl=(e,t)=>X.decodePiece(hl[e].puzzle.tiles[t]),Il=(e,t)=>Tl(e,t).group,Ml=(e,t)=>{const n=hl[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},El=(e,t)=>{const n=hl[e].puzzle.info,l={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},o=function(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t),o=l.x*n.tileSize,a=l.y*n.tileSize;return{x:o,y:a}}(e,t);return cl.pointAdd(l,o)},Dl=(e,t)=>Tl(e,t).pos,Nl=e=>{const t=Ql(e),n=Zl(e),l=Math.round(t/4),o=Math.round(n/4);return{x:0-l,y:0-o,w:t+2*l,h:n+2*o}},_l=(e,t)=>{const n=Ul(e),l=Tl(e,t);return{x:l.pos.x,y:l.pos.y,w:n,h:n}},Vl=(e,t)=>Tl(e,t).z,Ol=(e,t)=>{for(const n of hl[e].puzzle.tiles){const e=X.decodePiece(n);if(e.owner===t)return e.idx}return-1},Bl=e=>hl[e].puzzle.info.tileDrawSize,Ul=e=>hl[e].puzzle.info.tileSize,Rl=e=>hl[e].puzzle.data.maxGroup,$l=e=>hl[e].puzzle.data.maxZ;function Gl(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t);return[l.y>0?t-n.tilesX:-1,l.x<n.tilesX-1?t+1:-1,l.y<n.tilesY-1?t+n.tilesX:-1,l.x>0?t-1:-1]}const Ll=(e,t,n)=>{for(const l of t)zl(e,l,{z:n})},Fl=(e,t,n)=>{const l=Dl(e,t);zl(e,t,{pos:cl.pointAdd(l,n)})},jl=(e,t,n)=>{const l=Bl(e),o=Nl(e),a=n;for(const s of t){const t=Tl(e,s);t.pos.x+n.x<o.x?a.x=Math.max(o.x-t.pos.x,a.x):t.pos.x+l+n.x>o.x+o.w&&(a.x=Math.min(o.x+o.w-t.pos.x+l,a.x)),t.pos.y+n.y<o.y?a.y=Math.max(o.y-t.pos.y,a.y):t.pos.y+l+n.y>o.y+o.h&&(a.y=Math.min(o.y+o.h-t.pos.y+l,a.y))}for(const s of t)Fl(e,s,a)},Wl=(e,t)=>Tl(e,t).owner,Kl=(e,t)=>{for(const n of t)zl(e,n,{owner:-1,z:1})},Hl=(e,t,n)=>{for(const l of t)zl(e,l,{owner:n})};function Yl(e,t){const n=hl[e].puzzle.tiles,l=X.decodePiece(n[t]),o=[];if(l.group)for(const a of n){const e=X.decodePiece(a);e.group===l.group&&o.push(e.idx)}else o.push(l.idx);return o}const ql=(e,t)=>{const n=yl(e,t);return n?n.points:0},Ql=e=>hl[e].puzzle.info.table.width,Zl=e=>hl[e].puzzle.info.table.height;var Xl={setGame:function(e,t){hl[e]=t},exists:function(e){return!!hl[e]||!1},playerExists:vl,getActivePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts<n&&e.points>0))},addPlayer:function(e,t,n){vl(e,t)?Al(e,t,{ts:n}):fl(e,t,function(e,t){return{id:e,x:0,y:0,d:0,name:null,color:null,bgcolor:null,points:0,ts:t}}(t,n))},getFinishedPiecesCount:Pl,getPieceCount:bl,getImageUrl:function(e){var t;const n=(null==(t=hl[e].puzzle.info.image)?void 0:t.url)||hl[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return hl[e]||null},getAllGames:function(){return Object.values(hl).sort(((e,t)=>kl(e.id)===kl(t.id)?t.puzzle.data.started-e.puzzle.data.started:kl(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=yl(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=yl(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=yl(e,t);return n?n.name:null},getPlayerIndexById:ml,getPlayerIdByIndex:function(e,t){return hl[e].players.length>t?X.decodePlayer(hl[e].players[t]).id:null},changePlayer:Al,setPlayer:fl,setPiece:function(e,t,n){hl[e].puzzle.tiles[t]=X.encodePiece(n)},setPuzzleData:function(e,t){hl[e].puzzle.data=t},getTableWidth:Ql,getTableHeight:Zl,getPuzzle:e=>hl[e].puzzle,getRng:e=>hl[e].rng.obj,getPuzzleWidth:e=>hl[e].puzzle.info.width,getPuzzleHeight:e=>hl[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return hl[e].puzzle.tiles.map(X.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Ol(e,t);return n<0?null:hl[e].puzzle.tiles[n]},getPieceDrawOffset:e=>hl[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Bl,getFinalPiecePos:El,getStartTs:e=>hl[e].puzzle.data.started,getFinishTs:e=>hl[e].puzzle.data.finished,handleInput:function(e,t,n,l,o){const a=hl[e].puzzle,s=function(e,t){return t in hl[e].evtInfos?hl[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([pn,a.data])},d=t=>{i.push([gn,X.encodePiece(Tl(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=yl(e,t);n&&i.push([hn,X.encodePlayer(n)])},p=n[0];if(p===tn){const o=n[1];Al(e,t,{bgcolor:o,ts:l}),u()}else if(p===nn){const o=n[1];Al(e,t,{color:o,ts:l}),u()}else if(p===ln){const o=`${n[1]}`.substr(0,16);Al(e,t,{name:o,ts:l}),u()}else if(p===qt){const o=n[1],a=n[2],s=yl(e,t);if(s){const n=s.x-o,i=s.y-a;Al(e,t,{ts:l,x:n,y:i}),u()}}else if(p===Qt){const o={x:n[1],y:n[2]};Al(e,t,{d:1,ts:l}),u(),s._last_mouse_down=o;const a=((e,t)=>{const n=hl[e].puzzle.info,l=hl[e].puzzle.tiles;let o=-1,a=-1;for(let s=0;s<l.length;s++){const e=X.decodePiece(l[s]);if(0!==e.owner)continue;const i={x:e.pos.x,y:e.pos.y,w:n.tileSize,h:n.tileSize};cl.pointInBounds(t,i)&&(-1===o||e.z>o)&&(o=e.z,a=s)}return a})(e,o);if(a>=0){const n=$l(e)+1;Sl(e,{maxZ:n}),r();const l=Yl(e,a);Ll(e,l,$l(e)),Hl(e,l,t),c(l)}s._last_mouse=o}else if(p===Xt){const o=n[1],a=n[2],i={x:o,y:a};if(null===s._last_mouse_down)Al(e,t,{x:o,y:a,ts:l}),u();else{const n=Ol(e,t);if(n>=0){Al(e,t,{x:o,y:a,ts:l}),u();const r=Yl(e,n);let d=cl.pointInBounds(i,Nl(e))&&cl.pointInBounds(s._last_mouse_down,Nl(e));for(const t of r){const n=_l(e,t);if(cl.pointInBounds(i,n)){d=!0;break}}if(d){const t=o-s._last_mouse_down.x,n=a-s._last_mouse_down.y;jl(e,r,{x:t,y:n}),c(r)}}else Al(e,t,{ts:l}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===Zt){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Ol(e,t);if(g>=0){const n=Yl(e,g);Hl(e,n,0),c(n);const s=Dl(e,g),i=El(e,g);let h=!1;if(xl(e)===_e.REAL){for(const t of n)if(Ml(e,t)){h=!0;break}}else h=!0;if(h&&cl.pointDistance(i,s)<a.info.snapDistance){const a=cl.pointSub(i,s);jl(e,n,a),Kl(e,n),c(n);let d=ql(e,t);Cl(e)===Me.FINAL?d+=n.length:Cl(e)===Me.ANY&&(d+=1),Al(e,t,{d:p,ts:l,points:d}),u(),Pl(e)===bl(e)&&(Sl(e,{finished:l}),r()),o&&o(t)}else{const n=(e,t,n,l)=>{const o=hl[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const l=Il(e,t),o=Il(e,n);return!(!l||l!==o)})(e,t,n))return!1;const a=Dl(e,t),s=cl.pointAdd(Dl(e,n),{x:l[0]*o.tileSize,y:l[1]*o.tileSize});if(cl.pointDistance(a,s)<o.snapDistance){const l=cl.pointSub(s,a);let o=Yl(e,t);if(jl(e,o,l),((e,t,n)=>{const l=hl[e].puzzle.tiles,o=Il(e,t),a=Il(e,n);let s;const i=[];o&&i.push(o),a&&i.push(a),o?s=o:a?s=a:(Sl(e,{maxGroup:Rl(e)+1}),r(),s=Rl(e));if(zl(e,t,{group:s}),d(t),zl(e,n,{group:s}),d(n),i.length>0)for(const r of l){const t=X.decodePiece(r);i.includes(t.group)&&(zl(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),o=Yl(e,t),((e,t)=>-1===Wl(e,t))(e,n))Kl(e,o);else{const t=((e,t)=>{let n=0;for(const l of t){const t=Vl(e,l);t>n&&(n=t)}return n})(e,o);Ll(e,o,t)}return c(o),!0}return!1};let a=!1;for(const t of Yl(e,g)){const l=Gl(e,t);if(n(e,t,l[0],[0,1])||n(e,t,l[1],[-1,0])||n(e,t,l[2],[0,-1])||n(e,t,l[3],[1,0])){a=!0;break}}if(a&&Cl(e)===Me.ANY){const n=ql(e,t)+1;Al(e,t,{d:p,ts:l,points:n}),u()}else Al(e,t,{d:p,ts:l}),u();a&&xl(e)===_e.REAL&&Pl(e)===bl(e)&&(Sl(e,{finished:l}),r()),a&&o&&o(t)}}else Al(e,t,{d:p,ts:l}),u();s._last_mouse=i}else if(p===Jt){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else if(p===en){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else Al(e,t,{ts:l}),u();return function(e,t,n){hl[e].evtInfos[t]=n}(e,t,s),i}};let Jl=-10,eo=20,to=2,no=15;class lo{constructor(e){this.radius=10,this.previousRadius=10,this.explodingDuration=100,this.hasExploded=!1,this.alive=!0,this.color=function(e){return"rgba("+e.random(0,255)+","+e.random(0,255)+","+e.random(0,255)+", 0.8)"}(e),this.px=window.innerWidth/4+Math.random()*window.innerWidth/2,this.py=window.innerHeight,this.vx=Jl+Math.random()*eo,this.vy=-1*(to+Math.random()*no),this.duration=0}update(e){if(this.hasExploded){const e=200-this.radius;this.previousRadius=this.radius,this.radius+=e/10,this.explodingDuration--,0==this.explodingDuration&&(this.alive=!1)}else this.vx+=0,this.vy+=1,this.vy>=0&&e&&this.explode(e),this.px+=this.vx,this.py+=this.vy}draw(e){e.beginPath(),e.arc(this.px,this.py,this.previousRadius,0,2*Math.PI,!1),this.hasExploded||(e.fillStyle=this.color,e.lineWidth=1,e.fill())}explode(e){this.hasExploded=!0;const t=3+Math.floor(3*Math.random());for(let n=0;n<t;n++){const t=10+Math.floor(21*Math.random()),n=5+5*Math.random(),l=2*Math.PI/t,o=Math.random()*l;for(let a=0;a<t;a++)e.push(new oo(this,a*l+o,n))}}}class oo{constructor(e,t,n){this.px=e.px,this.py=e.py,this.vx=Math.cos(t)*n,this.vy=Math.sin(t)*n,this.color=e.color,this.duration=40+Math.floor(20*Math.random()),this.alive=!0,this.radius=0}update(){this.vx+=0,this.vy+=.1,this.px+=this.vx,this.py+=this.vy,this.radius=3,this.duration--,this.duration<=0&&(this.alive=!1)}draw(e){e.beginPath(),e.arc(this.px,this.py,this.radius,0,2*Math.PI,!1),e.fillStyle=this.color,e.lineWidth=1,e.fill()}}class ao{constructor(e,t){this.canvas=e,this.rng=t,this.ctx=this.canvas.getContext("2d"),this.resize(),this.readyBombs=[],this.explodedBombs=[],this.particles=[],window.addEventListener("resize",(()=>{this.resize()}))}setSpeedParams(){let e=0,t=0;for(;e<this.canvas.height&&t>=0;)t+=1,e+=t;to=t/2,no=t-to;const n=1/4*this.canvas.width/(t/2);Jl=-n,eo=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new lo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new lo(this.rng));const e=[];for(;this.explodedBombs.length>0;){const t=this.explodedBombs.shift();if(!t)break;t.update(),t.alive&&e.push(t)}this.explodedBombs=e;const t=[];for(;this.readyBombs.length>0;){const e=this.readyBombs.shift();if(!e)break;e.update(this.particles),e.hasExploded?this.explodedBombs.push(e):t.push(e)}this.readyBombs=t;const n=[];for(;this.particles.length>0;){const e=this.particles.shift();if(!e)break;e.update(),e.alive&&n.push(e)}this.particles=n}render(){this.ctx.beginPath(),this.ctx.fillStyle="rgba(0, 0, 0, 0.1)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height);for(let e=0;e<this.readyBombs.length;e++)this.readyBombs[e].draw(this.ctx);for(let e=0;e<this.explodedBombs.length;e++)this.explodedBombs[e].draw(this.ctx);for(let e=0;e<this.particles.length;e++)this.particles[e].draw(this.ctx)}}const so="sound_volume",io="sound_enabled",ro="bg_color",co="player_color",uo="player_name",po="show_player_names",go=(e,t)=>{localStorage.setItem(e,t)},ho=e=>localStorage.getItem(e);var mo=(e,t)=>{go(e,`${t}`)},yo=(e,t)=>{const n=ho(e);if(null===n)return t;const l=parseInt(n,10);return isNaN(l)?t:l},fo=(e,t)=>{go(e,t?"1":"0")},vo=(e,t)=>{const n=ho(e);return null===n?t:"1"===n},wo=(e,t)=>{go(e,t)},bo=(e,t)=>{const n=ho(e);return null===n?t:n};const Co={"./grab.png":Zn,"./grab_mask.png":Xn,"./hand.png":Jn,"./hand_mask.png":el},xo={"./click.mp3":Qn};let ko=!0,Po=!0;let Ao=!0;async function So(e,t,n,l,o,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=xo["./click.mp3"].default,i=new Audio(s),r=await nl.loadImageToBitmap(Co["./grab.png"].default),d=await nl.loadImageToBitmap(Co["./hand.png"].default),c=await nl.loadImageToBitmap(Co["./grab_mask.png"].default),u=await nl.loadImageToBitmap(Co["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const l=e.d?c:u;y[t]=await createImageBitmap(nl.colorizedCanvas(n,l,e.color))}else y[t]=n}return y[t]},v=function(e,t){return t.width=window.innerWidth,t.height=window.innerHeight,e.appendChild(t),window.addEventListener("resize",(()=>{t.width=window.innerWidth,t.height=window.innerHeight,Ao=!0})),t}(o,nl.createCanvas()),w={final:!1,log:[],logPointer:0,speeds:[.5,1,2,5,10,20,50,100,250,500],speedIdx:1,paused:!1,lastRealTs:0,lastGameTs:0,gameStartTs:0,skipNonActionPhases:!0,dataOffset:0};Sn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Sn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===l){const l=await Sn.connect(n,e,t),o=X.decodeGame(l);Xl.setGame(o.id,o),C=()=>V()}else{if("replay"!==l)throw"[ 2020-12-22 MODE invalid, must be play|replay ]";{const t=await b(e);if(!t.game)throw"[ 2021-05-29 no game received ]";const n=X.decodeGame(t.game);Xl.setGame(n.id,n),w.lastRealTs=V(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Ao=!0};await x();const k=Xl.getPieceDrawOffset(e),P=Xl.getPieceDrawSize(e),A=Xl.getPuzzleWidth(e),S=Xl.getPuzzleHeight(e),z=Xl.getTableWidth(e),T=Xl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},M={w:A,h:S},E={w:P,h:P},D=await gl.loadPuzzleBitmaps(Xl.getPuzzle(e)),_=new ao(v,Xl.getRng(e));_.init();const O=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const B=function(){let e=0,t=0,n=1;const l=(l,o)=>{e+=l/n,t+=o/n},o=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=(e,t)=>{if(n==e)return!1;const o=1-n/e;return l(-t.x*o,-t.y*o),n=e,!0},s=l=>({x:l.x/n-e,y:l.y/n-t}),i=l=>({x:(l.x+e)*n,y:(l.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:l,canZoom:e=>n!=o(e),zoom:(e,t)=>a(o(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),U=()=>{B.reset(),B.move(-(z-v.width)/2,-(T-v.height)/2);const e=B.worldDimToViewport(M),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w<t&&e.h<n){const l=Math.min(t/e.w,n/e.h);B.setZoom(l,{x:v.width/2,y:v.height/2})}};U();const R=function(e,t,n,l){let o=[],a=!0,s=!1,i=!1,r=!1,d=!1,c=!1,u=!1,p=!1;const g=(e,t)=>{const l=n.viewportToWorld({x:e,y:t});return[l.x,l.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([Qt,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([Zt,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([Xt,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Jt:en;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([on]),"replay"===l&&("KeyI"===e.code&&v([rn]),"KeyO"===e.code&&v([dn]),"KeyP"===e.code&&v([sn])),"KeyF"===e.code&&(ko=!ko,Ao=!0),"KeyG"===e.code&&(Po=!Po,Ao=!0),"KeyM"===e.code&&v([an]),"KeyN"===e.code&&v([cn]),"KeyC"===e.code&&v([un]))}));const v=e=>{o.push(e)};return{addEvent:v,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const l=(p?24:12)*Math.sqrt(n.getCurrentZoom()),o=n.viewportDimToWorld({w:e*l,h:t*l});v([qt,o.w,o.h]),f&&(f[0]-=o.w,f[1]-=o.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([Jt,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([en,...e])}},setHotkeys:e=>{a=e}}}(v,window,B,l),$=Xl.getImageUrl(e),G=()=>{const t=Xl.getStartTs(e),n=Xl.getFinishTs(e),l=C();a.setFinished(!!n),a.setDuration((n||l)-t)};G(),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),a.setPiecesTotal(Xl.getPieceCount(e));const L=C();a.setActivePlayers(Xl.getActivePlayers(e,L)),a.setIdlePlayers(Xl.getIdlePlayers(e,L));const F=!!Xl.getFinishTs(e);let j=F;const W=()=>j&&!F,K=()=>yo(so,100),H=()=>vo(io,!1),Y=()=>vo(po,!0),q=()=>{const e=K();i.volume=e/100,i.play()},Q=()=>"replay"===l?bo(ro,"#222222"):Xl.getPlayerBgColor(e,t)||bo(ro,"#222222"),Z=()=>"replay"===l?bo(co,"#ffffff"):Xl.getPlayerColor(e,t)||bo(co,"#ffffff");let J="",ee="",te=!1;const ne=e=>{te=e;const[t,n]=e?[J,"grab"]:[ee,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},le=e=>{J=nl.colorizedCanvas(r,c,e).toDataURL(),ee=nl.colorizedCanvas(d,u,e).toDataURL(),ne(te)};le(Z());const oe=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},ae=()=>{w.speedIdx+1<w.speeds.length&&(w.speedIdx++,oe())},se=()=>{w.speedIdx>=1&&(w.speedIdx--,oe())},ie=()=>{w.paused=!w.paused,oe()},re=[];let de;let ce;if("play"===l?re.push(setInterval((()=>{G()}),1e3)):"replay"===l&&oe(),"play"===l)Sn.onServerChange((n=>{n[0],n[1],n[2];const l=n[3];for(const[o,a]of l)switch(o){case hn:{const n=X.decodePlayer(a);n.id!==t&&(Xl.setPlayer(e,n.id,n),Ao=!0)}break;case gn:{const t=X.decodePiece(a);Xl.setPiece(e,t.idx,t),Ao=!0}break;case pn:Xl.setPuzzleData(e,a),Ao=!0}j=!!Xl.getFinishTs(e)}));else if("replay"===l){const t=(t,n)=>{const l=t;if(l[0]===Kt){const t=l[1];return Xl.addPlayer(e,t,n),!0}if(l[0]===Ht){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return Xl.addPlayer(e,t,n),!0}if(l[0]===Yt){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const o=l[2];return Xl.handleInput(e,t,o,n),!0}return!1};let n=w.lastGameTs;const l=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=V();if(w.paused)return w.lastRealTs=o,void(de=setTimeout(l,50));const a=(o-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const l=w.log[w.logPointer],o=n+l[l.length-1],a=w.log[e],i=a[a.length-1],r=o+i;if(r>s){s+500*N<r&&(s+=i);break}n=o,t(a,r)&&(Ao=!0),w.logPointer=e}w.lastRealTs=o,w.lastGameTs=s,G(),w.final||(de=setTimeout(l,50))};l()}let ue=null;return ce=(e=>{let t=!1;const n=e.fps||60,l=e.slow||1,o=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=l*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,o(i);a(c/l),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===l){const l=n[0];if(l===qt){const e=n[1],t=n[2],l=B.worldDimToViewport({w:e,h:t});Ao=!0,B.move(l.w,l.h)}else if(l===Xt){if(ue&&!Xl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(l===nn)le(n[1]);else if(l===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(l===Zt)ue=null,ne(!1);else if(l===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(l===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else l===on?a.togglePreview():l===an?a.toggleSoundsEnabled():l===cn?a.togglePlayerNames():l===un&&U();const o=C();Xl.handleInput(e,t,n,o,(e=>{H()&&q()})).length>0&&(Ao=!0),Sn.sendClientEvent(n)}else if("replay"===l){const e=n[0];if(e===sn)ie();else if(e===dn)se();else if(e===rn)ae();else if(e===qt){const e=n[1],t=n[2];Ao=!0,B.move(e,t)}else if(e===Xt){if(ue){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(e===nn)le(n[1]);else if(e===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(e===Zt)ue=null,ne(!1);else if(e===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(e===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else e===on?a.togglePreview():e===an?a.toggleSoundsEnabled():e===cn?a.togglePlayerNames():e===un&&U()}j=!!Xl.getFinishTs(e),W()&&(_.update(),Ao=!0)},render:async()=>{if(!Ao)return;const n=C();let o,s,i;window.DEBUG&&sl(0),O.fillStyle=Q(),O.fillRect(0,0,v.width,v.height),window.DEBUG&&il("clear done"),o=B.worldToViewportRaw(I),s=B.worldDimToViewportRaw(M),O.fillStyle="rgba(255, 255, 255, .3)",O.fillRect(o.x,o.y,s.w,s.h),window.DEBUG&&il("board done");const r=Xl.getPiecesSortedByZIndex(e);window.DEBUG&&il("get tiles done"),s=B.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?ko:Po)&&(i=D[e.idx],o=B.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),O.drawImage(i,0,0,i.width,i.height,o.x,o.y,s.w,s.h));window.DEBUG&&il("tiles done");const d=[];for(const a of Xl.getActivePlayers(e,n))c=a,("replay"===l||c.id!==t)&&(i=await f(a),o=B.worldToViewport(a),O.drawImage(i,o.x-g,o.y-m),Y()&&d.push([`${a.name} (${a.points})`,o.x,o.y+h]));var c;O.fillStyle="white",O.textAlign="center";for(const[e,t,l]of d)O.fillText(e,t,l);window.DEBUG&&il("players done"),a.setActivePlayers(Xl.getActivePlayers(e,n)),a.setIdlePlayers(Xl.getIdlePlayers(e,n)),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),window.DEBUG&&il("HUD done"),W()&&_.render(),Ao=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{wo(ro,e),R.addEvent([tn,e])},onColorChange:e=>{wo(co,e),R.addEvent([nn,e])},onNameChange:e=>{wo(uo,e),R.addEvent([ln,e])},onSoundsEnabledChange:e=>{fo(io,e)},onSoundsVolumeChange:e=>{mo(so,e),q()},onShowPlayerNamesChange:e=>{fo(po,e)},replayOnSpeedUp:ae,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:$,player:{background:Q(),color:Z(),name:"replay"===l?bo(uo,"anon"):Xl.getPlayerName(e,t)||bo(uo,"anon"),soundsEnabled:H(),soundsVolume:K(),showPlayerNames:Y()},game:Xl.get(e),disconnect:Sn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var zo=e({name:"game",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,ConnectionOverlay:zn,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const To={id:"game"},Io={key:1,class:"overlay"},Mo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Eo={class:"menu"},Do={class:"tabs"},No=i("🧩 Puzzles");zo.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",To,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Io,[Mo])):o("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Eo,[n("div",Do,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[No])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))}," Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var _o=e({name:"replay",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Vo={id:"replay"},Oo={key:1,class:"overlay"},Bo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Uo={class:"menu"},Ro={class:"tabs"},$o=i("🧩 Puzzles");_o.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Vo,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Oo,[Bo])):o("",!0),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:l((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Uo,[n("div",Ro,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[$o])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))}," Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=await fetch("/api/conf"),t=await e.json();const n=k({history:P(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:it},{name:"game",path:"/g/:id",component:zo},{name:"replay",path:"/replay/:id",component:_o}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const l=A(S);l.config.globalProperties.$config=t,l.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=X.uniqId(),localStorage.setItem("ID",e)),e}(),l.use(n),l.mount("#app")})();