diff --git a/build/public/assets/index.7efa4c6c.js b/build/public/assets/index.7efa4c6c.js deleted file mode 100644 index 375a85b..0000000 --- a/build/public/assets/index.7efa4c6c.js +++ /dev/null @@ -1 +0,0 @@ -import{d as e,c as t,a as n,w as o,b as l,r as a,o as i,e as s,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 x,s as C,u as k,x as A,y as S}from"./vendor.684f7bc8.js";var z=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const T={id:"app"},P={key:0,class:"nav"},I=s("Index"),D=s("New game");z.render=function(e,s,r,d,c,u){const p=a("router-link"),g=a("router-view");return i(),t("div",T,[e.showNav?(i(),t("ul",P,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:o((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:o((()=>[D])),_:1})])])):l("",!0),n(g)])};const E=864e5,_=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const o=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${o}m ${Math.floor(e/1e3)}s`};var M=1e3,O=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},N=(e,t)=>_(t-e),B=_,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?"🏁":"⏳",o=e,l=t||O();return`${n} ${N(o,l)}`}}});const R={class:"game-info-text"},V=n("br",null,null,-1),$=n("br",null,null,-1),G=n("br",null,null,-1),F=s(" β†ͺ️ Watch replay ");U.render=function(e,d,c,u,p,g){const h=a("router-link");return i(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",R,[s(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),V,s(" πŸ‘₯ "+r(e.game.players),1),$,s(" "+r(e.time(e.game.started,e.game.finished)),1),G])])),_:1},8,["to"]),e.game.hasReplay?(i(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[F])),_:1},8,["to"])):l("",!0)],4)};var L=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 j=n("h1",null,"Running games",-1),W=n("h1",null,"Finished games",-1);L.render=function(e,o,l,s,r,u){const p=a("game-teaser");return i(),t("div",null,[j,(i(!0),t(d,null,c(e.gamesRunning,((e,o)=>(i(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),W,(i(!0),t(d,null,c(e.gamesFinished,((e,o)=>(i(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var q=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")}}});q.render=function(e,o,l,a,s,r){return i(),t("div",{class:"imageteaser",style:e.style,onClick:o[2]||(o[2]=(...t)=>e.onClick&&e.onClick(...t))},[n("div",{class:"btn edit",onClick:o[1]||(o[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var H,Y,Q,Z,K,X,J,ee,te=e({name:"image-library",components:{ImageTeaser:q},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});te.render=function(e,n,o,l,s,r){const u=a("image-teaser");return i(),t("div",null,[(i(!0),t(d,null,c(e.images,((n,o)=>(i(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])},(Y=H||(H={}))[Y.Flat=0]="Flat",Y[Y.Out=1]="Out",Y[Y.In=-1]="In",(Z=Q||(Q={}))[Z.FINAL=0]="FINAL",Z[Z.ANY=1]="ANY",(X=K||(K={}))[X.NORMAL=0]="NORMAL",X[X.ANY=1]="ANY",X[X.FLAT=2]="FLAT",(ee=J||(J={}))[ee.NORMAL=0]="NORMAL",ee[ee.REAL=1]="REAL";class ne{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),o=t[n];t[n]=t[e],t[e]=o}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new ne(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const oe=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},le=(...e)=>{const t=t=>(...n)=>{const o=new Date,l=oe(o.getHours(),"00"),a=oe(o.getMinutes(),"00"),i=oe(o.getSeconds(),"00");console[t](`${l}:${a}:${i}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var ae={hash:e=>{let t=0;for(let n=0;n{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||"",ne.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode||Q.FINAL,e.shapeMode||K.ANY,e.snapMode||J.NORMAL]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:ne.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 o=[n,e[n]].map(encodeURIComponent);t.push(o.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const ie={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}}}};ie.render=function(e,n,o,l,a,s){return i(),t("div",{style:s.style,title:o.title},null,12,["title"])};var se=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.key&&this.autocomplete.values.length>0?(this.autocomplete.idx0?(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 re=m();y("data-v-39ed99c7");const de={key:0,class:"autocomplete"};f();const ce=re(((e,o,a,s,u,m)=>(i(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.input=t),placeholder:"Plants, People",onChange:o[2]||(o[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:o[3]||(o[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:o[4]||(o[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(i(),t("div",de,[n("ul",null,[(i(!0),t(d,null,c(e.autocomplete.values,((n,o)=>(i(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(i(!0),t(d,null,c(e.values,((n,o)=>(i(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" βœ–",9,["onClick"])))),128))]))));se.render=ce,se.__scopeId="data-v-39ed99c7";const ue=le("NewImageDialog.vue");var pe=e({name:"new-image-dialog",components:{ResponsiveImage:ie,TagsInput:se},props:{autocompleteTags:{type:Function}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{canPostToGallery(){return!(!this.previewUrl||!this.file)},canSetupGameClick(){return!(!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 o=n[0];return o.type.startsWith("image/")?o: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(){ue.info("onDragleave"),this.droppable=!1}}});const ge={key:0,class:"has-image"},he={key:1},me={class:"upload"},ye=n("span",{class:"btn"},"Upload File",-1),fe={class:"area-settings"},ve=n("td",null,[n("label",null,"Title")],-1),we=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),be=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},Ce=s("🧩 Post to gallery "),ke=n("br",null,null,-1),Ae=s(" + set up game");pe.render=function(e,o,l,s,r,d){const c=a("responsive-image"),h=a("tags-input");return i(),t("div",{class:"overlay new-image-dialog",onClick:o[11]||(o[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[10]||(o[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:o[3]||(o[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:o[4]||(o[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:o[5]||(o[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[e.previewUrl?(i(),t("div",ge,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(c,{src:e.previewUrl},null,8,["src"])])):(i(),t("div",he,[n("label",me,[n("input",{type:"file",style:{display:"none"},onChange:o[2]||(o[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ye])]))],34),n("div",fe,[n("table",null,[n("tr",null,[ve,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[6]||(o[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),we,n("tr",null,[be,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[7]||(o[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",xe,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:o[8]||(o[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},"πŸ–ΌοΈ Post to gallery",8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},[Ce,ke,Ae],8,["disabled"])])])])};var Se=e({name:"edit-image-dialog",components:{ResponsiveImage:ie,TagsInput:se},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 ze={class:"area-image"},Te={class:"has-image"},Pe={class:"area-settings"},Ie=n("td",null,[n("label",null,"Title")],-1),De=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),Ee=n("td",null,[n("label",null,"Tags")],-1),_e={class:"area-buttons"};Se.render=function(e,o,l,s,r,d){const c=a("responsive-image"),h=a("tags-input");return i(),t("div",{class:"overlay edit-image-dialog",onClick:o[5]||(o[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[4]||(o[4]=u((()=>{}),["stop"]))},[n("div",ze,[n("div",Te,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Pe,[n("table",null,[n("tr",null,[Ie,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),De,n("tr",null,[Ee,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[2]||(o[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",_e,[n("button",{class:"btn",onClick:o[3]||(o[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"πŸ–ΌοΈ Save image")])])])};var Me=e({name:"new-game-dialog",components:{ResponsiveImage:ie},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Q.ANY,shapeMode:K.NORMAL,snapMode:J.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 Oe={class:"area-image"},Ne={class:"has-image"},Be={key:0,class:"image-title"},Ue={class:"area-settings"},Re=n("td",null,[n("label",null,"Pieces")],-1),Ve=n("td",null,[n("label",null,"Scoring: ")],-1),$e=s(" Any (Score when pieces are connected to each other or on final location)"),Ge=n("br",null,null,-1),Fe=s(" Final (Score when pieces are put to their final location)"),Le=n("td",null,[n("label",null,"Shapes: ")],-1),je=s(" Normal"),We=n("br",null,null,-1),qe=s(" Any (flat pieces can occur anywhere)"),He=n("br",null,null,-1),Ye=s(" Flat (all pieces flat on all sides)"),Qe=n("td",null,[n("label",null,"Snapping: ")],-1),Ze=s(" Normal (pieces snap to final destination and to each other)"),Ke=n("br",null,null,-1),Xe=s(" Real (pieces snap only to corners, already snapped pieces and to each other)"),Je={class:"area-buttons"};Me.render=function(e,o,s,d,c,h){const m=a("responsive-image");return i(),t("div",{class:"overlay new-game-dialog",onClick:o[11]||(o[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[10]||(o[10]=u((()=>{}),["stop"]))},[n("div",Oe,[n("div",Ne,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title?(i(),t("div",Be,'"'+r(e.image.title)+'"',1)):l("",!0)]),n("div",Ue,[n("table",null,[n("tr",null,[Re,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[Ve,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[2]||(o[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),$e]),Ge,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[3]||(o[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),Fe])])]),n("tr",null,[Le,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[4]||(o[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),je]),We,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[5]||(o[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),qe]),He,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[6]||(o[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),Ye])])]),n("tr",null,[Qe,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[7]||(o[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),Ze]),Ke,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[8]||(o[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),Xe])])])])]),n("div",Je,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var et=e({components:{ImageLibrary:te,NewImageDialog:pe,EditImageDialog:Se,NewGameDialog:Me},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:""}),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${ae.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){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 fetch("/api/upload",{method:"post",body:t});return 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){await this.uploadImage(e),this.dialog="",await this.loadImages()},async setupGameClick(e){const t=await this.uploadImage(e);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 tt={class:"upload-image-teaser"},nt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ot={key:0},lt=s(" Tags: "),at=s(" Sort by: "),it=n("option",{value:"date_desc"},"Newest first",-1),st=n("option",{value:"date_asc"},"Oldest first",-1),rt=n("option",{value:"alpha_asc"},"A-Z",-1),dt=n("option",{value:"alpha_desc"},"Z-A",-1);et.render=function(e,o,s,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return i(),t("div",null,[n("div",tt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),nt]),n("div",null,[e.tags.length>0?(i(),t("label",ot,[lt,(i(!0),t(d,null,c(e.relevantTags,((n,o)=>(i(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:o,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):l("",!0),n("label",null,[at,p(n("select",{"onUpdate:modelValue":o[2]||(o[2]=t=>e.filters.sort=t),onChange:o[3]||(o[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[it,st,rt,dt],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?(i(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(i(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:o[5]||(o[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):l("",!0),e.image&&"new-game"===e.dialog?(i(),t(v,{key:2,onBgclick:o[6]||(o[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):l("",!0)])};var ct=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 ut={class:"scores"},pt=n("div",null,"Scores",-1),gt=n("td",null,"⚑",-1),ht=n("td",null,"πŸ’€",-1);ct.render=function(e,o,l,a,s,u){return i(),t("div",ut,[pt,n("table",null,[(i(!0),t(d,null,c(e.actives,((e,o)=>(i(),t("tr",{key:o,style:{color:e.color}},[gt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(i(!0),t(d,null,c(e.idles,((e,o)=>(i(),t("tr",{key:o,style:{color:e.color}},[ht,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var mt=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 yt={class:"timer"};mt.render=function(e,o,l,a,s,d){return i(),t("div",yt,[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 ft=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:Object},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const vt=n("td",null,[n("label",null,"Background: ")],-1),wt=n("td",null,[n("label",null,"Color: ")],-1),bt=n("td",null,[n("label",null,"Name: ")],-1),xt=n("td",null,[n("label",null,"Sounds: ")],-1);ft.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay transparent",onClick:o[6]||(o[6]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[5]||(o[5]=u((()=>{}),["stop"]))},[n("tr",null,[vt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":o[1]||(o[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[wt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":o[2]||(o[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[bt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":o[3]||(o[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[xt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[x,e.modelValue.soundsEnabled]])])])])])};var Ct=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const kt={class:"preview"};Ct.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",kt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var At=1,St=4,zt=2,Tt=3,Pt=2,It=4,Dt=3,Et=9,_t=1,Mt=2,Ot=3,Nt=4,Bt=5,Ut=6,Rt=7,Vt=8,$t=10,Gt=11,Ft=1,Lt=2,jt=3;const Wt=le("Communication.js");let qt,Ht=[],Yt=e=>{Ht.push(e)},Qt=[],Zt=e=>{Qt.push(e)};let Kt=0;const Xt=e=>{Kt!==e&&(Kt=e,Zt(e))};function Jt(e){if(2===Kt)try{qt.send(JSON.stringify(e))}catch(t){Wt.info("unable to send message.. maybe because ws is invalid?")}}let en,tn;var nn={connect:function(e,t,n){return en=0,tn={},Xt(3),new Promise((o=>{qt=new WebSocket(e,n+"|"+t),qt.onopen=()=>{Xt(2),Jt([Tt])},qt.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===St){const e=t[1];o(e)}else{if(l!==At)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&tn[o])return void delete tn[o];Yt(t)}}},qt.onerror=()=>{throw Xt(1),"[ 2021-05-15 onerror ]"},qt.onclose=e=>{4e3===e.code||1001===e.code?Xt(4):Xt(1)}}))},requestReplayData:async function(e,t,n){const o={gameId:e,offset:t,size:n},l=await fetch(`/api/replay-data${ae.asQueryArgs(o)}`);return await l.json()},disconnect:function(){qt&&qt.close(4e3),en=0,tn={}},sendClientEvent:function(e){en++,tn[en]=e,Jt([zt,en,tn[en]])},onServerChange:function(e){Yt=e;for(const t of Ht)Yt(t);Ht=[]},onConnectionStateChange:function(e){Zt=e;for(const t of Qt)Zt(t);Qt=[]},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},on=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===nn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===nn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const ln={key:0,class:"overlay connection-lost"},an={key:0,class:"overlay-content"},sn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),rn={key:1,class:"overlay-content"},dn=n("div",null,"Connecting...",-1);on.render=function(e,o,a,s,r,d){return e.show?(i(),t("div",ln,[e.lostConnection?(i(),t("div",an,[sn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(i(),t("div",rn,[dn])):l("",!0)])):l("",!0)};var cn=e({name:"help-overlay",emits:{bgclick:null}});const un=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),s("/"),n("kbd",null,"↑"),s("/πŸ–±οΈ")])])],-1),pn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),s("/"),n("kbd",null,"↓"),s("/πŸ–±οΈ")])])],-1),gn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),s("/"),n("kbd",null,"←"),s("/πŸ–±οΈ")])])],-1),hn=n("tr",null,[n("td",null,"➑️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),s("/"),n("kbd",null,"β†’"),s("/πŸ–±οΈ")])])],-1),mn=n("tr",null,[n("td"),n("td",null,[n("div",null,[s("Move faster by holding "),n("kbd",null,"Shift")])])],-1),yn=n("tr",null,[n("td",null,"πŸ”+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),s("/πŸ–±οΈ-Wheel")])])],-1),fn=n("tr",null,[n("td",null,"πŸ”- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),s("/πŸ–±οΈ-Wheel")])])],-1),vn=n("tr",null,[n("td",null,"πŸ–ΌοΈ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),wn=n("tr",null,[n("td",null,"πŸ§©βœ”οΈ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),bn=n("tr",null,[n("td",null,"πŸ§©β“ Toggle loose pieces:"),n("td",null,[n("div",null,[n("kbd",null,"G")])])],-1),xn=n("tr",null,[n("td",null,"πŸ”‰ Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1);cn.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay transparent",onClick:o[2]||(o[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:o[1]||(o[1]=u((()=>{}),["stop"]))},[un,pn,gn,hn,mn,yn,fn,vn,wn,bn,xn])])};var Cn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),kn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),An=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Sn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),zn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function Tn(){let e=0,t=0,n=1;const o=(o,l)=>{e+=o/n,t+=l/n},l=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),s=e=>({w:e.w*n,h:e.h*n}),r=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>((e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0})(l(e),t),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}=s(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:s,viewportToWorld:e=>{const{x:t,y:n}=a(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:a,viewportDimToWorld:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:r}}function Pn(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var In={createCanvas:Pn,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 o=Pn(t,n);return o.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(o)},colorizedCanvas:function(e,t,n){const o=Pn(e.width,e.height),l=o.getContext("2d");return l.save(),l.drawImage(t,0,0),l.fillStyle=n,l.globalCompositeOperation="source-in",l.fillRect(0,0,t.width,t.height),l.restore(),l.save(),l.globalCompositeOperation="destination-over",l.drawImage(e,0,0),l.restore(),o}};const Dn=le("Debug.js");let En=0,_n=0;var Mn=e=>{En=performance.now(),_n=e},On=e=>{const t=performance.now(),n=t-En;n>_n&&Dn.log(e+": "+n),En=t};function Nn(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function Bn(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var Un={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:Nn,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:Bn,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 Nn(Bn(e),Bn(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 Rn=le("PuzzleGraphics.js");function Vn(e,t){const n=ae.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var $n={loadPuzzleBitmaps:async function(e){const t=await In.loadImageToBitmap(e.info.imageUrl),n=await In.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){Rn.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,i=o/100,s=[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:l,y:l},r=Un.pointAdd(a,{x:o,y:0}),c=Un.pointAdd(r,{x:0,y:o}),u=Un.pointSub(c,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oae.decodePiece(Gn[e].puzzle.tiles[t]),to=(e,t)=>eo(e,t).group,no=(e,t)=>{const n=Gn[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},oo=(e,t)=>{const n=Gn[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=Gn[e].puzzle.info,o=ae.coordByPieceIdx(n,t),l=o.x*n.tileSize,a=o.y*n.tileSize;return{x:l,y:a}}(e,t);return Un.pointAdd(o,l)},lo=(e,t)=>eo(e,t).pos,ao=e=>{const t=ko(e),n=Ao(e),o=Math.round(t/4),l=Math.round(n/4);return{x:0-o,y:0-l,w:t+2*o,h:n+2*l}},io=(e,t)=>{const n=uo(e),o=eo(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},so=(e,t)=>eo(e,t).z,ro=(e,t)=>{for(const n of Gn[e].puzzle.tiles){const e=ae.decodePiece(n);if(e.owner===t)return e.idx}return-1},co=e=>Gn[e].puzzle.info.tileDrawSize,uo=e=>Gn[e].puzzle.info.tileSize,po=e=>Gn[e].puzzle.data.maxGroup,go=e=>Gn[e].puzzle.data.maxZ;function ho(e,t){const n=Gn[e].puzzle.info,o=ae.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const mo=(e,t,n)=>{for(const o of t)Jn(e,o,{z:n})},yo=(e,t,n)=>{const o=lo(e,t);Jn(e,t,{pos:Un.pointAdd(o,n)})},fo=(e,t,n)=>{const o=co(e),l=ao(e),a=n;for(const i of t){const t=eo(e,i);t.pos.x+n.xl.x+l.w&&(a.x=Math.min(l.x+l.w-t.pos.x+o,a.x)),t.pos.y+n.yl.y+l.h&&(a.y=Math.min(l.y+l.h-t.pos.y+o,a.y))}for(const i of t)yo(e,i,a)},vo=(e,t)=>eo(e,t).owner,wo=(e,t)=>{for(const n of t)Jn(e,n,{owner:-1,z:1})},bo=(e,t,n)=>{for(const o of t)Jn(e,o,{owner:n})};function xo(e,t){const n=Gn[e].puzzle.tiles,o=ae.decodePiece(n[t]),l=[];if(o.group)for(const a of n){const e=ae.decodePiece(a);e.group===o.group&&l.push(e.idx)}else l.push(o.idx);return l}const Co=(e,t)=>{const n=Ln(e,t);return n?n.points:0},ko=e=>Gn[e].puzzle.info.table.width,Ao=e=>Gn[e].puzzle.info.table.height;var So={setGame:function(e,t){Gn[e]=t},exists:function(e){return!!Gn[e]||!1},playerExists:Wn,getActivePlayers:function(e,t){const n=t-30*M;return qn(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*M;return qn(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){Wn(e,t)?Kn(e,t,{ts:n}):jn(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:Zn,getPieceCount:Hn,getImageUrl:function(e){return Gn[e].puzzle.info.imageUrl},setImageUrl:function(e,t){Gn[e].puzzle.info.imageUrl=t},get:function(e){return Gn[e]||null},getAllGames:function(){return Object.values(Gn).sort(((e,t)=>Qn(e.id)===Qn(t.id)?t.puzzle.data.started-e.puzzle.data.started:Qn(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=Ln(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=Ln(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=Ln(e,t);return n?n.name:null},getPlayerIndexById:Fn,getPlayerIdByIndex:function(e,t){return Gn[e].players.length>t?ae.decodePlayer(Gn[e].players[t]).id:null},changePlayer:Kn,setPlayer:jn,setPiece:function(e,t,n){Gn[e].puzzle.tiles[t]=ae.encodePiece(n)},setPuzzleData:function(e,t){Gn[e].puzzle.data=t},getTableWidth:ko,getTableHeight:Ao,getPuzzle:e=>Gn[e].puzzle,getRng:e=>Gn[e].rng.obj,getPuzzleWidth:e=>Gn[e].puzzle.info.width,getPuzzleHeight:e=>Gn[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return Gn[e].puzzle.tiles.map(ae.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=ro(e,t);return n<0?null:Gn[e].puzzle.tiles[n]},getPieceDrawOffset:e=>Gn[e].puzzle.info.tileDrawOffset,getPieceDrawSize:co,getFinalPiecePos:oo,getStartTs:e=>Gn[e].puzzle.data.started,getFinishTs:e=>Gn[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=Gn[e].puzzle,i=function(e,t){return t in Gn[e].evtInfos?Gn[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),s=[],r=()=>{s.push([Ft,a.data])},d=t=>{s.push([Lt,ae.encodePiece(eo(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=Ln(e,t);n&&s.push([jt,ae.encodePlayer(n)])},p=n[0];if(p===Ut){const l=n[1];Kn(e,t,{bgcolor:l,ts:o}),u()}else if(p===Rt){const l=n[1];Kn(e,t,{color:l,ts:o}),u()}else if(p===Vt){const l=`${n[1]}`.substr(0,16);Kn(e,t,{name:l,ts:o}),u()}else if(p===Et){const l=n[1],a=n[2],i=Ln(e,t);if(i){const n=i.x-l,s=i.y-a;Kn(e,t,{ts:o,x:n,y:s}),u()}}else if(p===_t){const l={x:n[1],y:n[2]};Kn(e,t,{d:1,ts:o}),u(),i._last_mouse_down=l;const a=((e,t)=>{const n=Gn[e].puzzle.info,o=Gn[e].puzzle.tiles;let l=-1,a=-1;for(let i=0;il)&&(l=e.z,a=i)}return a})(e,l);if(a>=0){const n=go(e)+1;Xn(e,{maxZ:n}),r();const o=xo(e,a);mo(e,o,go(e)),bo(e,o,t),c(o)}i._last_mouse=l}else if(p===Ot){const l=n[1],a=n[2],s={x:l,y:a};if(null===i._last_mouse_down)Kn(e,t,{x:l,y:a,ts:o}),u();else{const n=ro(e,t);if(n>=0){Kn(e,t,{x:l,y:a,ts:o}),u();const r=xo(e,n);let d=Un.pointInBounds(s,ao(e))&&Un.pointInBounds(i._last_mouse_down,ao(e));for(const t of r){const n=io(e,t);if(Un.pointInBounds(s,n)){d=!0;break}}if(d){const t=l-i._last_mouse_down.x,n=a-i._last_mouse_down.y;fo(e,r,{x:t,y:n}),c(r)}}else Kn(e,t,{ts:o}),u();i._last_mouse_down=s}i._last_mouse=s}else if(p===Mt){const s={x:n[1],y:n[2]},p=0;i._last_mouse_down=null;const g=ro(e,t);if(g>=0){const n=xo(e,g);bo(e,n,0),c(n);const i=lo(e,g),s=oo(e,g);let h=!1;if(function(e){return Gn[e].snapMode||J.NORMAL}(e)===J.REAL){for(const t of n)if(no(e,t)){h=!0;break}}else h=!0;if(h&&Un.pointDistance(s,i){const l=Gn[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=to(e,t),l=to(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=lo(e,t),i=Un.pointAdd(lo(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(Un.pointDistance(a,i){const o=Gn[e].puzzle.tiles,l=to(e,t),a=to(e,n);let i;const s=[];l&&s.push(l),a&&s.push(a),l?i=l:a?i=a:(Xn(e,{maxGroup:po(e)+1}),r(),i=po(e));if(Jn(e,t,{group:i}),d(t),Jn(e,n,{group:i}),d(n),s.length>0)for(const r of o){const t=ae.decodePiece(r);s.includes(t.group)&&(Jn(e,t.idx,{group:i}),d(t.idx))}})(e,t,n),l=xo(e,t),((e,t)=>-1===vo(e,t))(e,n))wo(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=so(e,o);t>n&&(n=t)}return n})(e,l);mo(e,l,t)}return c(l),!0}return!1};let a=!1;for(const t of xo(e,g)){const o=ho(e,t);if(n(e,t,o[0],[0,1])||n(e,t,o[1],[-1,0])||n(e,t,o[2],[0,-1])||n(e,t,o[3],[1,0])){a=!0;break}}if(a&&Yn(e)===Q.ANY){const n=Co(e,t)+1;Kn(e,t,{d:p,ts:o,points:n}),u()}else Kn(e,t,{d:p,ts:o}),u();a&&l&&l(t)}}else Kn(e,t,{d:p,ts:o}),u();i._last_mouse=s}else if(p===Nt){const l=n[1],a=n[2];Kn(e,t,{x:l,y:a,ts:o}),u(),i._last_mouse={x:l,y:a}}else if(p===Bt){const l=n[1],a=n[2];Kn(e,t,{x:l,y:a,ts:o}),u(),i._last_mouse={x:l,y:a}}else Kn(e,t,{ts:o}),u();return function(e,t,n){Gn[e].evtInfos[t]=n}(e,t,i),s}};let zo=-10,To=20,Po=2,Io=15;class Do{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=zo+Math.random()*To,this.vy=-1*(Po+Math.random()*Io),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{this.resize()}))}setSpeedParams(){let e=0,t=0;for(;e=0;)t+=1,e+=t;Po=t/2,Io=t-Po;const n=1/4*this.canvas.width/(t/2);zo=-n,To=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new Do(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new Do(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{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?c:u;y[t]=await createImageBitmap(In.colorizedCanvas(n,o,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,Uo=!0})),t}(l,In.createCanvas()),w={final:!1,requesting:!0,log:[],logPointer:0,speeds:[.5,1,2,5,10,20,50,100,250,500],speedIdx:1,paused:!1,lastRealTs:0,lastGameTs:0,gameStartTs:0,dataOffset:0,dataSize:1e4};nn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{w.requesting=!0;const t=await nn.requestReplayData(e,w.dataOffset,w.dataSize);return w.dataOffset+=w.dataSize,w.requesting=!1,t};let x=()=>0;const C=async()=>{if("play"===o){const o=await nn.connect(n,e,t),l=ae.decodeGame(o);So.setGame(l.id,l),x=()=>O()}else{if("replay"!==o)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=ae.decodeGame(t.game);So.setGame(n.id,n),w.requesting=!1,w.log=t.log,w.lastRealTs=O(),w.gameStartTs=parseInt(w.log[0][4],10),w.lastGameTs=w.gameStartTs,w.final=!1,w.logPointer=0,w.speeds=[.5,1,2,5,10,20,50,100,250,500],w.speedIdx=1,w.paused=!1,w.dataOffset=0,w.dataSize=1e4,x=()=>w.lastGameTs}}Uo=!0};await C();const k=So.getPieceDrawOffset(e),A=So.getPieceDrawSize(e),S=So.getPuzzleWidth(e),z=So.getPuzzleHeight(e),T=So.getTableWidth(e),P=So.getTableHeight(e),I={x:(T-S)/2,y:(P-z)/2},D={w:S,h:z},E={w:A,h:A},_=await $n.loadPuzzleBitmaps(So.getPuzzle(e)),M=new _o(v,So.getRng(e));M.init();const N=v.getContext("2d");v.classList.add("loaded");const B=Tn();B.move(-(T-v.width)/2,-(P-v.height)/2);const U=function(e,t,n){let o=[],l=!0,a=!1,i=!1,s=!1,r=!1,d=!1,c=!1,u=!1;const p=(e,t)=>{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},g=e=>p(e.offsetX,e.offsetY),h=()=>p(e.width/2,e.height/2),m=(e,t)=>{l&&("Shift"===t.key?u=e:"ArrowUp"===t.key||"w"===t.key||"W"===t.key?s=e:"ArrowDown"===t.key||"s"===t.key||"S"===t.key?r=e:"ArrowLeft"===t.key||"a"===t.key||"A"===t.key?a=e:"ArrowRight"===t.key||"d"===t.key||"D"===t.key?i=e:"q"===t.key?c=e:"e"===t.key&&(d=e))};let y=null;e.addEventListener("mousedown",(e=>{y=g(e),0===e.button&&f([_t,...y])})),e.addEventListener("mouseup",(e=>{y=g(e),0===e.button&&f([Mt,...y])})),e.addEventListener("mousemove",(e=>{y=g(e),f([Ot,...y])})),e.addEventListener("wheel",(e=>{if(y=g(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Nt:Bt;f([t,...y])}})),t.addEventListener("keydown",(e=>m(!0,e))),t.addEventListener("keyup",(e=>m(!1,e))),t.addEventListener("keypress",(e=>{l&&(" "===e.key&&f([$t]),"F"!==e.key&&"f"!==e.key||(No=!No,Uo=!0),"G"!==e.key&&"g"!==e.key||(Bo=!Bo,Uo=!0),"M"!==e.key&&"m"!==e.key||f([Gt]))}));const f=e=>{o.push(e)};return{addEvent:f,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(a?1:0)-(i?1:0),t=(s?1:0)-(r?1:0);if(0!==e||0!==t){const o=(u?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});f([Et,l.w,l.h]),y&&(y[0]-=l.w,y[1]-=l.h)}if(d&&c);else if(d){if(n.canZoom("in")){const e=y||h();f([Nt,...e])}}else if(c&&n.canZoom("out")){const e=y||h();f([Bt,...e])}},setHotkeys:e=>{l=e}}}(v,window,B),R=So.getImageUrl(e),V=()=>{const t=So.getStartTs(e),n=So.getFinishTs(e),o=x();a.setFinished(!!n),a.setDuration((n||o)-t)};V(),a.setPiecesDone(So.getFinishedPiecesCount(e)),a.setPiecesTotal(So.getPieceCount(e));const $=x();a.setActivePlayers(So.getActivePlayers(e,$)),a.setIdlePlayers(So.getIdlePlayers(e,$));const G=!!So.getFinishTs(e);let F=G;const L=()=>F&&!G,j=()=>{const e=localStorage.getItem("sound_enabled");return null!==e&&"1"===e},W=()=>So.getPlayerBgColor(e,t)||localStorage.getItem("bg_color")||"#222222",q=()=>So.getPlayerColor(e,t)||localStorage.getItem("player_color")||"#ffffff";let H="",Y="",Q=!1;const Z=e=>{Q=e;const[t,n]=e?[H,"grab"]:[Y,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},K=e=>{H=In.colorizedCanvas(r,c,e).toDataURL(),Y=In.colorizedCanvas(d,u,e).toDataURL(),Z(Q)};K(q());const X=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},J=[],ee=()=>{J.forEach((e=>{clearInterval(e)}))};let te;"play"===o?J.push(setInterval((()=>{V()}),1e3)):"replay"===o&&X(),"play"===o?nn.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case jt:{const n=ae.decodePlayer(a);n.id!==t&&(So.setPlayer(e,n.id,n),Uo=!0)}break;case Lt:{const t=ae.decodePiece(a);So.setPiece(e,t.idx,t),Uo=!0}break;case Ft:So.setPuzzleData(e,a),Uo=!0}F=!!So.getFinishTs(e)})):"replay"===o&&J.push(setInterval((()=>{const t=O();if(w.requesting)return void(w.lastRealTs=t);if(w.logPointer+1>=w.log.length)return w.lastRealTs=t,void(async e=>{const t=await b(e);w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...t.log),t.log.length=w.log.length){w.final&&ee();break}const n=w.log[t],l=w.gameStartTs+n[n.length-1];if(l>o)break;const a=n.slice();if(a[0]===Pt){const t=a[1];So.addPlayer(e,t,l),Uo=!0}else if(a[0]===It){const t=So.getPlayerIdByIndex(e,a[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";So.addPlayer(e,t,l),Uo=!0}else if(a[0]===Dt){const t=So.getPlayerIdByIndex(e,a[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const n=a[2];So.handleInput(e,t,n,l),Uo=!0}w.logPointer=t}w.lastRealTs=t,w.lastGameTs=o,V()}),50));let ne=null;return te=(e=>{let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,i=window.requestAnimationFrame,s=1/n,r=o*s;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,l(s);a(c/o),u=d,t||i(p)};return i(p),{stop:()=>{t=!0}}})({update:()=>{U.createKeyEvents();for(const n of U.consumeAll())if("play"===o){const o=n[0];if(o===Et){const e=n[1],t=n[2],o=B.worldDimToViewport({w:e,h:t});Uo=!0,B.move(o.w,o.h)}else if(o===Ot){if(ne&&!So.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),o=Math.round(t.x-ne.x),l=Math.round(t.y-ne.y);Uo=!0,B.move(o,l),ne=t}}else if(o===Rt)K(n[1]);else if(o===_t){const e={x:n[1],y:n[2]};ne=B.worldToViewport(e),Z(!0)}else if(o===Mt)ne=null,Z(!1);else if(o===Nt){const e={x:n[1],y:n[2]};Uo=!0,B.zoom("in",B.worldToViewport(e))}else if(o===Bt){const e={x:n[1],y:n[2]};Uo=!0,B.zoom("out",B.worldToViewport(e))}else o===$t?a.togglePreview():o===Gt&&a.toggleSoundsEnabled();const l=x();So.handleInput(e,t,n,l,(e=>{j()&&s.play()})).length>0&&(Uo=!0),nn.sendClientEvent(n)}else if("replay"===o){const e=n[0];if(e===Et){const e=n[1],t=n[2];Uo=!0,B.move(e,t)}else if(e===Ot){if(ne){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),o=Math.round(t.x-ne.x),l=Math.round(t.y-ne.y);Uo=!0,B.move(o,l),ne=t}}else if(e===_t){const e={x:n[1],y:n[2]};ne=B.worldToViewport(e)}else if(e===Mt)ne=null;else if(e===Nt){const e={x:n[1],y:n[2]};Uo=!0,B.zoom("in",B.worldToViewport(e))}else if(e===Bt){const e={x:n[1],y:n[2]};Uo=!0,B.zoom("out",B.worldToViewport(e))}else e===$t&&a.togglePreview()}F=!!So.getFinishTs(e),L()&&(M.update(),Uo=!0)},render:async()=>{if(!Uo)return;const n=x();let l,i,s;window.DEBUG&&Mn(0),N.fillStyle=W(),N.fillRect(0,0,v.width,v.height),window.DEBUG&&On("clear done"),l=B.worldToViewportRaw(I),i=B.worldDimToViewportRaw(D),N.fillStyle="rgba(255, 255, 255, .3)",N.fillRect(l.x,l.y,i.w,i.h),window.DEBUG&&On("board done");const r=So.getPiecesSortedByZIndex(e);window.DEBUG&&On("get tiles done"),i=B.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?No:Bo)&&(s=_[e.idx],l=B.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),N.drawImage(s,0,0,s.width,s.height,l.x,l.y,i.w,i.h));window.DEBUG&&On("tiles done");const d=[];for(const a of So.getActivePlayers(e,n))c=a,("replay"===o||c.id!==t)&&(s=await f(a),l=B.worldToViewport(a),N.drawImage(s,l.x-g,l.y-m),d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var c;N.fillStyle="white",N.textAlign="center";for(const[e,t,o]of d)N.fillText(e,t,o);window.DEBUG&&On("players done"),a.setActivePlayers(So.getActivePlayers(e,n)),a.setIdlePlayers(So.getIdlePlayers(e,n)),a.setPiecesDone(So.getFinishedPiecesCount(e)),window.DEBUG&&On("HUD done"),L()&&M.render(),Uo=!1}}),{setHotkeys:e=>{U.setHotkeys(e)},onBgChange:e=>{localStorage.setItem("bg_color",e),U.addEvent([Ut,e])},onColorChange:e=>{localStorage.setItem("player_color",e),U.addEvent([Rt,e])},onNameChange:e=>{localStorage.setItem("player_name",e),U.addEvent([Vt,e])},onSoundsEnabledChange:e=>{localStorage.setItem("sound_enabled",e?"1":"0")},replayOnSpeedUp:()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,X())},replayOnPauseToggle:()=>{w.paused=!w.paused,X()},previewImageUrl:R,player:{background:W(),color:q(),name:So.getPlayerName(e,t)||localStorage.getItem("player_name")||"anon",soundsEnabled:j()},disconnect:nn.disconnect,connect:C,unload:()=>{ee(),te&&te.stop()}}}var Vo=e({name:"game",components:{PuzzleStatus:mt,Scores:ct,SettingsOverlay:ft,PreviewOverlay:Ct,ConnectionOverlay:on,HelpOverlay:cn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange: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.g=await Ro(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{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},setConnectionState:e=>{this.connectionState=e},togglePreview:()=>{this.toggle("preview",!1)},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled}}))},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 $o={id:"game"},Go={class:"menu"},Fo={class:"tabs"},Lo=s("🧩 Puzzles");Vo.render=function(e,l,s,r,d,c){const u=a("settings-overlay"),g=a("preview-overlay"),h=a("help-overlay"),m=a("connection-overlay"),y=a("puzzle-status"),f=a("router-link"),v=a("scores");return i(),t("div",$o,[p(n(u,{onBgclick:l[1]||(l[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":l[2]||(l[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[C,"settings"===e.overlay]]),p(n(g,{onBgclick:l[3]||(l[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[C,"preview"===e.overlay]]),p(n(h,{onBgclick:l[4]||(l[4]=t=>e.toggle("help",!0))},null,512),[[C,"help"===e.overlay]]),n(m,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(y,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Go,[n("div",Fo,[n(f,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Lo])),_:1}),n("div",{class:"opener",onClick:l[5]||(l[5]=t=>e.toggle("preview",!1))},"πŸ–ΌοΈ Preview"),n("div",{class:"opener",onClick:l[6]||(l[6]=t=>e.toggle("settings",!0))},"πŸ› οΈ Settings"),n("div",{class:"opener",onClick:l[7]||(l[7]=t=>e.toggle("help",!0))},"ℹ️ Help")])]),n(v,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var jo=e({name:"replay",components:{PuzzleStatus:mt,Scores:ct,SettingsOverlay:ft,PreviewOverlay:Ct,HelpOverlay:cn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange: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.g=await Ro(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{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}}))},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 Wo={id:"replay"},qo={class:"menu"},Ho={class:"tabs"},Yo=s("🧩 Puzzles");jo.render=function(e,l,s,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("help-overlay"),y=a("puzzle-status"),f=a("router-link"),v=a("scores");return i(),t("div",Wo,[p(n(g,{onBgclick:l[1]||(l[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":l[2]||(l[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[C,"settings"===e.overlay]]),p(n(h,{onBgclick:l[3]||(l[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[C,"preview"===e.overlay]]),p(n(m,{onBgclick:l[4]||(l[4]=t=>e.toggle("help",!0))},null,512),[[C,"help"===e.overlay]]),n(y,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:o((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:l[5]||(l[5]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:l[6]||(l[6]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:l[7]||(l[7]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",qo,[n("div",Ho,[n(f,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Yo])),_:1}),n("div",{class:"opener",onClick:l[8]||(l[8]=t=>e.toggle("preview",!1))},"πŸ–ΌοΈ Preview"),n("div",{class:"opener",onClick:l[9]||(l[9]=t=>e.toggle("settings",!0))},"πŸ› οΈ Settings"),n("div",{class:"opener",onClick:l[10]||(l[10]=t=>e.toggle("help",!0))},"ℹ️ Help")])]),n(v,{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:A(),routes:[{name:"index",path:"/",component:L},{name:"new-game",path:"/new-game",component:et},{name:"game",path:"/g/:id",component:Vo},{name:"replay",path:"/replay/:id",component:jo}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const o=S(z);o.config.globalProperties.$config=t,o.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=ae.uniqId(),localStorage.setItem("ID",e)),e}(),o.use(n),o.mount("#app")})(); diff --git a/build/public/assets/index.ab1d6e0f.js b/build/public/assets/index.ab1d6e0f.js new file mode 100644 index 0000000..d745c60 --- /dev/null +++ b/build/public/assets/index.ab1d6e0f.js @@ -0,0 +1 @@ +import{d as e,c as t,a as n,w as o,b as l,r as a,o as i,e as s,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 k,s as x,u as C,x as A,y as S}from"./vendor.684f7bc8.js";var T=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const P={id:"app"},z={key:0,class:"nav"},I=s("Index"),D=s("New game");T.render=function(e,s,r,d,c,u){const p=a("router-link"),g=a("router-view");return i(),t("div",P,[e.showNav?(i(),t("ul",z,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:o((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:o((()=>[D])),_:1})])])):l("",!0),n(g)])};const E=864e5,_=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const o=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${o}m ${Math.floor(e/1e3)}s`};var M=1,N=1e3,O=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},B=(e,t)=>_(t-e),U=_,R=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?"🏁":"⏳",o=e,l=t||O();return`${n} ${B(o,l)}`}}});const V={class:"game-info-text"},$=n("br",null,null,-1),G=n("br",null,null,-1),F=n("br",null,null,-1),L=s(" β†ͺ️ Watch replay ");R.render=function(e,d,c,u,p,g){const h=a("router-link");return i(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",V,[s(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),$,s(" πŸ‘₯ "+r(e.game.players),1),G,s(" "+r(e.time(e.game.started,e.game.finished)),1),F])])),_:1},8,["to"]),e.game.hasReplay?(i(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[L])),_:1},8,["to"])):l("",!0)],4)};var j=e({components:{GameTeaser:R},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),H=n("h1",null,"Finished games",-1);j.render=function(e,o,l,s,r,u){const p=a("game-teaser");return i(),t("div",null,[W,(i(!0),t(d,null,c(e.gamesRunning,((e,o)=>(i(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),H,(i(!0),t(d,null,c(e.gamesFinished,((e,o)=>(i(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var Y=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")}}});Y.render=function(e,o,l,a,s,r){return i(),t("div",{class:"imageteaser",style:e.style,onClick:o[2]||(o[2]=(...t)=>e.onClick&&e.onClick(...t))},[n("div",{class:"btn edit",onClick:o[1]||(o[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var Q,q,Z,K,X,J,ee,te,ne=e({name:"image-library",components:{ImageTeaser:Y},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});ne.render=function(e,n,o,l,s,r){const u=a("image-teaser");return i(),t("div",null,[(i(!0),t(d,null,c(e.images,((n,o)=>(i(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])},(q=Q||(Q={}))[q.Flat=0]="Flat",q[q.Out=1]="Out",q[q.In=-1]="In",(K=Z||(Z={}))[K.FINAL=0]="FINAL",K[K.ANY=1]="ANY",(J=X||(X={}))[J.NORMAL=0]="NORMAL",J[J.ANY=1]="ANY",J[J.FLAT=2]="FLAT",(te=ee||(ee={}))[te.NORMAL=0]="NORMAL",te[te.REAL=1]="REAL";class oe{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),o=t[n];t[n]=t[e],t[e]=o}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new oe(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const le=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},ae=(...e)=>{const t=t=>(...n)=>{const o=new Date,l=le(o.getHours(),"00"),a=le(o.getMinutes(),"00"),i=le(o.getSeconds(),"00");console[t](`${l}:${a}:${i}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var ie={hash:e=>{let t=0;for(let n=0;n{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||"",oe.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode||Z.FINAL,e.shapeMode||X.ANY,e.snapMode||ee.NORMAL]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:oe.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 o=[n,e[n]].map(encodeURIComponent);t.push(o.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const se={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}}}};se.render=function(e,n,o,l,a,s){return i(),t("div",{style:s.style,title:o.title},null,12,["title"])};var re=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.key&&this.autocomplete.values.length>0?(this.autocomplete.idx0?(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 de=m();y("data-v-39ed99c7");const ce={key:0,class:"autocomplete"};f();const ue=de(((e,o,a,s,u,m)=>(i(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.input=t),placeholder:"Plants, People",onChange:o[2]||(o[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:o[3]||(o[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:o[4]||(o[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(i(),t("div",ce,[n("ul",null,[(i(!0),t(d,null,c(e.autocomplete.values,((n,o)=>(i(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(i(!0),t(d,null,c(e.values,((n,o)=>(i(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" βœ–",9,["onClick"])))),128))]))));re.render=ue,re.__scopeId="data-v-39ed99c7";const pe=ae("NewImageDialog.vue");var ge=e({name:"new-image-dialog",components:{ResponsiveImage:se,TagsInput:re},props:{autocompleteTags:{type:Function}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{canPostToGallery(){return!(!this.previewUrl||!this.file)},canSetupGameClick(){return!(!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 o=n[0];return o.type.startsWith("image/")?o: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(){pe.info("onDragleave"),this.droppable=!1}}});const he={key:0,class:"has-image"},me={key:1},ye={class:"upload"},fe=n("span",{class:"btn"},"Upload File",-1),ve={class:"area-settings"},we=n("td",null,[n("label",null,"Title")],-1),be=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),ke=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},Ce=s("🧩 Post to gallery "),Ae=n("br",null,null,-1),Se=s(" + set up game");ge.render=function(e,o,l,s,r,d){const c=a("responsive-image"),h=a("tags-input");return i(),t("div",{class:"overlay new-image-dialog",onClick:o[11]||(o[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[10]||(o[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:o[3]||(o[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:o[4]||(o[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:o[5]||(o[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[e.previewUrl?(i(),t("div",he,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(c,{src:e.previewUrl},null,8,["src"])])):(i(),t("div",me,[n("label",ye,[n("input",{type:"file",style:{display:"none"},onChange:o[2]||(o[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),fe])]))],34),n("div",ve,[n("table",null,[n("tr",null,[we,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[6]||(o[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),be,n("tr",null,[ke,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[7]||(o[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",xe,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:o[8]||(o[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},"πŸ–ΌοΈ Post to gallery",8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},[Ce,Ae,Se],8,["disabled"])])])])};var Te=e({name:"edit-image-dialog",components:{ResponsiveImage:se,TagsInput:re},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 Pe={class:"area-image"},ze={class:"has-image"},Ie={class:"area-settings"},De=n("td",null,[n("label",null,"Title")],-1),Ee=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),_e=n("td",null,[n("label",null,"Tags")],-1),Me={class:"area-buttons"};Te.render=function(e,o,l,s,r,d){const c=a("responsive-image"),h=a("tags-input");return i(),t("div",{class:"overlay edit-image-dialog",onClick:o[5]||(o[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[4]||(o[4]=u((()=>{}),["stop"]))},[n("div",Pe,[n("div",ze,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Ie,[n("table",null,[n("tr",null,[De,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ee,n("tr",null,[_e,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[2]||(o[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",Me,[n("button",{class:"btn",onClick:o[3]||(o[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"πŸ–ΌοΈ Save image")])])])};var Ne=e({name:"new-game-dialog",components:{ResponsiveImage:se},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Z.ANY,shapeMode:X.NORMAL,snapMode:ee.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 Oe={class:"area-image"},Be={class:"has-image"},Ue={key:0,class:"image-title"},Re={class:"area-settings"},Ve=n("td",null,[n("label",null,"Pieces")],-1),$e=n("td",null,[n("label",null,"Scoring: ")],-1),Ge=s(" Any (Score when pieces are connected to each other or on final location)"),Fe=n("br",null,null,-1),Le=s(" Final (Score when pieces are put to their final location)"),je=n("td",null,[n("label",null,"Shapes: ")],-1),We=s(" Normal"),He=n("br",null,null,-1),Ye=s(" Any (flat pieces can occur anywhere)"),Qe=n("br",null,null,-1),qe=s(" Flat (all pieces flat on all sides)"),Ze=n("td",null,[n("label",null,"Snapping: ")],-1),Ke=s(" Normal (pieces snap to final destination and to each other)"),Xe=n("br",null,null,-1),Je=s(" Real (pieces snap only to corners, already snapped pieces and to each other)"),et={class:"area-buttons"};Ne.render=function(e,o,s,d,c,h){const m=a("responsive-image");return i(),t("div",{class:"overlay new-game-dialog",onClick:o[11]||(o[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:o[10]||(o[10]=u((()=>{}),["stop"]))},[n("div",Oe,[n("div",Be,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title?(i(),t("div",Ue,'"'+r(e.image.title)+'"',1)):l("",!0)]),n("div",Re,[n("table",null,[n("tr",null,[Ve,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[$e,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[2]||(o[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),Ge]),Fe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[3]||(o[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),Le])])]),n("tr",null,[je,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[4]||(o[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),We]),He,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[5]||(o[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),Ye]),Qe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[6]||(o[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),qe])])]),n("tr",null,[Ze,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[7]||(o[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),Ke]),Xe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[8]||(o[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),Je])])])])]),n("div",et,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var tt=e({components:{ImageLibrary:ne,NewImageDialog:ge,EditImageDialog:Te,NewGameDialog:Ne},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:""}),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${ie.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){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 fetch("/api/upload",{method:"post",body:t});return 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){await this.uploadImage(e),this.dialog="",await this.loadImages()},async setupGameClick(e){const t=await this.uploadImage(e);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 nt={class:"upload-image-teaser"},ot=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),lt={key:0},at=s(" Tags: "),it=s(" Sort by: "),st=n("option",{value:"date_desc"},"Newest first",-1),rt=n("option",{value:"date_asc"},"Oldest first",-1),dt=n("option",{value:"alpha_asc"},"A-Z",-1),ct=n("option",{value:"alpha_desc"},"Z-A",-1);tt.render=function(e,o,s,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return i(),t("div",null,[n("div",nt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),ot]),n("div",null,[e.tags.length>0?(i(),t("label",lt,[at,(i(!0),t(d,null,c(e.relevantTags,((n,o)=>(i(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:o,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):l("",!0),n("label",null,[it,p(n("select",{"onUpdate:modelValue":o[2]||(o[2]=t=>e.filters.sort=t),onChange:o[3]||(o[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[st,rt,dt,ct],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?(i(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(i(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:o[5]||(o[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):l("",!0),e.image&&"new-game"===e.dialog?(i(),t(v,{key:2,onBgclick:o[6]||(o[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):l("",!0)])};var ut=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 pt={class:"scores"},gt=n("div",null,"Scores",-1),ht=n("td",null,"⚑",-1),mt=n("td",null,"πŸ’€",-1);ut.render=function(e,o,l,a,s,u){return i(),t("div",pt,[gt,n("table",null,[(i(!0),t(d,null,c(e.actives,((e,o)=>(i(),t("tr",{key:o,style:{color:e.color}},[ht,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(i(!0),t(d,null,c(e.idles,((e,o)=>(i(),t("tr",{key:o,style:{color:e.color}},[mt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var yt=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 U(this.duration)}}});const ft={class:"timer"};yt.render=function(e,o,l,a,s,d){return i(),t("div",ft,[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 vt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:Object},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const wt=n("td",null,[n("label",null,"Background: ")],-1),bt=n("td",null,[n("label",null,"Color: ")],-1),kt=n("td",null,[n("label",null,"Name: ")],-1),xt=n("td",null,[n("label",null,"Sounds: ")],-1);vt.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay transparent",onClick:o[6]||(o[6]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[5]||(o[5]=u((()=>{}),["stop"]))},[n("tr",null,[wt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":o[1]||(o[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[bt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":o[2]||(o[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[kt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":o[3]||(o[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[xt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[k,e.modelValue.soundsEnabled]])])])])])};var Ct=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const At={class:"preview"};Ct.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",At,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var St=1,Tt=4,Pt=2,zt=3,It=2,Dt=4,Et=3,_t=9,Mt=1,Nt=2,Ot=3,Bt=4,Ut=5,Rt=6,Vt=7,$t=8,Gt=10,Ft=11,Lt=1,jt=2,Wt=3;const Ht=ae("Communication.js");let Yt,Qt=[],qt=e=>{Qt.push(e)},Zt=[],Kt=e=>{Zt.push(e)};let Xt=0;const Jt=e=>{Xt!==e&&(Xt=e,Kt(e))};function en(e){if(2===Xt)try{Yt.send(JSON.stringify(e))}catch(t){Ht.info("unable to send message.. maybe because ws is invalid?")}}let tn,nn;var on={connect:function(e,t,n){return tn=0,nn={},Jt(3),new Promise((o=>{Yt=new WebSocket(e,n+"|"+t),Yt.onopen=()=>{Jt(2),en([zt])},Yt.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===Tt){const e=t[1];o(e)}else{if(l!==St)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&nn[o])return void delete nn[o];qt(t)}}},Yt.onerror=()=>{throw Jt(1),"[ 2021-05-15 onerror ]"},Yt.onclose=e=>{4e3===e.code||1001===e.code?Jt(4):Jt(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},o=await fetch(`/api/replay-data${ie.asQueryArgs(n)}`);return await o.json()},disconnect:function(){Yt&&Yt.close(4e3),tn=0,nn={}},sendClientEvent:function(e){tn++,nn[tn]=e,en([Pt,tn,nn[tn]])},onServerChange:function(e){qt=e;for(const t of Qt)qt(t);Qt=[]},onConnectionStateChange:function(e){Kt=e;for(const t of Zt)Kt(t);Zt=[]},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},ln=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===on.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===on.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const an={key:0,class:"overlay connection-lost"},sn={key:0,class:"overlay-content"},rn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),dn={key:1,class:"overlay-content"},cn=n("div",null,"Connecting...",-1);ln.render=function(e,o,a,s,r,d){return e.show?(i(),t("div",an,[e.lostConnection?(i(),t("div",sn,[rn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(i(),t("div",dn,[cn])):l("",!0)])):l("",!0)};var un=e({name:"help-overlay",emits:{bgclick:null}});const pn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),s("/"),n("kbd",null,"↑"),s("/πŸ–±οΈ")])])],-1),gn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),s("/"),n("kbd",null,"↓"),s("/πŸ–±οΈ")])])],-1),hn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),s("/"),n("kbd",null,"←"),s("/πŸ–±οΈ")])])],-1),mn=n("tr",null,[n("td",null,"➑️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),s("/"),n("kbd",null,"β†’"),s("/πŸ–±οΈ")])])],-1),yn=n("tr",null,[n("td"),n("td",null,[n("div",null,[s("Move faster by holding "),n("kbd",null,"Shift")])])],-1),fn=n("tr",null,[n("td",null,"πŸ”+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),s("/πŸ–±οΈ-Wheel")])])],-1),vn=n("tr",null,[n("td",null,"πŸ”- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),s("/πŸ–±οΈ-Wheel")])])],-1),wn=n("tr",null,[n("td",null,"πŸ–ΌοΈ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),bn=n("tr",null,[n("td",null,"πŸ§©βœ”οΈ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),kn=n("tr",null,[n("td",null,"πŸ§©β“ Toggle loose pieces:"),n("td",null,[n("div",null,[n("kbd",null,"G")])])],-1),xn=n("tr",null,[n("td",null,"πŸ”‰ Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1);un.render=function(e,o,l,a,s,r){return i(),t("div",{class:"overlay transparent",onClick:o[2]||(o[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:o[1]||(o[1]=u((()=>{}),["stop"]))},[pn,gn,hn,mn,yn,fn,vn,wn,bn,kn,xn])])};var Cn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),An=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),Sn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Tn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),Pn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function zn(){let e=0,t=0,n=1;const o=(o,l)=>{e+=o/n,t+=l/n},l=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),s=e=>({w:e.w*n,h:e.h*n}),r=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>((e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0})(l(e),t),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}=s(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:s,viewportToWorld:e=>{const{x:t,y:n}=a(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:a,viewportDimToWorld:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:r}}function In(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var Dn={createCanvas:In,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 o=In(t,n);return o.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(o)},colorizedCanvas:function(e,t,n){const o=In(e.width,e.height),l=o.getContext("2d");return l.save(),l.drawImage(t,0,0),l.fillStyle=n,l.globalCompositeOperation="source-in",l.fillRect(0,0,t.width,t.height),l.restore(),l.save(),l.globalCompositeOperation="destination-over",l.drawImage(e,0,0),l.restore(),o}};const En=ae("Debug.js");let _n=0,Mn=0;var Nn=e=>{_n=performance.now(),Mn=e},On=e=>{const t=performance.now(),n=t-_n;n>Mn&&En.log(e+": "+n),_n=t};function Bn(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function Un(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var Rn={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:Bn,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:Un,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 Bn(Un(e),Un(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 Vn=ae("PuzzleGraphics.js");function $n(e,t){const n=ie.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var Gn={loadPuzzleBitmaps:async function(e){const t=await Dn.loadImageToBitmap(e.info.imageUrl),n=await Dn.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){Vn.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,i=o/100,s=[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:l,y:l},r=Rn.pointAdd(a,{x:o,y:0}),c=Rn.pointAdd(r,{x:0,y:o}),u=Rn.pointSub(c,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oie.decodePiece(Fn[e].puzzle.tiles[t]),no=(e,t)=>to(e,t).group,oo=(e,t)=>{const n=Fn[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},lo=(e,t)=>{const n=Fn[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=Fn[e].puzzle.info,o=ie.coordByPieceIdx(n,t),l=o.x*n.tileSize,a=o.y*n.tileSize;return{x:l,y:a}}(e,t);return Rn.pointAdd(o,l)},ao=(e,t)=>to(e,t).pos,io=e=>{const t=Ao(e),n=So(e),o=Math.round(t/4),l=Math.round(n/4);return{x:0-o,y:0-l,w:t+2*o,h:n+2*l}},so=(e,t)=>{const n=po(e),o=to(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},ro=(e,t)=>to(e,t).z,co=(e,t)=>{for(const n of Fn[e].puzzle.tiles){const e=ie.decodePiece(n);if(e.owner===t)return e.idx}return-1},uo=e=>Fn[e].puzzle.info.tileDrawSize,po=e=>Fn[e].puzzle.info.tileSize,go=e=>Fn[e].puzzle.data.maxGroup,ho=e=>Fn[e].puzzle.data.maxZ;function mo(e,t){const n=Fn[e].puzzle.info,o=ie.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const yo=(e,t,n)=>{for(const o of t)eo(e,o,{z:n})},fo=(e,t,n)=>{const o=ao(e,t);eo(e,t,{pos:Rn.pointAdd(o,n)})},vo=(e,t,n)=>{const o=uo(e),l=io(e),a=n;for(const i of t){const t=to(e,i);t.pos.x+n.xl.x+l.w&&(a.x=Math.min(l.x+l.w-t.pos.x+o,a.x)),t.pos.y+n.yl.y+l.h&&(a.y=Math.min(l.y+l.h-t.pos.y+o,a.y))}for(const i of t)fo(e,i,a)},wo=(e,t)=>to(e,t).owner,bo=(e,t)=>{for(const n of t)eo(e,n,{owner:-1,z:1})},ko=(e,t,n)=>{for(const o of t)eo(e,o,{owner:n})};function xo(e,t){const n=Fn[e].puzzle.tiles,o=ie.decodePiece(n[t]),l=[];if(o.group)for(const a of n){const e=ie.decodePiece(a);e.group===o.group&&l.push(e.idx)}else l.push(o.idx);return l}const Co=(e,t)=>{const n=jn(e,t);return n?n.points:0},Ao=e=>Fn[e].puzzle.info.table.width,So=e=>Fn[e].puzzle.info.table.height;var To={setGame:function(e,t){Fn[e]=t},exists:function(e){return!!Fn[e]||!1},playerExists:Hn,getActivePlayers:function(e,t){const n=t-30*N;return Yn(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*N;return Yn(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){Hn(e,t)?Xn(e,t,{ts:n}):Wn(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:Kn,getPieceCount:Qn,getImageUrl:function(e){return Fn[e].puzzle.info.imageUrl},setImageUrl:function(e,t){Fn[e].puzzle.info.imageUrl=t},get:function(e){return Fn[e]||null},getAllGames:function(){return Object.values(Fn).sort(((e,t)=>Zn(e.id)===Zn(t.id)?t.puzzle.data.started-e.puzzle.data.started:Zn(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=jn(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=jn(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=jn(e,t);return n?n.name:null},getPlayerIndexById:Ln,getPlayerIdByIndex:function(e,t){return Fn[e].players.length>t?ie.decodePlayer(Fn[e].players[t]).id:null},changePlayer:Xn,setPlayer:Wn,setPiece:function(e,t,n){Fn[e].puzzle.tiles[t]=ie.encodePiece(n)},setPuzzleData:function(e,t){Fn[e].puzzle.data=t},getTableWidth:Ao,getTableHeight:So,getPuzzle:e=>Fn[e].puzzle,getRng:e=>Fn[e].rng.obj,getPuzzleWidth:e=>Fn[e].puzzle.info.width,getPuzzleHeight:e=>Fn[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return Fn[e].puzzle.tiles.map(ie.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=co(e,t);return n<0?null:Fn[e].puzzle.tiles[n]},getPieceDrawOffset:e=>Fn[e].puzzle.info.tileDrawOffset,getPieceDrawSize:uo,getFinalPiecePos:lo,getStartTs:e=>Fn[e].puzzle.data.started,getFinishTs:e=>Fn[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=Fn[e].puzzle,i=function(e,t){return t in Fn[e].evtInfos?Fn[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),s=[],r=()=>{s.push([Lt,a.data])},d=t=>{s.push([jt,ie.encodePiece(to(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=jn(e,t);n&&s.push([Wt,ie.encodePlayer(n)])},p=n[0];if(p===Rt){const l=n[1];Xn(e,t,{bgcolor:l,ts:o}),u()}else if(p===Vt){const l=n[1];Xn(e,t,{color:l,ts:o}),u()}else if(p===$t){const l=`${n[1]}`.substr(0,16);Xn(e,t,{name:l,ts:o}),u()}else if(p===_t){const l=n[1],a=n[2],i=jn(e,t);if(i){const n=i.x-l,s=i.y-a;Xn(e,t,{ts:o,x:n,y:s}),u()}}else if(p===Mt){const l={x:n[1],y:n[2]};Xn(e,t,{d:1,ts:o}),u(),i._last_mouse_down=l;const a=((e,t)=>{const n=Fn[e].puzzle.info,o=Fn[e].puzzle.tiles;let l=-1,a=-1;for(let i=0;il)&&(l=e.z,a=i)}return a})(e,l);if(a>=0){const n=ho(e)+1;Jn(e,{maxZ:n}),r();const o=xo(e,a);yo(e,o,ho(e)),ko(e,o,t),c(o)}i._last_mouse=l}else if(p===Ot){const l=n[1],a=n[2],s={x:l,y:a};if(null===i._last_mouse_down)Xn(e,t,{x:l,y:a,ts:o}),u();else{const n=co(e,t);if(n>=0){Xn(e,t,{x:l,y:a,ts:o}),u();const r=xo(e,n);let d=Rn.pointInBounds(s,io(e))&&Rn.pointInBounds(i._last_mouse_down,io(e));for(const t of r){const n=so(e,t);if(Rn.pointInBounds(s,n)){d=!0;break}}if(d){const t=l-i._last_mouse_down.x,n=a-i._last_mouse_down.y;vo(e,r,{x:t,y:n}),c(r)}}else Xn(e,t,{ts:o}),u();i._last_mouse_down=s}i._last_mouse=s}else if(p===Nt){const s={x:n[1],y:n[2]},p=0;i._last_mouse_down=null;const g=co(e,t);if(g>=0){const n=xo(e,g);ko(e,n,0),c(n);const i=ao(e,g),s=lo(e,g);let h=!1;if(function(e){return Fn[e].snapMode||ee.NORMAL}(e)===ee.REAL){for(const t of n)if(oo(e,t)){h=!0;break}}else h=!0;if(h&&Rn.pointDistance(s,i){const l=Fn[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=no(e,t),l=no(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=ao(e,t),i=Rn.pointAdd(ao(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(Rn.pointDistance(a,i){const o=Fn[e].puzzle.tiles,l=no(e,t),a=no(e,n);let i;const s=[];l&&s.push(l),a&&s.push(a),l?i=l:a?i=a:(Jn(e,{maxGroup:go(e)+1}),r(),i=go(e));if(eo(e,t,{group:i}),d(t),eo(e,n,{group:i}),d(n),s.length>0)for(const r of o){const t=ie.decodePiece(r);s.includes(t.group)&&(eo(e,t.idx,{group:i}),d(t.idx))}})(e,t,n),l=xo(e,t),((e,t)=>-1===wo(e,t))(e,n))bo(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=ro(e,o);t>n&&(n=t)}return n})(e,l);yo(e,l,t)}return c(l),!0}return!1};let a=!1;for(const t of xo(e,g)){const o=mo(e,t);if(n(e,t,o[0],[0,1])||n(e,t,o[1],[-1,0])||n(e,t,o[2],[0,-1])||n(e,t,o[3],[1,0])){a=!0;break}}if(a&&qn(e)===Z.ANY){const n=Co(e,t)+1;Xn(e,t,{d:p,ts:o,points:n}),u()}else Xn(e,t,{d:p,ts:o}),u();a&&l&&l(t)}}else Xn(e,t,{d:p,ts:o}),u();i._last_mouse=s}else if(p===Bt){const l=n[1],a=n[2];Xn(e,t,{x:l,y:a,ts:o}),u(),i._last_mouse={x:l,y:a}}else if(p===Ut){const l=n[1],a=n[2];Xn(e,t,{x:l,y:a,ts:o}),u(),i._last_mouse={x:l,y:a}}else Xn(e,t,{ts:o}),u();return function(e,t,n){Fn[e].evtInfos[t]=n}(e,t,i),s}};let Po=-10,zo=20,Io=2,Do=15;class Eo{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=Po+Math.random()*zo,this.vy=-1*(Io+Math.random()*Do),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{this.resize()}))}setSpeedParams(){let e=0,t=0;for(;e=0;)t+=1,e+=t;Io=t/2,Do=t-Io;const n=1/4*this.canvas.width/(t/2);Po=-n,zo=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new Eo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new Eo(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{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?c:u;y[t]=await createImageBitmap(Dn.colorizedCanvas(n,o,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,Ro=!0})),t}(l,Dn.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};on.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await on.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 k=()=>0;const x=async()=>{if("play"===o){const o=await on.connect(n,e,t),l=ie.decodeGame(o);To.setGame(l.id,l),k=()=>O()}else{if("replay"!==o)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=ie.decodeGame(t.game);To.setGame(n.id,n),w.lastRealTs=O(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,k=()=>w.lastGameTs}}Ro=!0};await x();const C=To.getPieceDrawOffset(e),A=To.getPieceDrawSize(e),S=To.getPuzzleWidth(e),T=To.getPuzzleHeight(e),P=To.getTableWidth(e),z=To.getTableHeight(e),I={x:(P-S)/2,y:(z-T)/2},D={w:S,h:T},E={w:A,h:A},_=await Gn.loadPuzzleBitmaps(To.getPuzzle(e)),N=new Mo(v,To.getRng(e));N.init();const B=v.getContext("2d");v.classList.add("loaded");const U=zn();U.move(-(P-v.width)/2,-(z-v.height)/2);const R=function(e,t,n){let o=[],l=!0,a=!1,i=!1,s=!1,r=!1,d=!1,c=!1,u=!1;const p=(e,t)=>{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},g=e=>p(e.offsetX,e.offsetY),h=()=>p(e.width/2,e.height/2),m=(e,t)=>{l&&("Shift"===t.key?u=e:"ArrowUp"===t.key||"w"===t.key||"W"===t.key?s=e:"ArrowDown"===t.key||"s"===t.key||"S"===t.key?r=e:"ArrowLeft"===t.key||"a"===t.key||"A"===t.key?a=e:"ArrowRight"===t.key||"d"===t.key||"D"===t.key?i=e:"q"===t.key?c=e:"e"===t.key&&(d=e))};let y=null;e.addEventListener("mousedown",(e=>{y=g(e),0===e.button&&f([Mt,...y])})),e.addEventListener("mouseup",(e=>{y=g(e),0===e.button&&f([Nt,...y])})),e.addEventListener("mousemove",(e=>{y=g(e),f([Ot,...y])})),e.addEventListener("wheel",(e=>{if(y=g(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Bt:Ut;f([t,...y])}})),t.addEventListener("keydown",(e=>m(!0,e))),t.addEventListener("keyup",(e=>m(!1,e))),t.addEventListener("keypress",(e=>{l&&(" "===e.key&&f([Gt]),"F"!==e.key&&"f"!==e.key||(Bo=!Bo,Ro=!0),"G"!==e.key&&"g"!==e.key||(Uo=!Uo,Ro=!0),"M"!==e.key&&"m"!==e.key||f([Ft]))}));const f=e=>{o.push(e)};return{addEvent:f,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(a?1:0)-(i?1:0),t=(s?1:0)-(r?1:0);if(0!==e||0!==t){const o=(u?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});f([_t,l.w,l.h]),y&&(y[0]-=l.w,y[1]-=l.h)}if(d&&c);else if(d){if(n.canZoom("in")){const e=y||h();f([Bt,...e])}}else if(c&&n.canZoom("out")){const e=y||h();f([Ut,...e])}},setHotkeys:e=>{l=e}}}(v,window,U),V=To.getImageUrl(e),$=()=>{const t=To.getStartTs(e),n=To.getFinishTs(e),o=k();a.setFinished(!!n),a.setDuration((n||o)-t)};$(),a.setPiecesDone(To.getFinishedPiecesCount(e)),a.setPiecesTotal(To.getPieceCount(e));const G=k();a.setActivePlayers(To.getActivePlayers(e,G)),a.setIdlePlayers(To.getIdlePlayers(e,G));const F=!!To.getFinishTs(e);let L=F;const j=()=>L&&!F,W=()=>{const e=localStorage.getItem("sound_enabled");return null!==e&&"1"===e},H=()=>To.getPlayerBgColor(e,t)||localStorage.getItem("bg_color")||"#222222",Y=()=>To.getPlayerColor(e,t)||localStorage.getItem("player_color")||"#ffffff";let Q="",q="",Z=!1;const K=e=>{Z=e;const[t,n]=e?[Q,"grab"]:[q,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},X=e=>{Q=Dn.colorizedCanvas(r,c,e).toDataURL(),q=Dn.colorizedCanvas(d,u,e).toDataURL(),K(Z)};X(Y());const J=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},ee=[];let te;let ne;if("play"===o?ee.push(setInterval((()=>{$()}),1e3)):"replay"===o&&J(),"play"===o)on.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case Wt:{const n=ie.decodePlayer(a);n.id!==t&&(To.setPlayer(e,n.id,n),Ro=!0)}break;case jt:{const t=ie.decodePiece(a);To.setPiece(e,t.idx,t),Ro=!0}break;case Lt:To.setPuzzleData(e,a),Ro=!0}L=!!To.getFinishTs(e)}));else if("replay"===o){const t=(t,n)=>{const o=t;if(o[0]===It){const t=o[1];return To.addPlayer(e,t,n),!0}if(o[0]===Dt){const t=To.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return To.addPlayer(e,t,n),!0}if(o[0]===Et){const t=To.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const l=o[2];return To.handleInput(e,t,l,n),!0}return!1},n=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=O();if(w.paused)return w.lastRealTs=o,void(te=setTimeout(n,50));const l=(o-w.lastRealTs)*w.speeds[w.speedIdx];let a=w.lastGameTs+l;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const n=w.log[w.logPointer],o=w.gameStartTs+n[n.length-1],l=w.log[e],i=w.gameStartTs+l[l.length-1];if(i>a){if(w.skipNonActionPhases&&a+500*M{let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,i=window.requestAnimationFrame,s=1/n,r=o*s;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,l(s);a(c/o),u=d,t||i(p)};return i(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===o){const o=n[0];if(o===_t){const e=n[1],t=n[2],o=U.worldDimToViewport({w:e,h:t});Ro=!0,U.move(o.w,o.h)}else if(o===Ot){if(oe&&!To.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=U.worldToViewport(e),o=Math.round(t.x-oe.x),l=Math.round(t.y-oe.y);Ro=!0,U.move(o,l),oe=t}}else if(o===Vt)X(n[1]);else if(o===Mt){const e={x:n[1],y:n[2]};oe=U.worldToViewport(e),K(!0)}else if(o===Nt)oe=null,K(!1);else if(o===Bt){const e={x:n[1],y:n[2]};Ro=!0,U.zoom("in",U.worldToViewport(e))}else if(o===Ut){const e={x:n[1],y:n[2]};Ro=!0,U.zoom("out",U.worldToViewport(e))}else o===Gt?a.togglePreview():o===Ft&&a.toggleSoundsEnabled();const l=k();To.handleInput(e,t,n,l,(e=>{W()&&s.play()})).length>0&&(Ro=!0),on.sendClientEvent(n)}else if("replay"===o){const e=n[0];if(e===_t){const e=n[1],t=n[2];Ro=!0,U.move(e,t)}else if(e===Ot){if(oe){const e={x:n[1],y:n[2]},t=U.worldToViewport(e),o=Math.round(t.x-oe.x),l=Math.round(t.y-oe.y);Ro=!0,U.move(o,l),oe=t}}else if(e===Mt){const e={x:n[1],y:n[2]};oe=U.worldToViewport(e)}else if(e===Nt)oe=null;else if(e===Bt){const e={x:n[1],y:n[2]};Ro=!0,U.zoom("in",U.worldToViewport(e))}else if(e===Ut){const e={x:n[1],y:n[2]};Ro=!0,U.zoom("out",U.worldToViewport(e))}else e===Gt&&a.togglePreview()}L=!!To.getFinishTs(e),j()&&(N.update(),Ro=!0)},render:async()=>{if(!Ro)return;const n=k();let l,i,s;window.DEBUG&&Nn(0),B.fillStyle=H(),B.fillRect(0,0,v.width,v.height),window.DEBUG&&On("clear done"),l=U.worldToViewportRaw(I),i=U.worldDimToViewportRaw(D),B.fillStyle="rgba(255, 255, 255, .3)",B.fillRect(l.x,l.y,i.w,i.h),window.DEBUG&&On("board done");const r=To.getPiecesSortedByZIndex(e);window.DEBUG&&On("get tiles done"),i=U.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?Bo:Uo)&&(s=_[e.idx],l=U.worldToViewportRaw({x:C+e.pos.x,y:C+e.pos.y}),B.drawImage(s,0,0,s.width,s.height,l.x,l.y,i.w,i.h));window.DEBUG&&On("tiles done");const d=[];for(const a of To.getActivePlayers(e,n))c=a,("replay"===o||c.id!==t)&&(s=await f(a),l=U.worldToViewport(a),B.drawImage(s,l.x-g,l.y-m),d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var c;B.fillStyle="white",B.textAlign="center";for(const[e,t,o]of d)B.fillText(e,t,o);window.DEBUG&&On("players done"),a.setActivePlayers(To.getActivePlayers(e,n)),a.setIdlePlayers(To.getIdlePlayers(e,n)),a.setPiecesDone(To.getFinishedPiecesCount(e)),window.DEBUG&&On("HUD done"),j()&&N.render(),Ro=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{localStorage.setItem("bg_color",e),R.addEvent([Rt,e])},onColorChange:e=>{localStorage.setItem("player_color",e),R.addEvent([Vt,e])},onNameChange:e=>{localStorage.setItem("player_name",e),R.addEvent([$t,e])},onSoundsEnabledChange:e=>{localStorage.setItem("sound_enabled",e?"1":"0")},replayOnSpeedUp:()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,J())},replayOnPauseToggle:()=>{w.paused=!w.paused,J()},replayOnSkipToggle:()=>{w.skipNonActionPhases=!w.skipNonActionPhases},previewImageUrl:V,player:{background:H(),color:Y(),name:To.getPlayerName(e,t)||localStorage.getItem("player_name")||"anon",soundsEnabled:W()},disconnect:on.disconnect,connect:x,unload:()=>{ee.forEach((e=>{clearInterval(e)})),te&&clearTimeout(te),ne&&ne.stop()}}}var $o=e({name:"game",components:{PuzzleStatus:yt,Scores:ut,SettingsOverlay:vt,PreviewOverlay:Ct,ConnectionOverlay:ln,HelpOverlay:un},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange: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.g=await Vo(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{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},setConnectionState:e=>{this.connectionState=e},togglePreview:()=>{this.toggle("preview",!1)},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled}}))},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 Go={id:"game"},Fo={class:"menu"},Lo={class:"tabs"},jo=s("🧩 Puzzles");$o.render=function(e,l,s,r,d,c){const u=a("settings-overlay"),g=a("preview-overlay"),h=a("help-overlay"),m=a("connection-overlay"),y=a("puzzle-status"),f=a("router-link"),v=a("scores");return i(),t("div",Go,[p(n(u,{onBgclick:l[1]||(l[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":l[2]||(l[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(g,{onBgclick:l[3]||(l[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),p(n(h,{onBgclick:l[4]||(l[4]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),n(m,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(y,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Fo,[n("div",Lo,[n(f,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[jo])),_:1}),n("div",{class:"opener",onClick:l[5]||(l[5]=t=>e.toggle("preview",!1))},"πŸ–ΌοΈ Preview"),n("div",{class:"opener",onClick:l[6]||(l[6]=t=>e.toggle("settings",!0))},"πŸ› οΈ Settings"),n("div",{class:"opener",onClick:l[7]||(l[7]=t=>e.toggle("help",!0))},"ℹ️ Help")])]),n(v,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Wo=e({name:"replay",components:{PuzzleStatus:yt,Scores:ut,SettingsOverlay:vt,PreviewOverlay:Ct,HelpOverlay:un},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,skipNoAction:!0,overlay:"",connectionState:0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},replayOnSkipToggle:()=>{},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.g=await Vo(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{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}}))},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 Ho={id:"replay"},Yo=s("Skip no action phases: "),Qo={class:"menu"},qo={class:"tabs"},Zo=s("🧩 Puzzles");Wo.render=function(e,l,s,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("help-overlay"),y=a("puzzle-status"),f=a("router-link"),v=a("scores");return i(),t("div",Ho,[p(n(g,{onBgclick:l[1]||(l[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":l[2]||(l[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:l[3]||(l[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),p(n(m,{onBgclick:l[4]||(l[4]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),n(y,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:o((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("div",null,[n("label",null,[Yo,p(n("input",{type:"checkbox","onUpdate:modelValue":l[5]||(l[5]=t=>e.skipNoAction=t),onChange:l[6]||(l[6]=t=>e.g.replayOnSkipToggle())},null,544),[[k,e.skipNoAction]])])]),n("button",{class:"btn",onClick:l[7]||(l[7]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:l[8]||(l[8]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:l[9]||(l[9]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Qo,[n("div",qo,[n(f,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Zo])),_:1}),n("div",{class:"opener",onClick:l[10]||(l[10]=t=>e.toggle("preview",!1))},"πŸ–ΌοΈ Preview"),n("div",{class:"opener",onClick:l[11]||(l[11]=t=>e.toggle("settings",!0))},"πŸ› οΈ Settings"),n("div",{class:"opener",onClick:l[12]||(l[12]=t=>e.toggle("help",!0))},"ℹ️ Help")])]),n(v,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=await fetch("/api/conf"),t=await e.json();const n=C({history:A(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:tt},{name:"game",path:"/g/:id",component:$o},{name:"replay",path:"/replay/:id",component:Wo}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const o=S(T);o.config.globalProperties.$config=t,o.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=ie.uniqId(),localStorage.setItem("ID",e)),e}(),o.use(n),o.mount("#app")})(); diff --git a/build/public/index.html b/build/public/index.html index 2fe3679..456eedc 100644 --- a/build/public/index.html +++ b/build/public/index.html @@ -4,7 +4,7 @@ 🧩 jigsaw.hyottoko.club - + diff --git a/build/server/main.js b/build/server/main.js index 6a02829..c87b04b 100644 --- a/build/server/main.js +++ b/build/server/main.js @@ -3,8 +3,6 @@ import express from 'express'; import compression from 'compression'; import multer from 'multer'; import fs from 'fs'; -import readline from 'readline'; -import stream from 'stream'; import { fileURLToPath } from 'url'; import { dirname } from 'path'; import sizeOf from 'image-size'; @@ -1249,6 +1247,7 @@ const PUBLIC_DIR = `${BASE_DIR}/build/public/`; const DB_PATCHES_DIR = `${BASE_DIR}/src/dbpatches`; const DB_FILE = `${BASE_DIR}/data/db.sqlite`; +const LINES_PER_LOG_FILE = 10000; const POST_GAME_LOG_DURATION = 5 * Time.MIN; const shouldLog = (finishTs, currentTs) => { // when not finished yet, always log @@ -1260,54 +1259,52 @@ const shouldLog = (finishTs, currentTs) => { const timeSinceGameEnd = currentTs - finishTs; return timeSinceGameEnd <= POST_GAME_LOG_DURATION; }; -const filename = (gameId) => `${DATA_DIR}/log_${gameId}.log`; +const filename = (gameId, offset) => `${DATA_DIR}/log_${gameId}-${offset}.log`; +const idxname = (gameId) => `${DATA_DIR}/log_${gameId}.idx.log`; const create = (gameId) => { - const file = filename(gameId); - if (!fs.existsSync(file)) { - fs.appendFileSync(file, ''); + const idxfile = idxname(gameId); + if (!fs.existsSync(idxfile)) { + const logfile = filename(gameId, 0); + fs.appendFileSync(logfile, ""); + fs.appendFileSync(idxfile, JSON.stringify({ + total: 0, + currentFile: logfile, + perFile: LINES_PER_LOG_FILE, + })); } }; const exists = (gameId) => { - const file = filename(gameId); - return fs.existsSync(file); + const idxfile = idxname(gameId); + return fs.existsSync(idxfile); }; const _log = (gameId, ...args) => { - const file = filename(gameId); - if (!fs.existsSync(file)) { + const idxfile = idxname(gameId); + if (!fs.existsSync(idxfile)) { return; } - const str = JSON.stringify(args); - fs.appendFileSync(file, str + "\n"); + const idx = JSON.parse(fs.readFileSync(idxfile, 'utf-8')); + idx.total++; + fs.appendFileSync(idx.currentFile, JSON.stringify(args) + "\n"); + // prepare next log file + if (idx.total % idx.perFile === 0) { + const logfile = filename(gameId, idx.total); + fs.appendFileSync(logfile, ""); + idx.currentFile = logfile; + } + fs.writeFileSync(idxfile, JSON.stringify(idx)); }; -const get = async (gameId, offset = 0, size = 10000) => { - const file = filename(gameId); +const get = (gameId, offset = 0) => { + const idxfile = idxname(gameId); + if (!fs.existsSync(idxfile)) { + return []; + } + const file = filename(gameId, offset); if (!fs.existsSync(file)) { return []; } - return new Promise((resolve) => { - const instream = fs.createReadStream(file); - const outstream = new stream.Writable(); - const rl = readline.createInterface(instream, outstream); - const lines = []; - let i = -1; - rl.on('line', (line) => { - if (!line) { - // skip empty - return; - } - i++; - if (offset > i) { - return; - } - if (offset + size <= i) { - rl.close(); - return; - } - lines.push(JSON.parse(line)); - }); - rl.on('close', () => { - resolve(lines); - }); + const log = fs.readFileSync(file, 'utf-8').split("\n"); + return log.map(line => { + return JSON.parse(line); }); }; var GameLog = { @@ -2061,7 +2058,7 @@ app.get('/api/replay-data', async (req, res) => { res.status(404).send({ reason: 'no log found' }); return; } - const log = await GameLog.get(gameId, offset, size); + const log = GameLog.get(gameId, offset); let game = null; if (offset === 0) { // also need the game diff --git a/scripts/split_logs.ts b/scripts/split_logs.ts new file mode 100644 index 0000000..3da036f --- /dev/null +++ b/scripts/split_logs.ts @@ -0,0 +1,72 @@ +import fs from 'fs' +import readline from 'readline' +import stream from 'stream' +import { logger } from '../src/common/Util' +import { DATA_DIR } from '../src/server/Dirs' + +const log = logger('rewrite_logs') + +const doit = (file: string): Promise => { + const filename = (offset: number) => file.replace(/\.log$/, `-${offset}.log`) + const idxname = () => file.replace(/\.log$/, `.idx.log`) + + let perfile = 10000 + const idx = { + total: 0, + currentFile: '', + perFile: perfile, + } + + return new Promise((resolve) => { + const instream = fs.createReadStream(DATA_DIR + '/' + file) + const outstream = new stream.Writable() + const rl = readline.createInterface(instream, outstream) + + + let lines: any[] = [] + let offset = 0 + let count = 0 + rl.on('line', (line) => { + if (!line) { + // skip empty + return + } + count++ + lines.push(line) + if (count >= perfile) { + const fn = filename(offset) + idx.currentFile = fn + idx.total += count + fs.writeFileSync(DATA_DIR + '/' + fn, lines.join("\n")) + count = 0 + offset += perfile + lines = [] + } + }) + + rl.on('close', () => { + if (count > 0) { + const fn = filename(offset) + idx.currentFile = fn + idx.total += count + fs.writeFileSync(DATA_DIR + '/' + fn, lines.join("\n")) + count = 0 + offset += perfile + lines = [] + } + + fs.writeFileSync(DATA_DIR + '/' + idxname(), JSON.stringify(idx)) + resolve() + }) + }) +} + +let logs = fs.readdirSync(DATA_DIR) + .filter(f => f.toLowerCase().match(/^log_.*\.log$/)) + + +;(async () => { + for (const file of logs) { + await doit(file) + } +})() diff --git a/src/frontend/Communication.ts b/src/frontend/Communication.ts index 5301faa..70a61c8 100644 --- a/src/frontend/Communication.ts +++ b/src/frontend/Communication.ts @@ -114,10 +114,9 @@ function connect( async function requestReplayData( gameId: string, - offset: number, - size: number + offset: number ): Promise { - const args = { gameId, offset, size } + const args = { gameId, offset } const res = await fetch(`/api/replay-data${Util.asQueryArgs(args)}`) const json: ReplayData = await res.json() return json diff --git a/src/frontend/game.ts b/src/frontend/game.ts index 7a14e42..2a7d3fd 100644 --- a/src/frontend/game.ts +++ b/src/frontend/game.ts @@ -69,7 +69,6 @@ interface Replay { skipNonActionPhases: boolean // dataOffset: number - dataSize: number } const shouldDrawPiece = (piece: Piece) => { @@ -301,9 +300,8 @@ export async function main( lastRealTs: 0, lastGameTs: 0, gameStartTs: 0, - skipNonActionPhases: false, + skipNonActionPhases: true, dataOffset: 0, - dataSize: 10000, } Communication.onConnectionStateChange((state) => { @@ -314,11 +312,10 @@ export async function main( gameId: string ): Promise => { const offset = REPLAY.dataOffset - REPLAY.dataOffset += REPLAY.dataSize + REPLAY.dataOffset += 10000 // meh const replay: ReplayData = await Communication.requestReplayData( gameId, - offset, - REPLAY.dataSize + offset ) // cut log that was already handled @@ -326,7 +323,7 @@ export async function main( REPLAY.logPointer = 0 REPLAY.log.push(...replay.log) - if (replay.log.length < REPLAY.dataSize) { + if (replay.log.length === 0) { REPLAY.final = true } return replay @@ -340,10 +337,6 @@ export async function main( Game.setGame(gameObject.id, gameObject) TIME = () => Time.timestamp() } else if (MODE === MODE_REPLAY) { - REPLAY.logPointer = 0 - REPLAY.dataSize = 10000 - REPLAY.speeds = [0.5, 1, 2, 5, 10, 20, 50, 100, 250, 500] - REPLAY.speedIdx = 1 const replay: ReplayData = await queryNextReplayBatch(gameId) if (!replay.game) { throw '[ 2021-05-29 no game received ]' @@ -354,8 +347,6 @@ export async function main( REPLAY.lastRealTs = Time.timestamp() REPLAY.gameStartTs = parseInt(replay.log[0][4], 10) REPLAY.lastGameTs = REPLAY.gameStartTs - REPLAY.paused = false - REPLAY.skipNonActionPhases = false TIME = () => REPLAY.lastGameTs } else { @@ -493,6 +484,10 @@ export async function main( doSetSpeedStatus() } + const replayOnSkipToggle = () => { + REPLAY.skipNonActionPhases = !REPLAY.skipNonActionPhases + } + const intervals: NodeJS.Timeout[] = [] let to: NodeJS.Timeout const clearIntervals = () => { @@ -520,9 +515,6 @@ export async function main( doSetSpeedStatus() } - // // TODO: remove (make changable via interface) - // REPLAY.skipNonActionPhases = true - if (MODE === MODE_PLAY) { Communication.onServerChange((msg: ServerEvent) => { const msgType = msg[0] @@ -608,10 +600,8 @@ export async function main( const nextTs: Timestamp = REPLAY.gameStartTs + nextLogEntry[nextLogEntry.length - 1] if (nextTs > maxGameTs) { // next log entry is too far into the future - if (REPLAY.skipNonActionPhases && (maxGameTs + 50 < nextTs)) { + if (REPLAY.skipNonActionPhases && (maxGameTs + 500 * Time.MS < nextTs)) { const skipInterval = nextTs - currTs - // lets skip to the next log entry - // log.info('skipping non-action, from', maxGameTs, skipInterval) maxGameTs += skipInterval } break @@ -874,6 +864,7 @@ export async function main( replayOnSpeedUp, replayOnSpeedDown, replayOnPauseToggle, + replayOnSkipToggle, previewImageUrl, player: { background: playerBgColor(), diff --git a/src/frontend/views/Replay.vue b/src/frontend/views/Replay.vue index d846dbc..74bcbba 100644 --- a/src/frontend/views/Replay.vue +++ b/src/frontend/views/Replay.vue @@ -12,6 +12,12 @@ >
{{replayText}}
+
+ +
@@ -59,6 +65,7 @@ export default defineComponent({ duration: 0, piecesDone: 0, piecesTotal: 0, + skipNoAction: true, overlay: '', @@ -80,6 +87,7 @@ export default defineComponent({ replayOnSpeedUp: () => {}, replayOnSpeedDown: () => {}, replayOnPauseToggle: () => {}, + replayOnSkipToggle: () => {}, connect: () => {}, disconnect: () => {}, unload: () => {}, diff --git a/src/server/GameLog.ts b/src/server/GameLog.ts index d764304..0c016ad 100644 --- a/src/server/GameLog.ts +++ b/src/server/GameLog.ts @@ -8,6 +8,7 @@ import { DATA_DIR } from './../server/Dirs' const log = logger('GameLog.js') +const LINES_PER_LOG_FILE = 10000 const POST_GAME_LOG_DURATION = 5 * Time.MIN const shouldLog = (finishTs: Timestamp, currentTs: Timestamp): boolean => { @@ -22,62 +23,63 @@ const shouldLog = (finishTs: Timestamp, currentTs: Timestamp): boolean => { return timeSinceGameEnd <= POST_GAME_LOG_DURATION } -const filename = (gameId: string) => `${DATA_DIR}/log_${gameId}.log` +const filename = (gameId: string, offset: number) => `${DATA_DIR}/log_${gameId}-${offset}.log` +const idxname = (gameId: string) => `${DATA_DIR}/log_${gameId}.idx.log` const create = (gameId: string): void => { - const file = filename(gameId) - if (!fs.existsSync(file)) { - fs.appendFileSync(file, '') + const idxfile = idxname(gameId) + if (!fs.existsSync(idxfile)) { + const logfile = filename(gameId, 0) + fs.appendFileSync(logfile, "") + fs.appendFileSync(idxfile, JSON.stringify({ + total: 0, + currentFile: logfile, + perFile: LINES_PER_LOG_FILE, + })) } } const exists = (gameId: string): boolean => { - const file = filename(gameId) - return fs.existsSync(file) + const idxfile = idxname(gameId) + return fs.existsSync(idxfile) } const _log = (gameId: string, ...args: Array): void => { - const file = filename(gameId) - if (!fs.existsSync(file)) { + const idxfile = idxname(gameId) + if (!fs.existsSync(idxfile)) { return } - const str = JSON.stringify(args) - fs.appendFileSync(file, str + "\n") + + const idx = JSON.parse(fs.readFileSync(idxfile, 'utf-8')) + idx.total++ + fs.appendFileSync(idx.currentFile, JSON.stringify(args) + "\n") + + // prepare next log file + if (idx.total % idx.perFile === 0) { + const logfile = filename(gameId, idx.total) + fs.appendFileSync(logfile, "") + idx.currentFile = logfile + } + fs.writeFileSync(idxfile, JSON.stringify(idx)) } -const get = async ( +const get = ( gameId: string, offset: number = 0, - size: number = 10000 -): Promise => { - const file = filename(gameId) +): any[] => { + const idxfile = idxname(gameId) + if (!fs.existsSync(idxfile)) { + return [] + } + + const file = filename(gameId, offset) if (!fs.existsSync(file)) { return [] } - return new Promise((resolve) => { - const instream = fs.createReadStream(file) - const outstream = new stream.Writable() - const rl = readline.createInterface(instream, outstream) - const lines: any[] = [] - let i = -1 - rl.on('line', (line) => { - if (!line) { - // skip empty - return - } - i++ - if (offset > i) { - return - } - if (offset + size <= i) { - rl.close() - return - } - lines.push(JSON.parse(line)) - }) - rl.on('close', () => { - resolve(lines) - }) + + const log = fs.readFileSync(file, 'utf-8').split("\n") + return log.map(line => { + return JSON.parse(line) }) } diff --git a/src/server/main.ts b/src/server/main.ts index 215ec6f..4d8e185 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -80,7 +80,7 @@ app.get('/api/replay-data', async (req, res): Promise => { res.status(404).send({ reason: 'no log found' }) return } - const log = await GameLog.get(gameId, offset, size) + const log = GameLog.get(gameId, offset) let game: GameType|null = null if (offset === 0) { // also need the game