From 2fb0e959ae42b70c33d6d64e295f3a5d169dfd96 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Fri, 9 Jul 2021 01:17:26 +0200 Subject: [PATCH 01/17] add info layer that shows info about current puzzle --- src/common/Types.ts | 3 +- src/frontend/PuzzleGraphics.ts | 2 +- src/frontend/components/InfoOverlay.vue | 68 +++++++++++++++++++++++++ src/frontend/game.ts | 1 + src/frontend/views/Game.vue | 7 ++- src/frontend/views/Replay.vue | 7 ++- src/server/Puzzle.ts | 2 + 7 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 src/frontend/components/InfoOverlay.vue diff --git a/src/common/Types.ts b/src/common/Types.ts index 0e8d21d..261e210 100644 --- a/src/common/Types.ts +++ b/src/common/Types.ts @@ -154,8 +154,9 @@ export interface PieceChange { export interface PuzzleInfo { table: PuzzleTable - targetTiles: number, + targetTiles: number imageUrl: string + imageTitle: string width: number height: number diff --git a/src/frontend/PuzzleGraphics.ts b/src/frontend/PuzzleGraphics.ts index 6debdbe..6934cda 100644 --- a/src/frontend/PuzzleGraphics.ts +++ b/src/frontend/PuzzleGraphics.ts @@ -3,7 +3,7 @@ import Geometry, { Rect } from '../common/Geometry' import Graphics from './Graphics' import Util, { logger } from './../common/Util' -import { Puzzle, PuzzleInfo, PieceShape, EncodedPiece } from './../common/GameCommon' +import { Puzzle, PuzzleInfo, PieceShape, EncodedPiece } from './../common/Types' const log = logger('PuzzleGraphics.js') diff --git a/src/frontend/components/InfoOverlay.vue b/src/frontend/components/InfoOverlay.vue new file mode 100644 index 0000000..7f76d2d --- /dev/null +++ b/src/frontend/components/InfoOverlay.vue @@ -0,0 +1,68 @@ + + diff --git a/src/frontend/game.ts b/src/frontend/game.ts index 9f66e8d..ea457d1 100644 --- a/src/frontend/game.ts +++ b/src/frontend/game.ts @@ -969,6 +969,7 @@ export async function main( soundsVolume: playerSoundVolume(), showPlayerNames: showPlayerNames(), }, + game: Game.get(gameId), disconnect: Communication.disconnect, connect: connect, unload: unload, diff --git a/src/frontend/views/Game.vue b/src/frontend/views/Game.vue index d1789f0..e0d3394 100644 --- a/src/frontend/views/Game.vue +++ b/src/frontend/views/Game.vue @@ -2,6 +2,7 @@
+
@@ -27,7 +28,8 @@ 🧩 Puzzles
🖼️ Preview
🛠️ Settings
-
ℹ️ Hotkeys
+
ℹ️ Info
+
⌨️ Hotkeys
@@ -41,6 +43,7 @@ import Scores from './../components/Scores.vue' import PuzzleStatus from './../components/PuzzleStatus.vue' import SettingsOverlay from './../components/SettingsOverlay.vue' import PreviewOverlay from './../components/PreviewOverlay.vue' +import InfoOverlay from './../components/InfoOverlay.vue' import ConnectionOverlay from './../components/ConnectionOverlay.vue' import HelpOverlay from './../components/HelpOverlay.vue' @@ -54,6 +57,7 @@ export default defineComponent({ Scores, SettingsOverlay, PreviewOverlay, + InfoOverlay, ConnectionOverlay, HelpOverlay, }, @@ -81,6 +85,7 @@ export default defineComponent({ soundsVolume: 100, showPlayerNames: true, }, + game: null, previewImageUrl: '', setHotkeys: (v: boolean) => {}, onBgChange: (v: string) => {}, diff --git a/src/frontend/views/Replay.vue b/src/frontend/views/Replay.vue index c8f64ae..7239d2a 100644 --- a/src/frontend/views/Replay.vue +++ b/src/frontend/views/Replay.vue @@ -2,6 +2,7 @@
+
@@ -29,7 +30,8 @@ 🧩 Puzzles
🖼️ Preview
🛠️ Settings
-
ℹ️ Hotkeys
+
ℹ️ Info
+
⌨️ Hotkeys
@@ -43,6 +45,7 @@ import Scores from './../components/Scores.vue' import PuzzleStatus from './../components/PuzzleStatus.vue' import SettingsOverlay from './../components/SettingsOverlay.vue' import PreviewOverlay from './../components/PreviewOverlay.vue' +import InfoOverlay from './../components/InfoOverlay.vue' import HelpOverlay from './../components/HelpOverlay.vue' import { main, MODE_REPLAY } from './../game' @@ -55,6 +58,7 @@ export default defineComponent({ Scores, SettingsOverlay, PreviewOverlay, + InfoOverlay, HelpOverlay, }, data() { @@ -81,6 +85,7 @@ export default defineComponent({ soundsVolume: 100, showPlayerNames: true, }, + game: null, previewImageUrl: '', setHotkeys: (v: boolean) => {}, onBgChange: (v: string) => {}, diff --git a/src/server/Puzzle.ts b/src/server/Puzzle.ts index 4b65f2c..bd0ad98 100644 --- a/src/server/Puzzle.ts +++ b/src/server/Puzzle.ts @@ -7,6 +7,7 @@ import { Dim, Point } from '../common/Geometry' export interface PuzzleCreationImageInfo { file: string url: string + title: string } export interface PuzzleCreationInfo { @@ -140,6 +141,7 @@ async function createPuzzle( // information that was used to create the puzzle targetTiles: targetTiles, imageUrl, + imageTitle: image.title || '', width: info.width, // actual puzzle width (same as bitmap.width) height: info.height, // actual puzzle height (same as bitmap.height) From 0cb1cec2108c0f3fc67f7b4a50d588395a9ffbb8 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Fri, 9 Jul 2021 01:19:35 +0200 Subject: [PATCH 02/17] type hints --- src/frontend/views/Game.vue | 4 ++-- src/frontend/views/Replay.vue | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/frontend/views/Game.vue b/src/frontend/views/Game.vue index e0d3394..c228211 100644 --- a/src/frontend/views/Game.vue +++ b/src/frontend/views/Game.vue @@ -48,7 +48,7 @@ import ConnectionOverlay from './../components/ConnectionOverlay.vue' import HelpOverlay from './../components/HelpOverlay.vue' import { main, MODE_PLAY } from './../game' -import { Player } from '../../common/Types' +import { Game, Player } from '../../common/Types' export default defineComponent({ name: 'game', @@ -85,7 +85,7 @@ export default defineComponent({ soundsVolume: 100, showPlayerNames: true, }, - game: null, + game: null as Game|null, previewImageUrl: '', setHotkeys: (v: boolean) => {}, onBgChange: (v: string) => {}, diff --git a/src/frontend/views/Replay.vue b/src/frontend/views/Replay.vue index 7239d2a..1bf775a 100644 --- a/src/frontend/views/Replay.vue +++ b/src/frontend/views/Replay.vue @@ -85,7 +85,7 @@ export default defineComponent({ soundsVolume: 100, showPlayerNames: true, }, - game: null, + game: null as Game|null, previewImageUrl: '', setHotkeys: (v: boolean) => {}, onBgChange: (v: string) => {}, From 518092d269ab8ec698cd407dac5021162214ffb6 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 16:37:34 +0200 Subject: [PATCH 03/17] info overlay + script to update images in games and logs --- build/public/assets/index.19dfb063.js | 1 - build/public/assets/index.93936dee.js | 1 + build/public/index.html | 2 +- build/server/main.js | 26 +++---- scripts/fix_games_image_info.ts | 90 +++++++++++++++++++++++++ scripts/fix_image.ts | 23 ------- src/common/GameCommon.ts | 12 ++-- src/common/Types.ts | 18 ++++- src/frontend/components/InfoOverlay.vue | 8 +-- src/server/Game.ts | 8 +-- src/server/GameLog.ts | 2 + src/server/Images.ts | 29 +------- src/server/Puzzle.ts | 17 ++--- src/server/main.ts | 4 +- 14 files changed, 148 insertions(+), 93 deletions(-) delete mode 100644 build/public/assets/index.19dfb063.js create mode 100644 build/public/assets/index.93936dee.js create mode 100644 scripts/fix_games_image_info.ts delete mode 100644 scripts/fix_image.ts diff --git a/build/public/assets/index.19dfb063.js b/build/public/assets/index.19dfb063.js deleted file mode 100644 index 9a09aad..0000000 --- a/build/public/assets/index.19dfb063.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 s,e as i,t as r,F as d,f as u,g as c,h as p,v as g,i as h,j as m,p as y,k as f,l as w,m as v,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),D=i("New game");S.render=function(e,i,r,d,u,c){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default: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,M=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 N=1,_=1e3,V=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},O=(e,t)=>M(t-e),U=M,B=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||V();return`${n} ${O(o,l)}`}}});const R={class:"game-info-text"},G=n("br",null,null,-1),$=n("br",null,null,-1),L=n("br",null,null,-1),F=i(" ↪️ Watch replay ");B.render=function(e,d,u,c,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",R,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),G,i(" 👥 "+r(e.game.players),1),$,i(" "+r(e.time(e.game.started,e.game.finished)),1),L])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[F])),_:1},8,["to"])):l("",!0)],4)};var j=e({components:{GameTeaser:B},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await fetch("/api/index-data"),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const W=n("h1",null,"Running games",-1),K=n("h1",null,"Finished games",-1);j.render=function(e,o,l,i,r,c){const p=a("game-teaser");return s(),t("div",null,[W,(s(!0),t(d,null,u(e.gamesRunning,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),K,(s(!0),t(d,null,u(e.gamesFinished,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var H=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});H.render=function(e,o,l,a,i,r){return s(),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]=c(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var Y=e({name:"image-library",components:{ImageTeaser:H},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});Y.render=function(e,n,o,l,i,r){const c=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,u(e.images,((n,o)=>(s(),t(c,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])};class q{constructor(e){this.rand_high=e||3735929054,this.rand_low=1231121986^e}random(e,t){this.rand_high=(this.rand_high<<16)+(this.rand_high>>16)+this.rand_low&4294967295,this.rand_low=this.rand_low+this.rand_high&4294967295;return e+(this.rand_high>>>0)/4294967295*(t-e+1)|0}choice(e){return e[this.random(0,e.length-1)]}shuffle(e){const t=e.slice();for(let n=0;n<=t.length-2;n++){const e=this.random(n,t.length-1),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 q(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const Q=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},Z=(...e)=>{const t=t=>(...n)=>{const o=new Date,l=Q(o.getHours(),"00"),a=Q(o.getMinutes(),"00"),s=Q(o.getSeconds(),"00");console[t](`${l}:${a}:${s}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var X={hash:e=>{let t=0;for(let n=0;n{let t=e.toLowerCase();return t=t.replace(/[^a-z0-9]+/g,"-"),t=t.replace(/^-|-$/,""),t},uniqId:()=>Date.now().toString(36)+Math.random().toString(36).substring(2),encodeShape:function(e){return e.top+1<<0|e.right+1<<2|e.bottom+1<<4|e.left+1<<6},decodeShape:function(e){return{top:(e>>0&3)-1,right:(e>>2&3)-1,bottom:(e>>4&3)-1,left:(e>>6&3)-1}},encodePiece:function(e){return[e.idx,e.pos.x,e.pos.y,e.z,e.owner,e.group]},decodePiece:function(e){return{idx:e[0],pos:{x:e[1],y:e[2]},z:e[3],owner:e[4],group:e[5]}},encodePlayer:function(e){return[e.id,e.x,e.y,e.d,e.name,e.color,e.bgcolor,e.points,e.ts]},decodePlayer:function(e){return{id:e[0],x:e[1],y:e[2],d:e[3],name:e[4],color:e[5],bgcolor:e[6],points:e[7],ts:e[8]}},encodeGame:function(e){return[e.id,e.rng.type||"",q.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode,e.shapeMode,e.snapMode]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:q.unserialize(e[2])},puzzle:e[3],players:e[4],evtInfos:e[5],scoreMode:e[6],shapeMode:e[7],snapMode:e[8]}},coordByPieceIdx:function(e,t){const n=e.width/e.tileSize;return{x:t%n,y:Math.floor(t/n)}},asQueryArgs:function(e){const t=[];for(const n in e){const o=[n,e[n]].map(encodeURIComponent);t.push(o.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const J={name:"responsive-image",props:{src:String,title:{type:String,default:""},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},computed:{style(){return{display:"inline-block",verticalAlign:"text-bottom",backgroundImage:`url('${this.src}')`,backgroundRepeat:"no-repeat",backgroundSize:"contain",backgroundPosition:"center",width:this.width,height:this.height}}}};J.render=function(e,n,o,l,a,i){return s(),t("div",{style:i.style,title:o.title},null,12,["title"])};var ee=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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 te=m();y("data-v-a4fa5e7e");const ne={key:0,class:"autocomplete"};f();const oe=te(((e,o,a,i,c,m)=>(s(),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?(s(),t("div",ne,[n("ul",null,[(s(!0),t(d,null,u(e.autocomplete.values,((n,o)=>(s(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(s(!0),t(d,null,u(e.values,((n,o)=>(s(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ee.render=oe,ee.__scopeId="data-v-a4fa5e7e";const le=Z("NewImageDialog.vue");var ae=e({name:"new-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const 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(){le.info("onDragleave"),this.droppable=!1}}});const se=n("div",{class:"drop-target"},null,-1),ie={key:0,class:"has-image"},re={key:1},de={class:"upload"},ue=n("span",{class:"btn"},"Upload File",-1),ce={class:"area-settings"},pe=n("td",null,[n("label",null,"Title")],-1),ge=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),he=n("td",null,[n("label",null,"Tags")],-1),me={class:"area-buttons"},ye=i("🖼️ Post to gallery"),fe=i("🧩 Post to gallery "),we=n("br",null,null,-1),ve=i(" + set up game");ae.render=function(e,o,l,u,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),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]=c((()=>{}),["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))},[se,e.previewUrl?(s(),t("div",ie,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",re,[n("label",de,[n("input",{type:"file",style:{display:"none"},onChange:o[2]||(o[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ue])]))],34),n("div",ce,[n("table",null,[n("tr",null,[pe,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]])])]),ge,n("tr",null,[he,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":o[7]||(o[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",me,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:o[8]||(o[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ye],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[fe,we,ve],64))],8,["disabled"])])])])};var be=e({name:"edit-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{image:{type:Object,required:!0},autocompleteTags:{type:Function}},emits:{bgclick:null,saveClick:null},data:()=>({title:"",tags:[]}),created(){this.title=this.image.title,this.tags=this.image.tags.map((e=>e.title))},methods:{saveImage(){this.$emit("saveClick",{id:this.image.id,title:this.title,tags:this.tags})}}});const Ce={class:"area-image"},xe={class:"has-image"},ke={class:"area-settings"},Pe=n("td",null,[n("label",null,"Title")],-1),Ae=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),Se=n("td",null,[n("label",null,"Tags")],-1),ze={class:"area-buttons"};var Te,Ie,De,Ee,Me,Ne,_e,Ve;be.render=function(e,o,l,i,r,d){const u=a("responsive-image"),h=a("tags-input");return s(),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]=c((()=>{}),["stop"]))},[n("div",Ce,[n("div",xe,[n(u,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",ke,[n("table",null,[n("tr",null,[Pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ae,n("tr",null,[Se,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[2]||(o[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",ze,[n("button",{class:"btn",onClick:o[3]||(o[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Ie=Te||(Te={}))[Ie.Flat=0]="Flat",Ie[Ie.Out=1]="Out",Ie[Ie.In=-1]="In",(Ee=De||(De={}))[Ee.FINAL=0]="FINAL",Ee[Ee.ANY=1]="ANY",(Ne=Me||(Me={}))[Ne.NORMAL=0]="NORMAL",Ne[Ne.ANY=1]="ANY",Ne[Ne.FLAT=2]="FLAT",(Ve=_e||(_e={}))[Ve.NORMAL=0]="NORMAL",Ve[Ve.REAL=1]="REAL";var Oe=e({name:"new-game-dialog",components:{ResponsiveImage:J},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:De.ANY,shapeMode:Me.NORMAL,snapMode:_e.NORMAL}),methods:{onNewGameClick(){this.$emit("newGame",{tiles:this.tilesInt,image:this.image,scoreMode:this.scoreModeInt,shapeMode:this.shapeModeInt,snapMode:this.snapModeInt})}},computed:{canStartNewGame(){return!!(this.tilesInt&&this.image&&this.image.url&&[0,1].includes(this.scoreModeInt))},scoreModeInt(){return parseInt(`${this.scoreMode}`,10)},shapeModeInt(){return parseInt(`${this.shapeMode}`,10)},snapModeInt(){return parseInt(`${this.snapMode}`,10)},tilesInt(){return parseInt(`${this.tiles}`,10)}}});const Ue={class:"area-image"},Be={class:"has-image"},Re={key:0,class:"image-title"},Ge={key:0,class:"image-title-title"},$e={key:1,class:"image-title-dim"},Le={class:"area-settings"},Fe=n("td",null,[n("label",null,"Pieces")],-1),je=n("td",null,[n("label",null,"Scoring: ")],-1),We=i(" Any (Score when pieces are connected to each other or on final location)"),Ke=n("br",null,null,-1),He=i(" Final (Score when pieces are put to their final location)"),Ye=n("td",null,[n("label",null,"Shapes: ")],-1),qe=i(" Normal"),Qe=n("br",null,null,-1),Ze=i(" Any (flat pieces can occur anywhere)"),Xe=n("br",null,null,-1),Je=i(" Flat (all pieces flat on all sides)"),et=n("td",null,[n("label",null,"Snapping: ")],-1),tt=i(" Normal (pieces snap to final destination and to each other)"),nt=n("br",null,null,-1),ot=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),lt={class:"area-buttons"};Oe.render=function(e,o,i,d,u,h){const m=a("responsive-image");return s(),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]=c((()=>{}),["stop"]))},[n("div",Ue,[n("div",Be,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",Re,[e.image.title?(s(),t("span",Ge,'"'+r(e.image.title)+'"',1)):l("",!0),e.image.width||e.image.height?(s(),t("span",$e,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):l("",!0)])):l("",!0)]),n("div",Le,[n("table",null,[n("tr",null,[Fe,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,[je,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),[[w,e.scoreMode]]),We]),Ke,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[3]||(o[3]=t=>e.scoreMode=t),value:"0"},null,512),[[w,e.scoreMode]]),He])])]),n("tr",null,[Ye,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),[[w,e.shapeMode]]),qe]),Qe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[5]||(o[5]=t=>e.shapeMode=t),value:"1"},null,512),[[w,e.shapeMode]]),Ze]),Xe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[6]||(o[6]=t=>e.shapeMode=t),value:"2"},null,512),[[w,e.shapeMode]]),Je])])]),n("tr",null,[et,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),[[w,e.snapMode]]),tt]),nt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":o[8]||(o[8]=t=>e.snapMode=t),value:"1"},null,512),[[w,e.snapMode]]),ot])])])])]),n("div",lt,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};const at=async(e,t,n)=>new Promise(((o,l)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.addEventListener("load",(function(e){o({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){l(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body)}));var st=(e,t)=>at("post",e,t),it=e({components:{ImageLibrary:Y,NewImageDialog:ae,EditImageDialog:be,NewGameDialog:Oe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await fetch(`/api/newgame-data${X.asQueryArgs(this.filters)}`),t=await e.json();this.images=t.images,this.tags=t.tags},async filtersChanged(){await this.loadImages()},onImageClicked(e){this.image=e,this.dialog="new-game"},onImageEditClicked(e){this.image=e,this.dialog="edit-image"},async uploadImage(e){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await st("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await fetch("/api/save-image",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({id:e.id,title:e.title,tags:e.tags})});return await t.json()},async onSaveImageClick(e){await this.saveImage(e),this.dialog="",await this.loadImages()},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await fetch("/api/newgame",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)});if(200===t.status){const e=await t.json();this.$router.push({name:"game",params:{id:e.id}})}}}});const rt={class:"upload-image-teaser"},dt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ut={key:0},ct=i(" Tags: "),pt=i(" Sort by: "),gt=n("option",{value:"date_desc"},"Newest first",-1),ht=n("option",{value:"date_asc"},"Oldest first",-1),mt=n("option",{value:"alpha_asc"},"A-Z",-1),yt=n("option",{value:"alpha_desc"},"Z-A",-1);it.render=function(e,o,i,c,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),w=a("new-game-dialog");return s(),t("div",null,[n("div",rt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),dt]),n("div",null,[e.tags.length>0?(s(),t("label",ut,[ct,(s(!0),t(d,null,u(e.relevantTags,((n,o)=>(s(),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,[pt,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))},[gt,ht,mt,yt],544),[[v,e.filters.sort]])])]),n(m,{images:e.images,onImageClicked:e.onImageClicked,onImageEditClicked:e.onImageEditClicked},null,8,["images","onImageClicked","onImageEditClicked"]),"new-image"===e.dialog?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(s(),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?(s(),t(w,{key:2,onBgclick:o[6]||(o[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):l("",!0)])};var ft=e({name:"scores",props:{activePlayers:{type:Array,required:!0},idlePlayers:{type:Array,required:!0}},computed:{actives(){return this.activePlayers.sort(((e,t)=>t.points-e.points)),this.activePlayers},idles(){return this.idlePlayers.sort(((e,t)=>t.points-e.points)),this.idlePlayers}}});const wt={class:"scores"},vt=n("div",null,"Scores",-1),bt=n("td",null,"⚡",-1),Ct=n("td",null,"💤",-1);ft.render=function(e,o,l,a,i,c){return s(),t("div",wt,[vt,n("table",null,[(s(!0),t(d,null,u(e.actives,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[bt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,u(e.idles,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[Ct,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var xt=e({name:"puzzle-status",props:{finished:{type:Boolean,required:!0},duration:{type:Number,required:!0},piecesDone:{type:Number,required:!0},piecesTotal:{type:Number,required:!0}},computed:{icon(){return this.finished?"🏁":"⏳"},durationStr(){return U(this.duration)}}});const kt={class:"timer"};xt.render=function(e,o,l,a,i,d){return s(),t("div",kt,[n("div",null," 🧩 "+r(e.piecesDone)+"/"+r(e.piecesTotal),1),n("div",null,r(e.icon)+" "+r(e.durationStr),1),b(e.$slots,"default")])};var Pt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const At=m();y("data-v-4d56fc17");const St=n("td",null,[n("label",null,"Background: ")],-1),zt=n("td",null,[n("label",null,"Color: ")],-1),Tt=n("td",null,[n("label",null,"Name: ")],-1),It=n("td",null,[n("label",null,"Sounds: ")],-1),Dt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Et={class:"sound-volume"},Mt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Nt=At(((e,o,l,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:o[10]||(o[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[9]||(o[9]=c((()=>{}),["stop"]))},[n("tr",null,[St,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,[zt,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,[Tt,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,[It,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Dt,n("td",Et,[n("span",{onClick:o[5]||(o[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:o[6]||(o[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:o[7]||(o[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Mt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[8]||(o[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));Pt.render=Nt,Pt.__scopeId="data-v-4d56fc17";var _t=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const Vt={class:"preview"};_t.render=function(e,o,l,a,i,r){return s(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",Vt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Ot=1,Ut=4,Bt=2,Rt=3,Gt=2,$t=4,Lt=3,Ft=9,jt=1,Wt=2,Kt=3,Ht=4,Yt=5,qt=6,Qt=7,Zt=8,Xt=10,Jt=11,en=12,tn=13,nn=14,on=15,ln=16,an=1,sn=2,rn=3;const dn=Z("Communication.js");let un,cn=[],pn=e=>{cn.push(e)},gn=[],hn=e=>{gn.push(e)};let mn=0;const yn=e=>{mn!==e&&(mn=e,hn(e))};function fn(e){if(2===mn)try{un.send(JSON.stringify(e))}catch(t){dn.info("unable to send message.. maybe because ws is invalid?")}}let wn,vn;var bn={connect:function(e,t,n){return wn=0,vn={},yn(3),new Promise((o=>{un=new WebSocket(e,n+"|"+t),un.onopen=()=>{yn(2),fn([Rt])},un.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===Ut){const e=t[1];o(e)}else{if(l!==Ot)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&vn[o])return void delete vn[o];pn(t)}}},un.onerror=()=>{throw yn(1),"[ 2021-05-15 onerror ]"},un.onclose=e=>{4e3===e.code||1001===e.code?yn(4):yn(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},o=await fetch(`/api/replay-data${X.asQueryArgs(n)}`);return await o.json()},disconnect:function(){un&&un.close(4e3),wn=0,vn={}},sendClientEvent:function(e){wn++,vn[wn]=e,fn([Bt,wn,vn[wn]])},onServerChange:function(e){pn=e;for(const t of cn)pn(t);cn=[]},onConnectionStateChange:function(e){hn=e;for(const t of gn)hn(t);gn=[]},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},Cn=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===bn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===bn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const xn={key:0,class:"overlay connection-lost"},kn={key:0,class:"overlay-content"},Pn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),An={key:1,class:"overlay-content"},Sn=n("div",null,"Connecting...",-1);Cn.render=function(e,o,a,i,r,d){return e.show?(s(),t("div",xn,[e.lostConnection?(s(),t("div",kn,[Pn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(s(),t("div",An,[Sn])):l("",!0)])):l("",!0)};var zn=e({name:"help-overlay",emits:{bgclick:null}});const Tn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),In=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Dn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),En=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Mn=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Nn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),_n=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),Vn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),On=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Un=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),Rn=n("tr",null,[n("td",null,"👤 Toggle player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Gn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),$n=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),Ln=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),Fn=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);zn.render=function(e,o,l,a,i,r){return s(),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]=c((()=>{}),["stop"]))},[Tn,In,Dn,En,Mn,Nn,_n,Vn,On,Un,Bn,Rn,Gn,$n,Ln,Fn])])};var jn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),Wn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),Kn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Hn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),Yn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function qn(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var Qn={createCanvas:qn,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=qn(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=qn(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 Zn=Z("Debug.js");let Xn=0,Jn=0;var eo=e=>{Xn=performance.now(),Jn=e},to=e=>{const t=performance.now(),n=t-Xn;n>Jn&&Zn.log(e+": "+n),Xn=t};function no(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function oo(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var lo={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:no,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:oo,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 no(oo(e),oo(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 ao=Z("PuzzleGraphics.js");function so(e,t){const n=X.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var io={loadPuzzleBitmaps:async function(e){const t=await Qn.loadImageToBitmap(e.info.imageUrl),n=await Qn.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){ao.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,s=o/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function u(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=lo.pointAdd(a,{x:o,y:0}),u=lo.pointAdd(r,{x:0,y:o}),c=lo.pointSub(u,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oX.decodePiece(ro[e].puzzle.tiles[t]),Po=(e,t)=>ko(e,t).group,Ao=(e,t)=>{const n=ro[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},So=(e,t)=>{const n=ro[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=ro[e].puzzle.info,o=X.coordByPieceIdx(n,t),l=o.x*n.tileSize,a=o.y*n.tileSize;return{x:l,y:a}}(e,t);return lo.pointAdd(o,l)},zo=(e,t)=>ko(e,t).pos,To=e=>{const t=Wo(e),n=Ko(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=No(e),o=ko(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},Do=(e,t)=>ko(e,t).z,Eo=(e,t)=>{for(const n of ro[e].puzzle.tiles){const e=X.decodePiece(n);if(e.owner===t)return e.idx}return-1},Mo=e=>ro[e].puzzle.info.tileDrawSize,No=e=>ro[e].puzzle.info.tileSize,_o=e=>ro[e].puzzle.data.maxGroup,Vo=e=>ro[e].puzzle.data.maxZ;function Oo(e,t){const n=ro[e].puzzle.info,o=X.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const Uo=(e,t,n)=>{for(const o of t)xo(e,o,{z:n})},Bo=(e,t,n)=>{const o=zo(e,t);xo(e,t,{pos:lo.pointAdd(o,n)})},Ro=(e,t,n)=>{const o=Mo(e),l=To(e),a=n;for(const s of t){const t=ko(e,s);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 s of t)Bo(e,s,a)},Go=(e,t)=>ko(e,t).owner,$o=(e,t)=>{for(const n of t)xo(e,n,{owner:-1,z:1})},Lo=(e,t,n)=>{for(const o of t)xo(e,o,{owner:n})};function Fo(e,t){const n=ro[e].puzzle.tiles,o=X.decodePiece(n[t]),l=[];if(o.group)for(const a of n){const e=X.decodePiece(a);e.group===o.group&&l.push(e.idx)}else l.push(o.idx);return l}const jo=(e,t)=>{const n=co(e,t);return n?n.points:0},Wo=e=>ro[e].puzzle.info.table.width,Ko=e=>ro[e].puzzle.info.table.height;var Ho={setGame:function(e,t){ro[e]=t},exists:function(e){return!!ro[e]||!1},playerExists:go,getActivePlayers:function(e,t){const n=t-30*_;return ho(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*_;return ho(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){go(e,t)?bo(e,t,{ts:n}):po(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:vo,getPieceCount:mo,getImageUrl:function(e){return ro[e].puzzle.info.imageUrl},setImageUrl:function(e,t){ro[e].puzzle.info.imageUrl=t},get:function(e){return ro[e]||null},getAllGames:function(){return Object.values(ro).sort(((e,t)=>wo(e.id)===wo(t.id)?t.puzzle.data.started-e.puzzle.data.started:wo(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=co(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=co(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=co(e,t);return n?n.name:null},getPlayerIndexById:uo,getPlayerIdByIndex:function(e,t){return ro[e].players.length>t?X.decodePlayer(ro[e].players[t]).id:null},changePlayer:bo,setPlayer:po,setPiece:function(e,t,n){ro[e].puzzle.tiles[t]=X.encodePiece(n)},setPuzzleData:function(e,t){ro[e].puzzle.data=t},getTableWidth:Wo,getTableHeight:Ko,getPuzzle:e=>ro[e].puzzle,getRng:e=>ro[e].rng.obj,getPuzzleWidth:e=>ro[e].puzzle.info.width,getPuzzleHeight:e=>ro[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return ro[e].puzzle.tiles.map(X.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Eo(e,t);return n<0?null:ro[e].puzzle.tiles[n]},getPieceDrawOffset:e=>ro[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Mo,getFinalPiecePos:So,getStartTs:e=>ro[e].puzzle.data.started,getFinishTs:e=>ro[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=ro[e].puzzle,s=function(e,t){return t in ro[e].evtInfos?ro[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([an,a.data])},d=t=>{i.push([sn,X.encodePiece(ko(e,t))])},u=e=>{for(const t of e)d(t)},c=()=>{const n=co(e,t);n&&i.push([rn,X.encodePlayer(n)])},p=n[0];if(p===qt){const l=n[1];bo(e,t,{bgcolor:l,ts:o}),c()}else if(p===Qt){const l=n[1];bo(e,t,{color:l,ts:o}),c()}else if(p===Zt){const l=`${n[1]}`.substr(0,16);bo(e,t,{name:l,ts:o}),c()}else if(p===Ft){const l=n[1],a=n[2],s=co(e,t);if(s){const n=s.x-l,i=s.y-a;bo(e,t,{ts:o,x:n,y:i}),c()}}else if(p===jt){const l={x:n[1],y:n[2]};bo(e,t,{d:1,ts:o}),c(),s._last_mouse_down=l;const a=((e,t)=>{const n=ro[e].puzzle.info,o=ro[e].puzzle.tiles;let l=-1,a=-1;for(let s=0;sl)&&(l=e.z,a=s)}return a})(e,l);if(a>=0){const n=Vo(e)+1;Co(e,{maxZ:n}),r();const o=Fo(e,a);Uo(e,o,Vo(e)),Lo(e,o,t),u(o)}s._last_mouse=l}else if(p===Kt){const l=n[1],a=n[2],i={x:l,y:a};if(null===s._last_mouse_down)bo(e,t,{x:l,y:a,ts:o}),c();else{const n=Eo(e,t);if(n>=0){bo(e,t,{x:l,y:a,ts:o}),c();const r=Fo(e,n);let d=lo.pointInBounds(i,To(e))&&lo.pointInBounds(s._last_mouse_down,To(e));for(const t of r){const n=Io(e,t);if(lo.pointInBounds(i,n)){d=!0;break}}if(d){const t=l-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Ro(e,r,{x:t,y:n}),u(r)}}else bo(e,t,{ts:o}),c();s._last_mouse_down=i}s._last_mouse=i}else if(p===Wt){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Eo(e,t);if(g>=0){const n=Fo(e,g);Lo(e,n,0),u(n);const s=zo(e,g),i=So(e,g);let h=!1;if(fo(e)===_e.REAL){for(const t of n)if(Ao(e,t)){h=!0;break}}else h=!0;if(h&&lo.pointDistance(i,s){const l=ro[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=Po(e,t),l=Po(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=zo(e,t),s=lo.pointAdd(zo(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(lo.pointDistance(a,s){const o=ro[e].puzzle.tiles,l=Po(e,t),a=Po(e,n);let s;const i=[];l&&i.push(l),a&&i.push(a),l?s=l:a?s=a:(Co(e,{maxGroup:_o(e)+1}),r(),s=_o(e));if(xo(e,t,{group:s}),d(t),xo(e,n,{group:s}),d(n),i.length>0)for(const r of o){const t=X.decodePiece(r);i.includes(t.group)&&(xo(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),l=Fo(e,t),((e,t)=>-1===Go(e,t))(e,n))$o(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=Do(e,o);t>n&&(n=t)}return n})(e,l);Uo(e,l,t)}return u(l),!0}return!1};let a=!1;for(const t of Fo(e,g)){const o=Oo(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&&yo(e)===De.ANY){const n=jo(e,t)+1;bo(e,t,{d:p,ts:o,points:n}),c()}else bo(e,t,{d:p,ts:o}),c();a&&fo(e)===_e.REAL&&vo(e)===mo(e)&&(Co(e,{finished:o}),r()),a&&l&&l(t)}}else bo(e,t,{d:p,ts:o}),c();s._last_mouse=i}else if(p===Ht){const l=n[1],a=n[2];bo(e,t,{x:l,y:a,ts:o}),c(),s._last_mouse={x:l,y:a}}else if(p===Yt){const l=n[1],a=n[2];bo(e,t,{x:l,y:a,ts:o}),c(),s._last_mouse={x:l,y:a}}else bo(e,t,{ts:o}),c();return function(e,t,n){ro[e].evtInfos[t]=n}(e,t,s),i}};let Yo=-10,qo=20,Qo=2,Zo=15;class Xo{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=Yo+Math.random()*qo,this.vy=-1*(Qo+Math.random()*Zo),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;Qo=t/2,Zo=t-Qo;const n=1/4*this.canvas.width/(t/2);Yo=-n,qo=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new Xo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new Xo(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{localStorage.setItem(e,t)},rl=e=>localStorage.getItem(e);var dl=(e,t)=>{il(e,`${t}`)},ul=(e,t)=>{const n=rl(e);if(null===n)return t;const o=parseInt(n,10);return isNaN(o)?t:o},cl=(e,t)=>{il(e,t?"1":"0")},pl=(e,t)=>{const n=rl(e);return null===n?t:"1"===n},gl=(e,t)=>{il(e,t)},hl=(e,t)=>{const n=rl(e);return null===n?t:n};const ml={"./grab.png":Wn,"./grab_mask.png":Kn,"./hand.png":Hn,"./hand_mask.png":Yn},yl={"./click.mp3":jn};let fl=!0,wl=!0;let vl=!0;async function bl(e,t,n,o,l,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=yl["./click.mp3"].default,i=new Audio(s),r=await Qn.loadImageToBitmap(ml["./grab.png"].default),d=await Qn.loadImageToBitmap(ml["./hand.png"].default),u=await Qn.loadImageToBitmap(ml["./grab_mask.png"].default),c=await Qn.loadImageToBitmap(ml["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?u:c;y[t]=await createImageBitmap(Qn.colorizedCanvas(n,o,e.color))}else y[t]=n}return y[t]},w=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,vl=!0})),t}(l,Qn.createCanvas()),v={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};bn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=v.dataOffset;v.dataOffset+=1e4;const n=await bn.requestReplayData(e,t);return v.log=v.log.slice(v.logPointer),v.logPointer=0,v.log.push(...n.log),0===n.log.length&&(v.final=!0),n};let C=()=>0;const x=async()=>{if("play"===o){const o=await bn.connect(n,e,t),l=X.decodeGame(o);Ho.setGame(l.id,l),C=()=>V()}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=X.decodeGame(t.game);Ho.setGame(n.id,n),v.lastRealTs=V(),v.gameStartTs=parseInt(t.log[0][4],10),v.lastGameTs=v.gameStartTs,C=()=>v.lastGameTs}}vl=!0};await x();const k=Ho.getPieceDrawOffset(e),P=Ho.getPieceDrawSize(e),A=Ho.getPuzzleWidth(e),S=Ho.getPuzzleHeight(e),z=Ho.getTableWidth(e),T=Ho.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},D={w:A,h:S},E={w:P,h:P},M=await io.loadPuzzleBitmaps(Ho.getPuzzle(e)),_=new el(w,Ho.getRng(e));_.init();const O=w.getContext("2d");w.classList.add("loaded"),a.setPuzzleCut();const U=function(){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=(e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0},s=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>a(l(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),B=()=>{U.reset(),U.move(-(z-w.width)/2,-(T-w.height)/2);const e=U.worldDimToViewport(D),t=w.width-40,n=w.height-40;if(e.w>t||e.h>n||e.w{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?c=e:"KeyE"===t.code&&(u=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&w([jt,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&w([Wt,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),w([Kt,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Ht:Yt;w([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&w([Xt]),"replay"===o&&("KeyI"===e.code&&w([tn]),"KeyO"===e.code&&w([nn]),"KeyP"===e.code&&w([en])),"KeyF"===e.code&&(fl=!fl,vl=!0),"KeyG"===e.code&&(wl=!wl,vl=!0),"KeyM"===e.code&&w([Jt]),"KeyN"===e.code&&w([on]),"KeyC"===e.code&&w([ln]))}));const w=e=>{l.push(e)};return{addEvent:w,consumeAll:()=>{if(0===l.length)return[];const e=l.slice();return l=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const o=(p?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});w([Ft,l.w,l.h]),f&&(f[0]-=l.w,f[1]-=l.h)}if(u&&c);else if(u){if(n.canZoom("in")){const e=f||m();w([Ht,...e])}}else if(c&&n.canZoom("out")){const e=f||m();w([Yt,...e])}},setHotkeys:e=>{a=e}}}(w,window,U,o),G=Ho.getImageUrl(e),$=()=>{const t=Ho.getStartTs(e),n=Ho.getFinishTs(e),o=C();a.setFinished(!!n),a.setDuration((n||o)-t)};$(),a.setPiecesDone(Ho.getFinishedPiecesCount(e)),a.setPiecesTotal(Ho.getPieceCount(e));const L=C();a.setActivePlayers(Ho.getActivePlayers(e,L)),a.setIdlePlayers(Ho.getIdlePlayers(e,L));const F=!!Ho.getFinishTs(e);let j=F;const W=()=>j&&!F,K=()=>ul(tl,100),H=()=>pl(nl,!1),Y=()=>pl(sl,!0),q=()=>{const e=K();i.volume=e/100,i.play()},Q=()=>"replay"===o?hl(ol,"#222222"):Ho.getPlayerBgColor(e,t)||hl(ol,"#222222"),Z=()=>"replay"===o?hl(ll,"#ffffff"):Ho.getPlayerColor(e,t)||hl(ll,"#ffffff");let J="",ee="",te=!1;const ne=e=>{te=e;const[t,n]=e?[J,"grab"]:[ee,"default"];w.style.cursor=`url('${t}') ${g} ${m}, ${n}`},oe=e=>{J=Qn.colorizedCanvas(r,u,e).toDataURL(),ee=Qn.colorizedCanvas(d,c,e).toDataURL(),ne(te)};oe(Z());const le=()=>{a.setReplaySpeed&&a.setReplaySpeed(v.speeds[v.speedIdx]),a.setReplayPaused&&a.setReplayPaused(v.paused)},ae=()=>{v.speedIdx+1{v.speedIdx>=1&&(v.speedIdx--,le())},ie=()=>{v.paused=!v.paused,le()},re=[];let de;let ue;if("play"===o?re.push(setInterval((()=>{$()}),1e3)):"replay"===o&&le(),"play"===o)bn.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case rn:{const n=X.decodePlayer(a);n.id!==t&&(Ho.setPlayer(e,n.id,n),vl=!0)}break;case sn:{const t=X.decodePiece(a);Ho.setPiece(e,t.idx,t),vl=!0}break;case an:Ho.setPuzzleData(e,a),vl=!0}j=!!Ho.getFinishTs(e)}));else if("replay"===o){const t=(t,n)=>{const o=t;if(o[0]===Gt){const t=o[1];return Ho.addPlayer(e,t,n),!0}if(o[0]===$t){const t=Ho.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return Ho.addPlayer(e,t,n),!0}if(o[0]===Lt){const t=Ho.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const l=o[2];return Ho.handleInput(e,t,l,n),!0}return!1};let n=v.lastGameTs;const o=async()=>{v.logPointer+1>=v.log.length&&await b(e);const l=V();if(v.paused)return v.lastRealTs=l,void(de=setTimeout(o,50));const a=(l-v.lastRealTs)*v.speeds[v.speedIdx];let s=v.lastGameTs+a;for(;;){if(v.paused)break;const e=v.logPointer+1;if(e>=v.log.length)break;const o=v.log[v.logPointer],l=n+o[o.length-1],a=v.log[e],i=a[a.length-1],r=l+i;if(r>s){s+500*N{let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=o*i;let d,u=0,c=window.performance.now();const p=()=>{for(d=window.performance.now(),u+=Math.min(1,(d-c)/1e3);u>r;)u-=r,l(i);a(u/o),c=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===o){const o=n[0];if(o===Ft){const e=n[1],t=n[2],o=U.worldDimToViewport({w:e,h:t});vl=!0,U.move(o.w,o.h)}else if(o===Kt){if(ce&&!Ho.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=U.worldToViewport(e),o=Math.round(t.x-ce.x),l=Math.round(t.y-ce.y);vl=!0,U.move(o,l),ce=t}}else if(o===Qt)oe(n[1]);else if(o===jt){const e={x:n[1],y:n[2]};ce=U.worldToViewport(e),ne(!0)}else if(o===Wt)ce=null,ne(!1);else if(o===Ht){const e={x:n[1],y:n[2]};vl=!0,U.zoom("in",U.worldToViewport(e))}else if(o===Yt){const e={x:n[1],y:n[2]};vl=!0,U.zoom("out",U.worldToViewport(e))}else o===Xt?a.togglePreview():o===Jt?a.toggleSoundsEnabled():o===on?a.togglePlayerNames():o===ln&&B();const l=C();Ho.handleInput(e,t,n,l,(e=>{H()&&q()})).length>0&&(vl=!0),bn.sendClientEvent(n)}else if("replay"===o){const e=n[0];if(e===en)ie();else if(e===nn)se();else if(e===tn)ae();else if(e===Ft){const e=n[1],t=n[2];vl=!0,U.move(e,t)}else if(e===Kt){if(ce){const e={x:n[1],y:n[2]},t=U.worldToViewport(e),o=Math.round(t.x-ce.x),l=Math.round(t.y-ce.y);vl=!0,U.move(o,l),ce=t}}else if(e===Qt)oe(n[1]);else if(e===jt){const e={x:n[1],y:n[2]};ce=U.worldToViewport(e),ne(!0)}else if(e===Wt)ce=null,ne(!1);else if(e===Ht){const e={x:n[1],y:n[2]};vl=!0,U.zoom("in",U.worldToViewport(e))}else if(e===Yt){const e={x:n[1],y:n[2]};vl=!0,U.zoom("out",U.worldToViewport(e))}else e===Xt?a.togglePreview():e===Jt?a.toggleSoundsEnabled():e===on?a.togglePlayerNames():e===ln&&B()}j=!!Ho.getFinishTs(e),W()&&(_.update(),vl=!0)},render:async()=>{if(!vl)return;const n=C();let l,s,i;window.DEBUG&&eo(0),O.fillStyle=Q(),O.fillRect(0,0,w.width,w.height),window.DEBUG&&to("clear done"),l=U.worldToViewportRaw(I),s=U.worldDimToViewportRaw(D),O.fillStyle="rgba(255, 255, 255, .3)",O.fillRect(l.x,l.y,s.w,s.h),window.DEBUG&&to("board done");const r=Ho.getPiecesSortedByZIndex(e);window.DEBUG&&to("get tiles done"),s=U.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?fl:wl)&&(i=M[e.idx],l=U.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),O.drawImage(i,0,0,i.width,i.height,l.x,l.y,s.w,s.h));window.DEBUG&&to("tiles done");const d=[];for(const a of Ho.getActivePlayers(e,n))u=a,("replay"===o||u.id!==t)&&(i=await f(a),l=U.worldToViewport(a),O.drawImage(i,l.x-g,l.y-m),Y()&&d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var u;O.fillStyle="white",O.textAlign="center";for(const[e,t,o]of d)O.fillText(e,t,o);window.DEBUG&&to("players done"),a.setActivePlayers(Ho.getActivePlayers(e,n)),a.setIdlePlayers(Ho.getIdlePlayers(e,n)),a.setPiecesDone(Ho.getFinishedPiecesCount(e)),window.DEBUG&&to("HUD done"),W()&&_.render(),vl=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{gl(ol,e),R.addEvent([qt,e])},onColorChange:e=>{gl(ll,e),R.addEvent([Qt,e])},onNameChange:e=>{gl(al,e),R.addEvent([Zt,e])},onSoundsEnabledChange:e=>{cl(nl,e)},onSoundsVolumeChange:e=>{dl(tl,e),q()},onShowPlayerNamesChange:e=>{cl(sl,e)},replayOnSpeedUp:ae,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:G,player:{background:Q(),color:Z(),name:"replay"===o?hl(al,"anon"):Ho.getPlayerName(e,t)||hl(al,"anon"),soundsEnabled:H(),soundsVolume:K(),showPlayerNames:Y()},disconnect:bn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ue&&ue.stop()}}}var Cl=e({name:"game",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,ConnectionOverlay:Cn,HelpOverlay:zn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await bl(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const xl={id:"game"},kl={key:0,class:"overlay"},Pl=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Al={class:"menu"},Sl={class:"tabs"},zl=i("🧩 Puzzles");Cl.render=function(e,i,r,d,u,c){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("help-overlay"),y=a("connection-overlay"),f=a("puzzle-status"),w=a("router-link"),v=a("scores");return s(),t("div",xl,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),p(n(m,{onBgclick:i[4]||(i[4]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",kl,[Pl])):l("",!0),n(y,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(f,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Al,[n("div",Sl,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[zl])),_:1}),n("div",{class:"opener",onClick:i[5]||(i[5]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("help",!0))},"ℹ️ Hotkeys")])]),n(v,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Tl=e({name:"replay",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,HelpOverlay:zn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await bl(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Il={id:"replay"},Dl={key:0,class:"overlay"},El=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Ml={class:"menu"},Nl={class:"tabs"},_l=i("🧩 Puzzles");Tl.render=function(e,i,d,u,c,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("help-overlay"),f=a("puzzle-status"),w=a("router-link"),v=a("scores");return s(),t("div",Il,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),p(n(y,{onBgclick:i[4]||(i[4]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Dl,[El])):l("",!0),n(f,{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:i[5]||(i[5]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Ml,[n("div",Nl,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[_l])),_:1}),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("help",!0))},"ℹ️ Hotkeys")])]),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:P(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:it},{name:"game",path:"/g/:id",component:Cl},{name:"replay",path:"/replay/:id",component:Tl}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const o=A(S);o.config.globalProperties.$config=t,o.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=X.uniqId(),localStorage.setItem("ID",e)),e}(),o.use(n),o.mount("#app")})(); diff --git a/build/public/assets/index.93936dee.js b/build/public/assets/index.93936dee.js new file mode 100644 index 0000000..e6ab743 --- /dev/null +++ b/build/public/assets/index.93936dee.js @@ -0,0 +1 @@ +import{d as e,c as t,a as n,w as l,b as o,r as a,o as s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),M=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:l((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:l((()=>[M])),_:1})])])):o("",!0),n(g)])};const E=864e5,D=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const l=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${l}m ${Math.floor(e/1e3)}s`};var N=1,_=1e3,V=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},O=(e,t)=>D(t-e),B=D,U=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",l=e,o=t||V();return`${n} ${O(l,o)}`}}});const R={class:"game-info-text"},$=n("br",null,null,-1),G=n("br",null,null,-1),L=n("br",null,null,-1),F=i(" ↪️ Watch replay ");U.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:l((()=>[n("span",R,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),$,i(" 👥 "+r(e.game.players),1),G,i(" "+r(e.time(e.game.started,e.game.finished)),1),L])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:l((()=>[F])),_:1},8,["to"])):o("",!0)],4)};var j=e({components:{GameTeaser:U},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await fetch("/api/index-data"),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const W=n("h1",null,"Running games",-1),K=n("h1",null,"Finished games",-1);j.render=function(e,l,o,i,r,u){const p=a("game-teaser");return s(),t("div",null,[W,(s(!0),t(d,null,c(e.gamesRunning,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128)),K,(s(!0),t(d,null,c(e.gamesFinished,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128))])};var H=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});H.render=function(e,l,o,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:l[2]||(l[2]=(...t)=>e.onClick&&e.onClick(...t))},[n("div",{class:"btn edit",onClick:l[1]||(l[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var Y=e({name:"image-library",components:{ImageTeaser:H},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});Y.render=function(e,n,l,o,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,l)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:l},null,8,["image","onClick","onEditClick"])))),128))])};class q{constructor(e){this.rand_high=e||3735929054,this.rand_low=1231121986^e}random(e,t){this.rand_high=(this.rand_high<<16)+(this.rand_high>>16)+this.rand_low&4294967295,this.rand_low=this.rand_low+this.rand_high&4294967295;return e+(this.rand_high>>>0)/4294967295*(t-e+1)|0}choice(e){return e[this.random(0,e.length-1)]}shuffle(e){const t=e.slice();for(let n=0;n<=t.length-2;n++){const e=this.random(n,t.length-1),l=t[n];t[n]=t[e],t[e]=l}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new q(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const Q=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},Z=(...e)=>{const t=t=>(...n)=>{const l=new Date,o=Q(l.getHours(),"00"),a=Q(l.getMinutes(),"00"),s=Q(l.getSeconds(),"00");console[t](`${o}:${a}:${s}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var X={hash:e=>{let t=0;for(let n=0;n{let t=e.toLowerCase();return t=t.replace(/[^a-z0-9]+/g,"-"),t=t.replace(/^-|-$/,""),t},uniqId:()=>Date.now().toString(36)+Math.random().toString(36).substring(2),encodeShape:function(e){return e.top+1<<0|e.right+1<<2|e.bottom+1<<4|e.left+1<<6},decodeShape:function(e){return{top:(e>>0&3)-1,right:(e>>2&3)-1,bottom:(e>>4&3)-1,left:(e>>6&3)-1}},encodePiece:function(e){return[e.idx,e.pos.x,e.pos.y,e.z,e.owner,e.group]},decodePiece:function(e){return{idx:e[0],pos:{x:e[1],y:e[2]},z:e[3],owner:e[4],group:e[5]}},encodePlayer:function(e){return[e.id,e.x,e.y,e.d,e.name,e.color,e.bgcolor,e.points,e.ts]},decodePlayer:function(e){return{id:e[0],x:e[1],y:e[2],d:e[3],name:e[4],color:e[5],bgcolor:e[6],points:e[7],ts:e[8]}},encodeGame:function(e){return[e.id,e.rng.type||"",q.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode,e.shapeMode,e.snapMode]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:q.unserialize(e[2])},puzzle:e[3],players:e[4],evtInfos:e[5],scoreMode:e[6],shapeMode:e[7],snapMode:e[8]}},coordByPieceIdx:function(e,t){const n=e.width/e.tileSize;return{x:t%n,y:Math.floor(t/n)}},asQueryArgs:function(e){const t=[];for(const n in e){const l=[n,e[n]].map(encodeURIComponent);t.push(l.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const J={name:"responsive-image",props:{src:String,title:{type:String,default:""},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},computed:{style(){return{display:"inline-block",verticalAlign:"text-bottom",backgroundImage:`url('${this.src}')`,backgroundRepeat:"no-repeat",backgroundSize:"contain",backgroundPosition:"center",width:this.width,height:this.height}}}};J.render=function(e,n,l,o,a,i){return s(),t("div",{style:i.style,title:l.title},null,12,["title"])};var ee=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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 te=m();y("data-v-a4fa5e7e");const ne={key:0,class:"autocomplete"};f();const le=te(((e,l,a,i,u,m)=>(s(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.input=t),placeholder:"Plants, People",onChange:l[2]||(l[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:l[3]||(l[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:l[4]||(l[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(s(),t("div",ne,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,l)=>(s(),t("li",{key:l,class:{active:l===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):o("",!0),(s(!0),t(d,null,c(e.values,((n,l)=>(s(),t("span",{key:l,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ee.render=le,ee.__scopeId="data-v-a4fa5e7e";const oe=Z("NewImageDialog.vue");var ae=e({name:"new-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const l=n[0];return l.type.startsWith("image/")?l:null},onFileSelect(e){const t=e.target;if(!t.files)return;const n=t.files[0];n&&this.preview(n)},preview(e){const t=new FileReader;t.readAsDataURL(e),t.onload=t=>{this.previewUrl=t.target.result,this.file=e}},postToGallery(){this.$emit("postToGalleryClick",{file:this.file,title:this.title,tags:this.tags})},setupGameClick(){this.$emit("setupGameClick",{file:this.file,title:this.title,tags:this.tags})},onDrop(e){this.droppable=!1;const t=this.imageFromDragEvt(e);if(!t)return!1;const n=t.getAsFile();return!!n&&(this.file=n,this.preview(n),e.preventDefault(),!1)},onDragover(e){return!!this.imageFromDragEvt(e)&&(this.droppable=!0,e.preventDefault(),!1)},onDragleave(){oe.info("onDragleave"),this.droppable=!1}}});const se=n("div",{class:"drop-target"},null,-1),ie={key:0,class:"has-image"},re={key:1},de={class:"upload"},ce=n("span",{class:"btn"},"Upload File",-1),ue={class:"area-settings"},pe=n("td",null,[n("label",null,"Title")],-1),ge=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),he=n("td",null,[n("label",null,"Tags")],-1),me={class:"area-buttons"},ye=i("🖼️ Post to gallery"),fe=i("🧩 Post to gallery "),ve=n("br",null,null,-1),we=i(" + set up game");ae.render=function(e,l,o,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),t("div",{class:"overlay new-image-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:l[3]||(l[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:l[4]||(l[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:l[5]||(l[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[se,e.previewUrl?(s(),t("div",ie,[n("span",{class:"remove btn",onClick:l[1]||(l[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",re,[n("label",de,[n("input",{type:"file",style:{display:"none"},onChange:l[2]||(l[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ce])]))],34),n("div",ue,[n("table",null,[n("tr",null,[pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[6]||(l[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),ge,n("tr",null,[he,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":l[7]||(l[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",me,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:l[8]||(l[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ye],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:l[9]||(l[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[fe,ve,we],64))],8,["disabled"])])])])};var be=e({name:"edit-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{image:{type:Object,required:!0},autocompleteTags:{type:Function}},emits:{bgclick:null,saveClick:null},data:()=>({title:"",tags:[]}),created(){this.title=this.image.title,this.tags=this.image.tags.map((e=>e.title))},methods:{saveImage(){this.$emit("saveClick",{id:this.image.id,title:this.title,tags:this.tags})}}});const Ce={class:"area-image"},xe={class:"has-image"},ke={class:"area-settings"},Pe=n("td",null,[n("label",null,"Title")],-1),Ae=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),Se=n("td",null,[n("label",null,"Tags")],-1),ze={class:"area-buttons"};var Te,Ie,Me,Ee,De,Ne,_e,Ve;be.render=function(e,l,o,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),t("div",{class:"overlay edit-image-dialog",onClick:l[5]||(l[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[4]||(l[4]=u((()=>{}),["stop"]))},[n("div",Ce,[n("div",xe,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",ke,[n("table",null,[n("tr",null,[Pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ae,n("tr",null,[Se,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":l[2]||(l[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",ze,[n("button",{class:"btn",onClick:l[3]||(l[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Ie=Te||(Te={}))[Ie.Flat=0]="Flat",Ie[Ie.Out=1]="Out",Ie[Ie.In=-1]="In",(Ee=Me||(Me={}))[Ee.FINAL=0]="FINAL",Ee[Ee.ANY=1]="ANY",(Ne=De||(De={}))[Ne.NORMAL=0]="NORMAL",Ne[Ne.ANY=1]="ANY",Ne[Ne.FLAT=2]="FLAT",(Ve=_e||(_e={}))[Ve.NORMAL=0]="NORMAL",Ve[Ve.REAL=1]="REAL";var Oe=e({name:"new-game-dialog",components:{ResponsiveImage:J},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Me.ANY,shapeMode:De.NORMAL,snapMode:_e.NORMAL}),methods:{onNewGameClick(){this.$emit("newGame",{tiles:this.tilesInt,image:this.image,scoreMode:this.scoreModeInt,shapeMode:this.shapeModeInt,snapMode:this.snapModeInt})}},computed:{canStartNewGame(){return!!(this.tilesInt&&this.image&&this.image.url&&[0,1].includes(this.scoreModeInt))},scoreModeInt(){return parseInt(`${this.scoreMode}`,10)},shapeModeInt(){return parseInt(`${this.shapeMode}`,10)},snapModeInt(){return parseInt(`${this.snapMode}`,10)},tilesInt(){return parseInt(`${this.tiles}`,10)}}});const Be={class:"area-image"},Ue={class:"has-image"},Re={key:0,class:"image-title"},$e={key:0,class:"image-title-title"},Ge={key:1,class:"image-title-dim"},Le={class:"area-settings"},Fe=n("td",null,[n("label",null,"Pieces")],-1),je=n("td",null,[n("label",null,"Scoring: ")],-1),We=i(" Any (Score when pieces are connected to each other or on final location)"),Ke=n("br",null,null,-1),He=i(" Final (Score when pieces are put to their final location)"),Ye=n("td",null,[n("label",null,"Shapes: ")],-1),qe=i(" Normal"),Qe=n("br",null,null,-1),Ze=i(" Any (flat pieces can occur anywhere)"),Xe=n("br",null,null,-1),Je=i(" Flat (all pieces flat on all sides)"),et=n("td",null,[n("label",null,"Snapping: ")],-1),tt=i(" Normal (pieces snap to final destination and to each other)"),nt=n("br",null,null,-1),lt=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ot={class:"area-buttons"};Oe.render=function(e,l,i,d,c,h){const m=a("responsive-image");return s(),t("div",{class:"overlay new-game-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",Be,[n("div",Ue,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",Re,[e.image.title?(s(),t("span",$e,'"'+r(e.image.title)+'"',1)):o("",!0),e.image.width||e.image.height?(s(),t("span",Ge,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):o("",!0)])):o("",!0)]),n("div",Le,[n("table",null,[n("tr",null,[Fe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[je,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[2]||(l[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),We]),Ke,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[3]||(l[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),He])])]),n("tr",null,[Ye,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[4]||(l[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),qe]),Qe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[5]||(l[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),Ze]),Xe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[6]||(l[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),Je])])]),n("tr",null,[et,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[7]||(l[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),tt]),nt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[8]||(l[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),lt])])])])]),n("div",ot,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:l[9]||(l[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};const at=async(e,t,n)=>new Promise(((l,o)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.addEventListener("load",(function(e){l({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){o(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body)}));var st=(e,t)=>at("post",e,t),it=e({components:{ImageLibrary:Y,NewImageDialog:ae,EditImageDialog:be,NewGameDialog:Oe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await fetch(`/api/newgame-data${X.asQueryArgs(this.filters)}`),t=await e.json();this.images=t.images,this.tags=t.tags},async filtersChanged(){await this.loadImages()},onImageClicked(e){this.image=e,this.dialog="new-game"},onImageEditClicked(e){this.image=e,this.dialog="edit-image"},async uploadImage(e){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await st("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await fetch("/api/save-image",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({id:e.id,title:e.title,tags:e.tags})});return await t.json()},async onSaveImageClick(e){await this.saveImage(e),this.dialog="",await this.loadImages()},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await fetch("/api/newgame",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)});if(200===t.status){const e=await t.json();this.$router.push({name:"game",params:{id:e.id}})}}}});const rt={class:"upload-image-teaser"},dt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ct={key:0},ut=i(" Tags: "),pt=i(" Sort by: "),gt=n("option",{value:"date_desc"},"Newest first",-1),ht=n("option",{value:"date_asc"},"Oldest first",-1),mt=n("option",{value:"alpha_asc"},"A-Z",-1),yt=n("option",{value:"alpha_desc"},"Z-A",-1);it.render=function(e,l,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",rt,[n("div",{class:"btn btn-big",onClick:l[1]||(l[1]=t=>e.dialog="new-image")},"Upload your image"),dt]),n("div",null,[e.tags.length>0?(s(),t("label",ct,[ut,(s(!0),t(d,null,c(e.relevantTags,((n,l)=>(s(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:l,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):o("",!0),n("label",null,[pt,p(n("select",{"onUpdate:modelValue":l[2]||(l[2]=t=>e.filters.sort=t),onChange:l[3]||(l[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[gt,ht,mt,yt],544),[[w,e.filters.sort]])])]),n(m,{images:e.images,onImageClicked:e.onImageClicked,onImageEditClicked:e.onImageEditClicked},null,8,["images","onImageClicked","onImageEditClicked"]),"new-image"===e.dialog?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:l[4]||(l[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):o("",!0),"edit-image"===e.dialog?(s(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:l[5]||(l[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):o("",!0),e.image&&"new-game"===e.dialog?(s(),t(v,{key:2,onBgclick:l[6]||(l[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):o("",!0)])};var ft=e({name:"scores",props:{activePlayers:{type:Array,required:!0},idlePlayers:{type:Array,required:!0}},computed:{actives(){return this.activePlayers.sort(((e,t)=>t.points-e.points)),this.activePlayers},idles(){return this.idlePlayers.sort(((e,t)=>t.points-e.points)),this.idlePlayers}}});const vt={class:"scores"},wt=n("div",null,"Scores",-1),bt=n("td",null,"⚡",-1),Ct=n("td",null,"💤",-1);ft.render=function(e,l,o,a,i,u){return s(),t("div",vt,[wt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[bt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[Ct,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var xt=e({name:"puzzle-status",props:{finished:{type:Boolean,required:!0},duration:{type:Number,required:!0},piecesDone:{type:Number,required:!0},piecesTotal:{type:Number,required:!0}},computed:{icon(){return this.finished?"🏁":"⏳"},durationStr(){return B(this.duration)}}});const kt={class:"timer"};xt.render=function(e,l,o,a,i,d){return s(),t("div",kt,[n("div",null," 🧩 "+r(e.piecesDone)+"/"+r(e.piecesTotal),1),n("div",null,r(e.icon)+" "+r(e.durationStr),1),b(e.$slots,"default")])};var Pt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const At=m();y("data-v-4d56fc17");const St=n("td",null,[n("label",null,"Background: ")],-1),zt=n("td",null,[n("label",null,"Color: ")],-1),Tt=n("td",null,[n("label",null,"Name: ")],-1),It=n("td",null,[n("label",null,"Sounds: ")],-1),Mt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Et={class:"sound-volume"},Dt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Nt=At(((e,l,o,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:l[10]||(l[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:l[9]||(l[9]=u((()=>{}),["stop"]))},[n("tr",null,[St,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[1]||(l[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[zt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[2]||(l[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[Tt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":l[3]||(l[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[It,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[4]||(l[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Mt,n("td",Et,[n("span",{onClick:l[5]||(l[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:l[6]||(l[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:l[7]||(l[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[8]||(l[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));Pt.render=Nt,Pt.__scopeId="data-v-4d56fc17";var _t=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const Vt={class:"preview"};_t.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay",onClick:l[1]||(l[1]=t=>e.$emit("bgclick"))},[n("div",Vt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Ot=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Me.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Me.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case De.FLAT:return["Flat","all pieces flat on all sides"];case De.ANY:return["Any","flat pieces can occur anywhere"];case De.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case _e.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case _e.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Bt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ut=n("td",null,"Image Title: ",-1),Rt=n("td",null,"Snap Mode: ",-1),$t=n("td",null,"Shape Mode: ",-1),Gt=n("td",null,"Score Mode: ",-1);Ot.render=function(e,l,o,a,i,d){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Bt,n("tr",null,[Ut,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[Rt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[$t,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Gt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Lt=1,Ft=4,jt=2,Wt=3,Kt=2,Ht=4,Yt=3,qt=9,Qt=1,Zt=2,Xt=3,Jt=4,en=5,tn=6,nn=7,ln=8,on=10,an=11,sn=12,rn=13,dn=14,cn=15,un=16,pn=1,gn=2,hn=3;const mn=Z("Communication.js");let yn,fn=[],vn=e=>{fn.push(e)},wn=[],bn=e=>{wn.push(e)};let Cn=0;const xn=e=>{Cn!==e&&(Cn=e,bn(e))};function kn(e){if(2===Cn)try{yn.send(JSON.stringify(e))}catch(t){mn.info("unable to send message.. maybe because ws is invalid?")}}let Pn,An;var Sn={connect:function(e,t,n){return Pn=0,An={},xn(3),new Promise((l=>{yn=new WebSocket(e,n+"|"+t),yn.onopen=()=>{xn(2),kn([Wt])},yn.onmessage=e=>{const t=JSON.parse(e.data),o=t[0];if(o===Ft){const e=t[1];l(e)}else{if(o!==Lt)throw`[ 2021-05-09 invalid connect msgType ${o} ]`;{const e=t[1],l=t[2];if(e===n&&An[l])return void delete An[l];vn(t)}}},yn.onerror=()=>{throw xn(1),"[ 2021-05-15 onerror ]"},yn.onclose=e=>{4e3===e.code||1001===e.code?xn(4):xn(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},l=await fetch(`/api/replay-data${X.asQueryArgs(n)}`);return await l.json()},disconnect:function(){yn&&yn.close(4e3),Pn=0,An={}},sendClientEvent:function(e){Pn++,An[Pn]=e,kn([jt,Pn,An[Pn]])},onServerChange:function(e){vn=e;for(const t of fn)vn(t);fn=[]},onConnectionStateChange:function(e){bn=e;for(const t of wn)bn(t);wn=[]},CODE_CUSTOM_DISCONNECT:4e3,CONN_STATE_NOT_CONNECTED:0,CONN_STATE_DISCONNECTED:1,CONN_STATE_CLOSED:4,CONN_STATE_CONNECTED:2,CONN_STATE_CONNECTING:3},zn=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===Sn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===Sn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const Tn={key:0,class:"overlay connection-lost"},In={key:0,class:"overlay-content"},Mn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),En={key:1,class:"overlay-content"},Dn=n("div",null,"Connecting...",-1);zn.render=function(e,l,a,i,r,d){return e.show?(s(),t("div",Tn,[e.lostConnection?(s(),t("div",In,[Mn,n("span",{class:"btn",onClick:l[1]||(l[1]=t=>e.$emit("reconnect"))},"Reconnect")])):o("",!0),e.connecting?(s(),t("div",En,[Dn])):o("",!0)])):o("",!0)};var Nn=e({name:"help-overlay",emits:{bgclick:null}});const _n=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Vn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),On=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),Bn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Un=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Rn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),$n=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),Gn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Ln=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Fn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),jn=n("tr",null,[n("td",null,"🧩❓ Toggle loose pieces:"),n("td",null,[n("div",null,[n("kbd",null,"G")])])],-1),Wn=n("tr",null,[n("td",null,"👤 Toggle player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Kn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),Hn=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),Yn=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),qn=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);Nn.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[_n,Vn,On,Bn,Un,Rn,$n,Gn,Ln,Fn,jn,Wn,Kn,Hn,Yn,qn])])};var Qn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),Zn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),Xn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Jn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),el=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function tl(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var nl={createCanvas:tl,loadImageToBitmap:async function(e){return new Promise((t=>{const n=new Image;n.onload=()=>{createImageBitmap(n).then(t)},n.src=e}))},resizeBitmap:async function(e,t,n){const l=tl(t,n);return l.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(l)},colorizedCanvas:function(e,t,n){const l=tl(e.width,e.height),o=l.getContext("2d");return o.save(),o.drawImage(t,0,0),o.fillStyle=n,o.globalCompositeOperation="source-in",o.fillRect(0,0,t.width,t.height),o.restore(),o.save(),o.globalCompositeOperation="destination-over",o.drawImage(e,0,0),o.restore(),l}};const ll=Z("Debug.js");let ol=0,al=0;var sl=e=>{ol=performance.now(),al=e},il=e=>{const t=performance.now(),n=t-ol;n>al&&ll.log(e+": "+n),ol=t};function rl(e,t){const n=e.x-t.x,l=e.y-t.y;return Math.sqrt(n*n+l*l)}function dl(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var cl={pointSub:function(e,t){return{x:e.x-t.x,y:e.y-t.y}},pointAdd:function(e,t){return{x:e.x+t.x,y:e.y+t.y}},pointDistance:rl,pointInBounds:function(e,t){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h},rectCenter:dl,rectMoved:function(e,t,n){return{x:e.x+t,y:e.y+n,w:e.w,h:e.h}},rectCenterDistance:function(e,t){return rl(dl(e),dl(t))},rectsOverlap:function(e,t){return!(t.x>e.x+e.w||e.x>t.x+t.w||t.y>e.y+e.h||e.y>t.y+t.h)}};const ul=Z("PuzzleGraphics.js");function pl(e,t){const n=X.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var gl={loadPuzzleBitmaps:async function(e){const t=await nl.loadImageToBitmap(e.info.imageUrl),n=await nl.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){ul.log("start createPuzzleTileBitmaps");const l=n.tileSize,o=n.tileMarginWidth,a=n.tileDrawSize,s=l/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:o,y:o},r=cl.pointAdd(a,{x:l,y:0}),c=cl.pointAdd(r,{x:0,y:l}),u=cl.pointSub(c,{x:l,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let l=0;lX.decodePiece(hl[e].puzzle.tiles[t]),Il=(e,t)=>Tl(e,t).group,Ml=(e,t)=>{const n=hl[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},El=(e,t)=>{const n=hl[e].puzzle.info,l={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},o=function(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t),o=l.x*n.tileSize,a=l.y*n.tileSize;return{x:o,y:a}}(e,t);return cl.pointAdd(l,o)},Dl=(e,t)=>Tl(e,t).pos,Nl=e=>{const t=Ql(e),n=Zl(e),l=Math.round(t/4),o=Math.round(n/4);return{x:0-l,y:0-o,w:t+2*l,h:n+2*o}},_l=(e,t)=>{const n=Ul(e),l=Tl(e,t);return{x:l.pos.x,y:l.pos.y,w:n,h:n}},Vl=(e,t)=>Tl(e,t).z,Ol=(e,t)=>{for(const n of hl[e].puzzle.tiles){const e=X.decodePiece(n);if(e.owner===t)return e.idx}return-1},Bl=e=>hl[e].puzzle.info.tileDrawSize,Ul=e=>hl[e].puzzle.info.tileSize,Rl=e=>hl[e].puzzle.data.maxGroup,$l=e=>hl[e].puzzle.data.maxZ;function Gl(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t);return[l.y>0?t-n.tilesX:-1,l.x0?t-1:-1]}const Ll=(e,t,n)=>{for(const l of t)zl(e,l,{z:n})},Fl=(e,t,n)=>{const l=Dl(e,t);zl(e,t,{pos:cl.pointAdd(l,n)})},jl=(e,t,n)=>{const l=Bl(e),o=Nl(e),a=n;for(const s of t){const t=Tl(e,s);t.pos.x+n.xo.x+o.w&&(a.x=Math.min(o.x+o.w-t.pos.x+l,a.x)),t.pos.y+n.yo.y+o.h&&(a.y=Math.min(o.y+o.h-t.pos.y+l,a.y))}for(const s of t)Fl(e,s,a)},Wl=(e,t)=>Tl(e,t).owner,Kl=(e,t)=>{for(const n of t)zl(e,n,{owner:-1,z:1})},Hl=(e,t,n)=>{for(const l of t)zl(e,l,{owner:n})};function Yl(e,t){const n=hl[e].puzzle.tiles,l=X.decodePiece(n[t]),o=[];if(l.group)for(const a of n){const e=X.decodePiece(a);e.group===l.group&&o.push(e.idx)}else o.push(l.idx);return o}const ql=(e,t)=>{const n=yl(e,t);return n?n.points:0},Ql=e=>hl[e].puzzle.info.table.width,Zl=e=>hl[e].puzzle.info.table.height;var Xl={setGame:function(e,t){hl[e]=t},exists:function(e){return!!hl[e]||!1},playerExists:vl,getActivePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){vl(e,t)?Al(e,t,{ts:n}):fl(e,t,function(e,t){return{id:e,x:0,y:0,d:0,name:null,color:null,bgcolor:null,points:0,ts:t}}(t,n))},getFinishedPiecesCount:Pl,getPieceCount:bl,getImageUrl:function(e){var t;const n=(null==(t=hl[e].puzzle.info.image)?void 0:t.url)||hl[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return hl[e]||null},getAllGames:function(){return Object.values(hl).sort(((e,t)=>kl(e.id)===kl(t.id)?t.puzzle.data.started-e.puzzle.data.started:kl(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=yl(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=yl(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=yl(e,t);return n?n.name:null},getPlayerIndexById:ml,getPlayerIdByIndex:function(e,t){return hl[e].players.length>t?X.decodePlayer(hl[e].players[t]).id:null},changePlayer:Al,setPlayer:fl,setPiece:function(e,t,n){hl[e].puzzle.tiles[t]=X.encodePiece(n)},setPuzzleData:function(e,t){hl[e].puzzle.data=t},getTableWidth:Ql,getTableHeight:Zl,getPuzzle:e=>hl[e].puzzle,getRng:e=>hl[e].rng.obj,getPuzzleWidth:e=>hl[e].puzzle.info.width,getPuzzleHeight:e=>hl[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return hl[e].puzzle.tiles.map(X.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Ol(e,t);return n<0?null:hl[e].puzzle.tiles[n]},getPieceDrawOffset:e=>hl[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Bl,getFinalPiecePos:El,getStartTs:e=>hl[e].puzzle.data.started,getFinishTs:e=>hl[e].puzzle.data.finished,handleInput:function(e,t,n,l,o){const a=hl[e].puzzle,s=function(e,t){return t in hl[e].evtInfos?hl[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([pn,a.data])},d=t=>{i.push([gn,X.encodePiece(Tl(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=yl(e,t);n&&i.push([hn,X.encodePlayer(n)])},p=n[0];if(p===tn){const o=n[1];Al(e,t,{bgcolor:o,ts:l}),u()}else if(p===nn){const o=n[1];Al(e,t,{color:o,ts:l}),u()}else if(p===ln){const o=`${n[1]}`.substr(0,16);Al(e,t,{name:o,ts:l}),u()}else if(p===qt){const o=n[1],a=n[2],s=yl(e,t);if(s){const n=s.x-o,i=s.y-a;Al(e,t,{ts:l,x:n,y:i}),u()}}else if(p===Qt){const o={x:n[1],y:n[2]};Al(e,t,{d:1,ts:l}),u(),s._last_mouse_down=o;const a=((e,t)=>{const n=hl[e].puzzle.info,l=hl[e].puzzle.tiles;let o=-1,a=-1;for(let s=0;so)&&(o=e.z,a=s)}return a})(e,o);if(a>=0){const n=$l(e)+1;Sl(e,{maxZ:n}),r();const l=Yl(e,a);Ll(e,l,$l(e)),Hl(e,l,t),c(l)}s._last_mouse=o}else if(p===Xt){const o=n[1],a=n[2],i={x:o,y:a};if(null===s._last_mouse_down)Al(e,t,{x:o,y:a,ts:l}),u();else{const n=Ol(e,t);if(n>=0){Al(e,t,{x:o,y:a,ts:l}),u();const r=Yl(e,n);let d=cl.pointInBounds(i,Nl(e))&&cl.pointInBounds(s._last_mouse_down,Nl(e));for(const t of r){const n=_l(e,t);if(cl.pointInBounds(i,n)){d=!0;break}}if(d){const t=o-s._last_mouse_down.x,n=a-s._last_mouse_down.y;jl(e,r,{x:t,y:n}),c(r)}}else Al(e,t,{ts:l}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===Zt){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Ol(e,t);if(g>=0){const n=Yl(e,g);Hl(e,n,0),c(n);const s=Dl(e,g),i=El(e,g);let h=!1;if(xl(e)===_e.REAL){for(const t of n)if(Ml(e,t)){h=!0;break}}else h=!0;if(h&&cl.pointDistance(i,s){const o=hl[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const l=Il(e,t),o=Il(e,n);return!(!l||l!==o)})(e,t,n))return!1;const a=Dl(e,t),s=cl.pointAdd(Dl(e,n),{x:l[0]*o.tileSize,y:l[1]*o.tileSize});if(cl.pointDistance(a,s){const l=hl[e].puzzle.tiles,o=Il(e,t),a=Il(e,n);let s;const i=[];o&&i.push(o),a&&i.push(a),o?s=o:a?s=a:(Sl(e,{maxGroup:Rl(e)+1}),r(),s=Rl(e));if(zl(e,t,{group:s}),d(t),zl(e,n,{group:s}),d(n),i.length>0)for(const r of l){const t=X.decodePiece(r);i.includes(t.group)&&(zl(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),o=Yl(e,t),((e,t)=>-1===Wl(e,t))(e,n))Kl(e,o);else{const t=((e,t)=>{let n=0;for(const l of t){const t=Vl(e,l);t>n&&(n=t)}return n})(e,o);Ll(e,o,t)}return c(o),!0}return!1};let a=!1;for(const t of Yl(e,g)){const l=Gl(e,t);if(n(e,t,l[0],[0,1])||n(e,t,l[1],[-1,0])||n(e,t,l[2],[0,-1])||n(e,t,l[3],[1,0])){a=!0;break}}if(a&&Cl(e)===Me.ANY){const n=ql(e,t)+1;Al(e,t,{d:p,ts:l,points:n}),u()}else Al(e,t,{d:p,ts:l}),u();a&&xl(e)===_e.REAL&&Pl(e)===bl(e)&&(Sl(e,{finished:l}),r()),a&&o&&o(t)}}else Al(e,t,{d:p,ts:l}),u();s._last_mouse=i}else if(p===Jt){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else if(p===en){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else Al(e,t,{ts:l}),u();return function(e,t,n){hl[e].evtInfos[t]=n}(e,t,s),i}};let Jl=-10,eo=20,to=2,no=15;class lo{constructor(e){this.radius=10,this.previousRadius=10,this.explodingDuration=100,this.hasExploded=!1,this.alive=!0,this.color=function(e){return"rgba("+e.random(0,255)+","+e.random(0,255)+","+e.random(0,255)+", 0.8)"}(e),this.px=window.innerWidth/4+Math.random()*window.innerWidth/2,this.py=window.innerHeight,this.vx=Jl+Math.random()*eo,this.vy=-1*(to+Math.random()*no),this.duration=0}update(e){if(this.hasExploded){const e=200-this.radius;this.previousRadius=this.radius,this.radius+=e/10,this.explodingDuration--,0==this.explodingDuration&&(this.alive=!1)}else this.vx+=0,this.vy+=1,this.vy>=0&&e&&this.explode(e),this.px+=this.vx,this.py+=this.vy}draw(e){e.beginPath(),e.arc(this.px,this.py,this.previousRadius,0,2*Math.PI,!1),this.hasExploded||(e.fillStyle=this.color,e.lineWidth=1,e.fill())}explode(e){this.hasExploded=!0;const t=3+Math.floor(3*Math.random());for(let n=0;n{this.resize()}))}setSpeedParams(){let e=0,t=0;for(;e=0;)t+=1,e+=t;to=t/2,no=t-to;const n=1/4*this.canvas.width/(t/2);Jl=-n,eo=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new lo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new lo(this.rng));const e=[];for(;this.explodedBombs.length>0;){const t=this.explodedBombs.shift();if(!t)break;t.update(),t.alive&&e.push(t)}this.explodedBombs=e;const t=[];for(;this.readyBombs.length>0;){const e=this.readyBombs.shift();if(!e)break;e.update(this.particles),e.hasExploded?this.explodedBombs.push(e):t.push(e)}this.readyBombs=t;const n=[];for(;this.particles.length>0;){const e=this.particles.shift();if(!e)break;e.update(),e.alive&&n.push(e)}this.particles=n}render(){this.ctx.beginPath(),this.ctx.fillStyle="rgba(0, 0, 0, 0.1)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height);for(let e=0;e{localStorage.setItem(e,t)},ho=e=>localStorage.getItem(e);var mo=(e,t)=>{go(e,`${t}`)},yo=(e,t)=>{const n=ho(e);if(null===n)return t;const l=parseInt(n,10);return isNaN(l)?t:l},fo=(e,t)=>{go(e,t?"1":"0")},vo=(e,t)=>{const n=ho(e);return null===n?t:"1"===n},wo=(e,t)=>{go(e,t)},bo=(e,t)=>{const n=ho(e);return null===n?t:n};const Co={"./grab.png":Zn,"./grab_mask.png":Xn,"./hand.png":Jn,"./hand_mask.png":el},xo={"./click.mp3":Qn};let ko=!0,Po=!0;let Ao=!0;async function So(e,t,n,l,o,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=xo["./click.mp3"].default,i=new Audio(s),r=await nl.loadImageToBitmap(Co["./grab.png"].default),d=await nl.loadImageToBitmap(Co["./hand.png"].default),c=await nl.loadImageToBitmap(Co["./grab_mask.png"].default),u=await nl.loadImageToBitmap(Co["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const l=e.d?c:u;y[t]=await createImageBitmap(nl.colorizedCanvas(n,l,e.color))}else y[t]=n}return y[t]},v=function(e,t){return t.width=window.innerWidth,t.height=window.innerHeight,e.appendChild(t),window.addEventListener("resize",(()=>{t.width=window.innerWidth,t.height=window.innerHeight,Ao=!0})),t}(o,nl.createCanvas()),w={final:!1,log:[],logPointer:0,speeds:[.5,1,2,5,10,20,50,100,250,500],speedIdx:1,paused:!1,lastRealTs:0,lastGameTs:0,gameStartTs:0,skipNonActionPhases:!0,dataOffset:0};Sn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Sn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===l){const l=await Sn.connect(n,e,t),o=X.decodeGame(l);Xl.setGame(o.id,o),C=()=>V()}else{if("replay"!==l)throw"[ 2020-12-22 MODE invalid, must be play|replay ]";{const t=await b(e);if(!t.game)throw"[ 2021-05-29 no game received ]";const n=X.decodeGame(t.game);Xl.setGame(n.id,n),w.lastRealTs=V(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Ao=!0};await x();const k=Xl.getPieceDrawOffset(e),P=Xl.getPieceDrawSize(e),A=Xl.getPuzzleWidth(e),S=Xl.getPuzzleHeight(e),z=Xl.getTableWidth(e),T=Xl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},M={w:A,h:S},E={w:P,h:P},D=await gl.loadPuzzleBitmaps(Xl.getPuzzle(e)),_=new ao(v,Xl.getRng(e));_.init();const O=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const B=function(){let e=0,t=0,n=1;const l=(l,o)=>{e+=l/n,t+=o/n},o=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=(e,t)=>{if(n==e)return!1;const o=1-n/e;return l(-t.x*o,-t.y*o),n=e,!0},s=l=>({x:l.x/n-e,y:l.y/n-t}),i=l=>({x:(l.x+e)*n,y:(l.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:l,canZoom:e=>n!=o(e),zoom:(e,t)=>a(o(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),U=()=>{B.reset(),B.move(-(z-v.width)/2,-(T-v.height)/2);const e=B.worldDimToViewport(M),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const l=n.viewportToWorld({x:e,y:t});return[l.x,l.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([Qt,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([Zt,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([Xt,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Jt:en;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([on]),"replay"===l&&("KeyI"===e.code&&v([rn]),"KeyO"===e.code&&v([dn]),"KeyP"===e.code&&v([sn])),"KeyF"===e.code&&(ko=!ko,Ao=!0),"KeyG"===e.code&&(Po=!Po,Ao=!0),"KeyM"===e.code&&v([an]),"KeyN"===e.code&&v([cn]),"KeyC"===e.code&&v([un]))}));const v=e=>{o.push(e)};return{addEvent:v,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const l=(p?24:12)*Math.sqrt(n.getCurrentZoom()),o=n.viewportDimToWorld({w:e*l,h:t*l});v([qt,o.w,o.h]),f&&(f[0]-=o.w,f[1]-=o.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([Jt,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([en,...e])}},setHotkeys:e=>{a=e}}}(v,window,B,l),$=Xl.getImageUrl(e),G=()=>{const t=Xl.getStartTs(e),n=Xl.getFinishTs(e),l=C();a.setFinished(!!n),a.setDuration((n||l)-t)};G(),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),a.setPiecesTotal(Xl.getPieceCount(e));const L=C();a.setActivePlayers(Xl.getActivePlayers(e,L)),a.setIdlePlayers(Xl.getIdlePlayers(e,L));const F=!!Xl.getFinishTs(e);let j=F;const W=()=>j&&!F,K=()=>yo(so,100),H=()=>vo(io,!1),Y=()=>vo(po,!0),q=()=>{const e=K();i.volume=e/100,i.play()},Q=()=>"replay"===l?bo(ro,"#222222"):Xl.getPlayerBgColor(e,t)||bo(ro,"#222222"),Z=()=>"replay"===l?bo(co,"#ffffff"):Xl.getPlayerColor(e,t)||bo(co,"#ffffff");let J="",ee="",te=!1;const ne=e=>{te=e;const[t,n]=e?[J,"grab"]:[ee,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},le=e=>{J=nl.colorizedCanvas(r,c,e).toDataURL(),ee=nl.colorizedCanvas(d,u,e).toDataURL(),ne(te)};le(Z());const oe=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},ae=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,oe())},ie=()=>{w.paused=!w.paused,oe()},re=[];let de;let ce;if("play"===l?re.push(setInterval((()=>{G()}),1e3)):"replay"===l&&oe(),"play"===l)Sn.onServerChange((n=>{n[0],n[1],n[2];const l=n[3];for(const[o,a]of l)switch(o){case hn:{const n=X.decodePlayer(a);n.id!==t&&(Xl.setPlayer(e,n.id,n),Ao=!0)}break;case gn:{const t=X.decodePiece(a);Xl.setPiece(e,t.idx,t),Ao=!0}break;case pn:Xl.setPuzzleData(e,a),Ao=!0}j=!!Xl.getFinishTs(e)}));else if("replay"===l){const t=(t,n)=>{const l=t;if(l[0]===Kt){const t=l[1];return Xl.addPlayer(e,t,n),!0}if(l[0]===Ht){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return Xl.addPlayer(e,t,n),!0}if(l[0]===Yt){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const o=l[2];return Xl.handleInput(e,t,o,n),!0}return!1};let n=w.lastGameTs;const l=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=V();if(w.paused)return w.lastRealTs=o,void(de=setTimeout(l,50));const a=(o-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const l=w.log[w.logPointer],o=n+l[l.length-1],a=w.log[e],i=a[a.length-1],r=o+i;if(r>s){s+500*N{let t=!1;const n=e.fps||60,l=e.slow||1,o=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=l*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,o(i);a(c/l),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===l){const l=n[0];if(l===qt){const e=n[1],t=n[2],l=B.worldDimToViewport({w:e,h:t});Ao=!0,B.move(l.w,l.h)}else if(l===Xt){if(ue&&!Xl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(l===nn)le(n[1]);else if(l===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(l===Zt)ue=null,ne(!1);else if(l===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(l===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else l===on?a.togglePreview():l===an?a.toggleSoundsEnabled():l===cn?a.togglePlayerNames():l===un&&U();const o=C();Xl.handleInput(e,t,n,o,(e=>{H()&&q()})).length>0&&(Ao=!0),Sn.sendClientEvent(n)}else if("replay"===l){const e=n[0];if(e===sn)ie();else if(e===dn)se();else if(e===rn)ae();else if(e===qt){const e=n[1],t=n[2];Ao=!0,B.move(e,t)}else if(e===Xt){if(ue){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(e===nn)le(n[1]);else if(e===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(e===Zt)ue=null,ne(!1);else if(e===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(e===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else e===on?a.togglePreview():e===an?a.toggleSoundsEnabled():e===cn?a.togglePlayerNames():e===un&&U()}j=!!Xl.getFinishTs(e),W()&&(_.update(),Ao=!0)},render:async()=>{if(!Ao)return;const n=C();let o,s,i;window.DEBUG&&sl(0),O.fillStyle=Q(),O.fillRect(0,0,v.width,v.height),window.DEBUG&&il("clear done"),o=B.worldToViewportRaw(I),s=B.worldDimToViewportRaw(M),O.fillStyle="rgba(255, 255, 255, .3)",O.fillRect(o.x,o.y,s.w,s.h),window.DEBUG&&il("board done");const r=Xl.getPiecesSortedByZIndex(e);window.DEBUG&&il("get tiles done"),s=B.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?ko:Po)&&(i=D[e.idx],o=B.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),O.drawImage(i,0,0,i.width,i.height,o.x,o.y,s.w,s.h));window.DEBUG&&il("tiles done");const d=[];for(const a of Xl.getActivePlayers(e,n))c=a,("replay"===l||c.id!==t)&&(i=await f(a),o=B.worldToViewport(a),O.drawImage(i,o.x-g,o.y-m),Y()&&d.push([`${a.name} (${a.points})`,o.x,o.y+h]));var c;O.fillStyle="white",O.textAlign="center";for(const[e,t,l]of d)O.fillText(e,t,l);window.DEBUG&&il("players done"),a.setActivePlayers(Xl.getActivePlayers(e,n)),a.setIdlePlayers(Xl.getIdlePlayers(e,n)),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),window.DEBUG&&il("HUD done"),W()&&_.render(),Ao=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{wo(ro,e),R.addEvent([tn,e])},onColorChange:e=>{wo(co,e),R.addEvent([nn,e])},onNameChange:e=>{wo(uo,e),R.addEvent([ln,e])},onSoundsEnabledChange:e=>{fo(io,e)},onSoundsVolumeChange:e=>{mo(so,e),q()},onShowPlayerNamesChange:e=>{fo(po,e)},replayOnSpeedUp:ae,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:$,player:{background:Q(),color:Z(),name:"replay"===l?bo(uo,"anon"):Xl.getPlayerName(e,t)||bo(uo,"anon"),soundsEnabled:H(),soundsVolume:K(),showPlayerNames:Y()},game:Xl.get(e),disconnect:Sn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var zo=e({name:"game",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,ConnectionOverlay:zn,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const To={id:"game"},Io={key:1,class:"overlay"},Mo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Eo={class:"menu"},Do={class:"tabs"},No=i("🧩 Puzzles");zo.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",To,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Io,[Mo])):o("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Eo,[n("div",Do,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[No])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var _o=e({name:"replay",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Vo={id:"replay"},Oo={key:1,class:"overlay"},Bo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Uo={class:"menu"},Ro={class:"tabs"},$o=i("🧩 Puzzles");_o.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Vo,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Oo,[Bo])):o("",!0),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:l((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Uo,[n("div",Ro,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[$o])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=await fetch("/api/conf"),t=await e.json();const n=k({history:P(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:it},{name:"game",path:"/g/:id",component:zo},{name:"replay",path:"/replay/:id",component:_o}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const l=A(S);l.config.globalProperties.$config=t,l.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=X.uniqId(),localStorage.setItem("ID",e)),e}(),l.use(n),l.mount("#app")})(); diff --git a/build/public/index.html b/build/public/index.html index dadb3e4..3df4956 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 7e7a143..82e7590 100644 --- a/build/server/main.js +++ b/build/server/main.js @@ -626,10 +626,12 @@ function getPieceCount(gameId) { return GAMES[gameId].puzzle.tiles.length; } function getImageUrl(gameId) { - return GAMES[gameId].puzzle.info.imageUrl; -} -function setImageUrl(gameId, imageUrl) { - GAMES[gameId].puzzle.info.imageUrl = imageUrl; + const imageUrl = GAMES[gameId].puzzle.info.image?.url + || GAMES[gameId].puzzle.info.imageUrl; + if (!imageUrl) { + throw new Error('[2021-07-11] no image url set'); + } + return imageUrl; } function getScoreMode(gameId) { return GAMES[gameId].scoreMode; @@ -1243,7 +1245,6 @@ var GameCommon = { getFinishedPiecesCount, getPieceCount, getImageUrl, - setImageUrl, get: get$1, getAllGames, getPlayerBgColor, @@ -1358,6 +1359,8 @@ var GameLog = { exists, log: _log, get, + filename, + idxname, }; const log$4 = logger('Images.ts'); @@ -1433,7 +1436,6 @@ const imageFromDb = (db, imageId) => { return { id: i.id, filename: i.filename, - file: `${UPLOAD_DIR}/${i.filename}`, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, tags: getTags(db, i.id), @@ -1472,7 +1474,6 @@ inner join images i on i.id = ixc.image_id ${where.sql}; return images.map(i => ({ id: i.id, filename: i.filename, - file: `${UPLOAD_DIR}/${i.filename}`, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, tags: getTags(db, i.id), @@ -1490,7 +1491,6 @@ const allImagesFromDisk = (tags, sort) => { .map(f => ({ id: 0, filename: f, - file: `${UPLOAD_DIR}/${f}`, url: `${UPLOAD_URL}/${encodeURIComponent(f)}`, title: f.replace(/\.[a-z]+$/, ''), tags: [], @@ -1501,12 +1501,12 @@ const allImagesFromDisk = (tags, sort) => { switch (sort) { case 'alpha_asc': images = images.sort((a, b) => { - return a.file > b.file ? 1 : -1; + return a.filename > b.filename ? 1 : -1; }); break; case 'alpha_desc': images = images.sort((a, b) => { - return a.file < b.file ? 1 : -1; + return a.filename < b.filename ? 1 : -1; }); break; case 'date_asc': @@ -1552,7 +1552,7 @@ var Images = { // final resized version of the puzzle image const TILE_SIZE = 64; async function createPuzzle(rng, targetTiles, image, ts, shapeMode) { - const imagePath = image.file; + const imagePath = `${UPLOAD_DIR}/${image.filename}`; const imageUrl = image.url; // determine puzzle information from the image dimensions const dim = await Images.getDimensions(imagePath); @@ -1651,6 +1651,7 @@ async function createPuzzle(rng, targetTiles, image, ts, shapeMode) { // information that was used to create the puzzle targetTiles: targetTiles, imageUrl, + image: image, width: info.width, height: info.height, tileSize: info.tileSize, @@ -2114,7 +2115,8 @@ app.get('/api/replay-data', async (req, res) => { let game = null; if (offset === 0) { // also need the game - game = await Game.createGameObject(gameId, log[0][2], log[0][3], log[0][4], log[0][5], log[0][6], log[0][7]); + game = await Game.createGameObject(gameId, log[0][2], log[0][3], // must be ImageInfo + log[0][4], log[0][5], log[0][6], log[0][7]); } res.send({ log, game: game ? Util.encodeGame(game) : null }); }); diff --git a/scripts/fix_games_image_info.ts b/scripts/fix_games_image_info.ts new file mode 100644 index 0000000..559b512 --- /dev/null +++ b/scripts/fix_games_image_info.ts @@ -0,0 +1,90 @@ +import GameCommon from '../src/common/GameCommon' +import GameLog from '../src/server/GameLog' +import { Game } from '../src/common/Types' +import { logger } from '../src/common/Util' +import { DB_FILE, DB_PATCHES_DIR, UPLOAD_DIR } from '../src/server/Dirs' +import Db from '../src/server/Db' +import GameStorage from '../src/server/GameStorage' +import fs from 'fs' + +const log = logger('fix_games_image_info.ts') + +import Images from '../src/server/Images' + +console.log(DB_FILE) + +const db = new Db(DB_FILE, DB_PATCHES_DIR) +db.patch(true) + +// ;(async () => { +// let images = db.getMany('images') +// for (let image of images) { +// console.log(image.filename) +// let dim = await Images.getDimensions(`${UPLOAD_DIR}/${image.filename}`) +// console.log(await Images.getDimensions(`${UPLOAD_DIR}/${image.filename}`)) +// image.width = dim.w +// image.height = dim.h +// db.upsert('images', image, { id: image.id }) +// } +// })() + +function fixOne(gameId: string) { + let g = GameCommon.get(gameId) + if (!g) { + return + } + + if (!g.puzzle.info.image && g.puzzle.info.imageUrl) { + log.log('game id: ', gameId) + const parts = g.puzzle.info.imageUrl.split('/') + const fileName = parts[parts.length - 1] + const imageRow = db.get('images', {filename: fileName}) + if (!imageRow) { + return + } + + g.puzzle.info.image = Images.imageFromDb(db, imageRow.id) + + log.log(g.puzzle.info.image.title, imageRow.id) + + GameStorage.persistGame(gameId) + } else if (g.puzzle.info.image?.id) { + const imageId = g.puzzle.info.image.id + + g.puzzle.info.image = Images.imageFromDb(db, imageId) + + log.log(g.puzzle.info.image.title, imageId) + + GameStorage.persistGame(gameId) + } + + // fix log + const file = GameLog.filename(gameId, 0) + if (!fs.existsSync(file)) { + return + } + + const lines = fs.readFileSync(file, 'utf-8').split("\n") + const l = lines.filter(line => !!line).map(line => { + return JSON.parse(`[${line}]`) + }) + if (l && l[0] && !l[0][3].id) { + log.log(l[0][3]) + l[0][3] = g.puzzle.info.image + const newlines = l.map(ll => { + return JSON.stringify(ll).slice(1, -1) + }).join("\n") + "\n" + console.log(g.puzzle.info.image) + // process.exit(0) + fs.writeFileSync(file, newlines) + } +} + +function fix() { + GameStorage.loadGames() + GameCommon.getAllGames().forEach((game: Game) => { + fixOne(game.id) + }) +} + +fix() diff --git a/scripts/fix_image.ts b/scripts/fix_image.ts deleted file mode 100644 index 366ed1f..0000000 --- a/scripts/fix_image.ts +++ /dev/null @@ -1,23 +0,0 @@ -import GameCommon from '../src/common/GameCommon' -import { logger } from '../src/common/Util' -import GameStorage from '../src/server/GameStorage' - -const log = logger('fix_image.js') - -function fix(gameId) { - GameStorage.loadGame(gameId) - let changed = false - - let imgUrl = GameCommon.getImageUrl(gameId) - if (imgUrl.match(/^\/example-images\//)) { - log.log(`found bad imgUrl: ${imgUrl}`) - imgUrl = imgUrl.replace(/^\/example-images\//, '/uploads/') - GameCommon.setImageUrl(gameId, imgUrl) - changed = true - } - if (changed) { - GameStorage.persistGame(gameId) - } -} - -fix(process.argv[2]) diff --git a/src/common/GameCommon.ts b/src/common/GameCommon.ts index e2f18eb..7ce4599 100644 --- a/src/common/GameCommon.ts +++ b/src/common/GameCommon.ts @@ -162,11 +162,12 @@ function getPieceCount(gameId: string): number { } function getImageUrl(gameId: string): string { - return GAMES[gameId].puzzle.info.imageUrl -} - -function setImageUrl(gameId: string, imageUrl: string): void { - GAMES[gameId].puzzle.info.imageUrl = imageUrl + const imageUrl = GAMES[gameId].puzzle.info.image?.url + || GAMES[gameId].puzzle.info.imageUrl + if (!imageUrl) { + throw new Error('[2021-07-11] no image url set') + } + return imageUrl } function getScoreMode(gameId: string): ScoreMode { @@ -895,7 +896,6 @@ export default { getFinishedPiecesCount, getPieceCount, getImageUrl, - setImageUrl, get, getAllGames, getPlayerBgColor, diff --git a/src/common/Types.ts b/src/common/Types.ts index 261e210..71840bf 100644 --- a/src/common/Types.ts +++ b/src/common/Types.ts @@ -93,7 +93,7 @@ export interface Image { export interface GameSettings { tiles: number - image: Image + image: ImageInfo scoreMode: ScoreMode shapeMode: ShapeMode snapMode: SnapMode @@ -152,11 +152,23 @@ export interface PieceChange { group?: number } +export interface ImageInfo +{ + id: number + filename: string + url: string + title: string + tags: Tag[] + created: Timestamp + width: number + height: number +} + export interface PuzzleInfo { table: PuzzleTable targetTiles: number - imageUrl: string - imageTitle: string + imageUrl?: string // deprecated, use image.url instead + image?: ImageInfo width: number height: number diff --git a/src/frontend/components/InfoOverlay.vue b/src/frontend/components/InfoOverlay.vue index 7f76d2d..efc11fe 100644 --- a/src/frontend/components/InfoOverlay.vue +++ b/src/frontend/components/InfoOverlay.vue @@ -6,19 +6,19 @@ Image Title: - {{game.puzzle.info.imageTitle}} + {{game.puzzle.info.image.title}} Snap Mode: - {{scoreMode[0]}} + {{scoreMode[0]}} Shape Mode: - {{shapeMode[0]}} + {{shapeMode[0]}} Score Mode: - {{snapMode[0]}} + {{snapMode[0]}} diff --git a/src/server/Game.ts b/src/server/Game.ts index 2c4c123..0aef26f 100644 --- a/src/server/Game.ts +++ b/src/server/Game.ts @@ -1,9 +1,9 @@ import GameCommon from './../common/GameCommon' -import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode, Timestamp } from './../common/Types' +import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode,ImageInfo, Timestamp } from './../common/Types' import Util, { logger } from './../common/Util' import { Rng } from './../common/Rng' import GameLog from './GameLog' -import { createPuzzle, PuzzleCreationImageInfo } from './Puzzle' +import { createPuzzle } from './Puzzle' import Protocol from './../common/Protocol' import GameStorage from './GameStorage' @@ -12,7 +12,7 @@ const log = logger('Game.ts') async function createGameObject( gameId: string, targetTiles: number, - image: PuzzleCreationImageInfo, + image: ImageInfo, ts: Timestamp, scoreMode: ScoreMode, shapeMode: ShapeMode, @@ -35,7 +35,7 @@ async function createGameObject( async function createGame( gameId: string, targetTiles: number, - image: PuzzleCreationImageInfo, + image: ImageInfo, ts: Timestamp, scoreMode: ScoreMode, shapeMode: ShapeMode, diff --git a/src/server/GameLog.ts b/src/server/GameLog.ts index c6a14ad..a8b2050 100644 --- a/src/server/GameLog.ts +++ b/src/server/GameLog.ts @@ -100,4 +100,6 @@ export default { exists, log: _log, get, + filename, + idxname, } diff --git a/src/server/Images.ts b/src/server/Images.ts index 8cda19a..2a2c095 100644 --- a/src/server/Images.ts +++ b/src/server/Images.ts @@ -7,30 +7,10 @@ import {UPLOAD_DIR, UPLOAD_URL} from './Dirs' import Db, { OrderBy, WhereRaw } from './Db' import { Dim } from '../common/Geometry' import { logger } from '../common/Util' -import { Timestamp } from '../common/Types' +import { Tag, ImageInfo } from '../common/Types' const log = logger('Images.ts') -interface Tag -{ - id: number - slug: string - title: string -} - -interface ImageInfo -{ - id: number - filename: string - file: string - url: string - title: string - tags: Tag[] - created: Timestamp - width: number - height: number -} - const resizeImage = async (filename: string): Promise => { if (!filename.toLowerCase().match(/\.(jpe?g|webp|png)$/)) { return @@ -106,7 +86,6 @@ const imageFromDb = (db: Db, imageId: number): ImageInfo => { return { id: i.id, filename: i.filename, - file: `${UPLOAD_DIR}/${i.filename}`, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, tags: getTags(db, i.id), @@ -152,7 +131,6 @@ inner join images i on i.id = ixc.image_id ${where.sql}; return images.map(i => ({ id: i.id as number, filename: i.filename, - file: `${UPLOAD_DIR}/${i.filename}`, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, tags: getTags(db, i.id), @@ -174,7 +152,6 @@ const allImagesFromDisk = ( .map(f => ({ id: 0, filename: f, - file: `${UPLOAD_DIR}/${f}`, url: `${UPLOAD_URL}/${encodeURIComponent(f)}`, title: f.replace(/\.[a-z]+$/, ''), tags: [] as Tag[], @@ -186,13 +163,13 @@ const allImagesFromDisk = ( switch (sort) { case 'alpha_asc': images = images.sort((a, b) => { - return a.file > b.file ? 1 : -1 + return a.filename > b.filename ? 1 : -1 }) break; case 'alpha_desc': images = images.sort((a, b) => { - return a.file < b.file ? 1 : -1 + return a.filename < b.filename ? 1 : -1 }) break; diff --git a/src/server/Puzzle.ts b/src/server/Puzzle.ts index bd0ad98..581578a 100644 --- a/src/server/Puzzle.ts +++ b/src/server/Puzzle.ts @@ -1,14 +1,9 @@ import Util from './../common/Util' import { Rng } from './../common/Rng' import Images from './Images' -import { EncodedPiece, EncodedPieceShape, PieceShape, Puzzle, ShapeMode } from '../common/Types' +import { EncodedPiece, EncodedPieceShape, PieceShape, Puzzle, ShapeMode, ImageInfo } from '../common/Types' import { Dim, Point } from '../common/Geometry' - -export interface PuzzleCreationImageInfo { - file: string - url: string - title: string -} +import { UPLOAD_DIR } from './Dirs' export interface PuzzleCreationInfo { width: number @@ -28,11 +23,11 @@ const TILE_SIZE = 64 async function createPuzzle( rng: Rng, targetTiles: number, - image: PuzzleCreationImageInfo, + image: ImageInfo, ts: number, shapeMode: ShapeMode ): Promise { - const imagePath = image.file + const imagePath = `${UPLOAD_DIR}/${image.filename}` const imageUrl = image.url // determine puzzle information from the image dimensions @@ -140,8 +135,8 @@ async function createPuzzle( }, // information that was used to create the puzzle targetTiles: targetTiles, - imageUrl, - imageTitle: image.title || '', + imageUrl, // todo: remove + image: image, width: info.width, // actual puzzle width (same as bitmap.width) height: info.height, // actual puzzle height (same as bitmap.height) diff --git a/src/server/main.ts b/src/server/main.ts index 119bf9a..cbed199 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -19,7 +19,7 @@ import { UPLOAD_DIR, } from './Dirs' import GameCommon from '../common/GameCommon' -import { ServerEvent, Game as GameType, GameSettings, ScoreMode, ShapeMode, SnapMode } from '../common/Types' +import { ServerEvent, Game as GameType, GameSettings } from '../common/Types' import GameStorage from './GameStorage' import Db from './Db' @@ -87,7 +87,7 @@ app.get('/api/replay-data', async (req, res): Promise => { game = await Game.createGameObject( gameId, log[0][2], - log[0][3], + log[0][3], // must be ImageInfo log[0][4], log[0][5], log[0][6], From bbcfd4200878f72402734b66e5dd8298374cfb13 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 17:08:18 +0200 Subject: [PATCH 04/17] extract event adapter to own file --- build/public/assets/index.90925b20.js | 1 + build/public/assets/index.93936dee.js | 1 - build/public/index.html | 2 +- build/server/main.js | 4 + src/common/Protocol.ts | 6 + src/frontend/EventAdapter.ts | 177 ++++++++++++++++++++++++ src/frontend/game.ts | 188 ++------------------------ 7 files changed, 202 insertions(+), 177 deletions(-) create mode 100644 build/public/assets/index.90925b20.js delete mode 100644 build/public/assets/index.93936dee.js create mode 100644 src/frontend/EventAdapter.ts diff --git a/build/public/assets/index.90925b20.js b/build/public/assets/index.90925b20.js new file mode 100644 index 0000000..940cbdd --- /dev/null +++ b/build/public/assets/index.90925b20.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 s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),M=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:o((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:o((()=>[M])),_:1})])])):l("",!0),n(g)])};const E=864e5,D=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const o=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${o}m ${Math.floor(e/1e3)}s`};var N=1,_=1e3,V=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},O=(e,t)=>D(t-e),B=D,U=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",o=e,l=t||V();return`${n} ${O(o,l)}`}}});const R={class:"game-info-text"},$=n("br",null,null,-1),G=n("br",null,null,-1),L=n("br",null,null,-1),F=i(" ↪️ Watch replay ");U.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",R,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),$,i(" 👥 "+r(e.game.players),1),G,i(" "+r(e.time(e.game.started,e.game.finished)),1),L])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[F])),_:1},8,["to"])):l("",!0)],4)};var j=e({components:{GameTeaser:U},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await fetch("/api/index-data"),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const W=n("h1",null,"Running games",-1),K=n("h1",null,"Finished games",-1);j.render=function(e,o,l,i,r,u){const p=a("game-teaser");return s(),t("div",null,[W,(s(!0),t(d,null,c(e.gamesRunning,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),K,(s(!0),t(d,null,c(e.gamesFinished,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var H=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});H.render=function(e,o,l,a,i,r){return s(),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 Y=e({name:"image-library",components:{ImageTeaser:H},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});Y.render=function(e,n,o,l,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,o)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])};class q{constructor(e){this.rand_high=e||3735929054,this.rand_low=1231121986^e}random(e,t){this.rand_high=(this.rand_high<<16)+(this.rand_high>>16)+this.rand_low&4294967295,this.rand_low=this.rand_low+this.rand_high&4294967295;return e+(this.rand_high>>>0)/4294967295*(t-e+1)|0}choice(e){return e[this.random(0,e.length-1)]}shuffle(e){const t=e.slice();for(let n=0;n<=t.length-2;n++){const e=this.random(n,t.length-1),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 q(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const Q=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},Z=(...e)=>{const t=t=>(...n)=>{const o=new Date,l=Q(o.getHours(),"00"),a=Q(o.getMinutes(),"00"),s=Q(o.getSeconds(),"00");console[t](`${l}:${a}:${s}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var X={hash:e=>{let t=0;for(let n=0;n{let t=e.toLowerCase();return t=t.replace(/[^a-z0-9]+/g,"-"),t=t.replace(/^-|-$/,""),t},uniqId:()=>Date.now().toString(36)+Math.random().toString(36).substring(2),encodeShape:function(e){return e.top+1<<0|e.right+1<<2|e.bottom+1<<4|e.left+1<<6},decodeShape:function(e){return{top:(e>>0&3)-1,right:(e>>2&3)-1,bottom:(e>>4&3)-1,left:(e>>6&3)-1}},encodePiece:function(e){return[e.idx,e.pos.x,e.pos.y,e.z,e.owner,e.group]},decodePiece:function(e){return{idx:e[0],pos:{x:e[1],y:e[2]},z:e[3],owner:e[4],group:e[5]}},encodePlayer:function(e){return[e.id,e.x,e.y,e.d,e.name,e.color,e.bgcolor,e.points,e.ts]},decodePlayer:function(e){return{id:e[0],x:e[1],y:e[2],d:e[3],name:e[4],color:e[5],bgcolor:e[6],points:e[7],ts:e[8]}},encodeGame:function(e){return[e.id,e.rng.type||"",q.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode,e.shapeMode,e.snapMode]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:q.unserialize(e[2])},puzzle:e[3],players:e[4],evtInfos:e[5],scoreMode:e[6],shapeMode:e[7],snapMode:e[8]}},coordByPieceIdx:function(e,t){const n=e.width/e.tileSize;return{x:t%n,y:Math.floor(t/n)}},asQueryArgs:function(e){const t=[];for(const n in e){const o=[n,e[n]].map(encodeURIComponent);t.push(o.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const J={name:"responsive-image",props:{src:String,title:{type:String,default:""},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},computed:{style(){return{display:"inline-block",verticalAlign:"text-bottom",backgroundImage:`url('${this.src}')`,backgroundRepeat:"no-repeat",backgroundSize:"contain",backgroundPosition:"center",width:this.width,height:this.height}}}};J.render=function(e,n,o,l,a,i){return s(),t("div",{style:i.style,title:o.title},null,12,["title"])};var ee=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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 te=m();y("data-v-a4fa5e7e");const ne={key:0,class:"autocomplete"};f();const oe=te(((e,o,a,i,u,m)=>(s(),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?(s(),t("div",ne,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,o)=>(s(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(s(!0),t(d,null,c(e.values,((n,o)=>(s(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ee.render=oe,ee.__scopeId="data-v-a4fa5e7e";const le=Z("NewImageDialog.vue");var ae=e({name:"new-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const 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(){le.info("onDragleave"),this.droppable=!1}}});const se=n("div",{class:"drop-target"},null,-1),ie={key:0,class:"has-image"},re={key:1},de={class:"upload"},ce=n("span",{class:"btn"},"Upload File",-1),ue={class:"area-settings"},pe=n("td",null,[n("label",null,"Title")],-1),ge=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),he=n("td",null,[n("label",null,"Tags")],-1),me={class:"area-buttons"},ye=i("🖼️ Post to gallery"),fe=i("🧩 Post to gallery "),ve=n("br",null,null,-1),we=i(" + set up game");ae.render=function(e,o,l,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),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))},[se,e.previewUrl?(s(),t("div",ie,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",re,[n("label",de,[n("input",{type:"file",style:{display:"none"},onChange:o[2]||(o[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ce])]))],34),n("div",ue,[n("table",null,[n("tr",null,[pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[6]||(o[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),ge,n("tr",null,[he,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":o[7]||(o[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",me,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:o[8]||(o[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ye],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[fe,ve,we],64))],8,["disabled"])])])])};var be=e({name:"edit-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{image:{type:Object,required:!0},autocompleteTags:{type:Function}},emits:{bgclick:null,saveClick:null},data:()=>({title:"",tags:[]}),created(){this.title=this.image.title,this.tags=this.image.tags.map((e=>e.title))},methods:{saveImage(){this.$emit("saveClick",{id:this.image.id,title:this.title,tags:this.tags})}}});const Ce={class:"area-image"},xe={class:"has-image"},ke={class:"area-settings"},Pe=n("td",null,[n("label",null,"Title")],-1),Ae=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),Se=n("td",null,[n("label",null,"Tags")],-1),ze={class:"area-buttons"};var Te,Ie,Me,Ee,De,Ne,_e,Ve;be.render=function(e,o,l,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),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",Ce,[n("div",xe,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",ke,[n("table",null,[n("tr",null,[Pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":o[1]||(o[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ae,n("tr",null,[Se,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":o[2]||(o[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",ze,[n("button",{class:"btn",onClick:o[3]||(o[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Ie=Te||(Te={}))[Ie.Flat=0]="Flat",Ie[Ie.Out=1]="Out",Ie[Ie.In=-1]="In",(Ee=Me||(Me={}))[Ee.FINAL=0]="FINAL",Ee[Ee.ANY=1]="ANY",(Ne=De||(De={}))[Ne.NORMAL=0]="NORMAL",Ne[Ne.ANY=1]="ANY",Ne[Ne.FLAT=2]="FLAT",(Ve=_e||(_e={}))[Ve.NORMAL=0]="NORMAL",Ve[Ve.REAL=1]="REAL";var Oe=e({name:"new-game-dialog",components:{ResponsiveImage:J},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Me.ANY,shapeMode:De.NORMAL,snapMode:_e.NORMAL}),methods:{onNewGameClick(){this.$emit("newGame",{tiles:this.tilesInt,image:this.image,scoreMode:this.scoreModeInt,shapeMode:this.shapeModeInt,snapMode:this.snapModeInt})}},computed:{canStartNewGame(){return!!(this.tilesInt&&this.image&&this.image.url&&[0,1].includes(this.scoreModeInt))},scoreModeInt(){return parseInt(`${this.scoreMode}`,10)},shapeModeInt(){return parseInt(`${this.shapeMode}`,10)},snapModeInt(){return parseInt(`${this.snapMode}`,10)},tilesInt(){return parseInt(`${this.tiles}`,10)}}});const Be={class:"area-image"},Ue={class:"has-image"},Re={key:0,class:"image-title"},$e={key:0,class:"image-title-title"},Ge={key:1,class:"image-title-dim"},Le={class:"area-settings"},Fe=n("td",null,[n("label",null,"Pieces")],-1),je=n("td",null,[n("label",null,"Scoring: ")],-1),We=i(" Any (Score when pieces are connected to each other or on final location)"),Ke=n("br",null,null,-1),He=i(" Final (Score when pieces are put to their final location)"),Ye=n("td",null,[n("label",null,"Shapes: ")],-1),qe=i(" Normal"),Qe=n("br",null,null,-1),Ze=i(" Any (flat pieces can occur anywhere)"),Xe=n("br",null,null,-1),Je=i(" Flat (all pieces flat on all sides)"),et=n("td",null,[n("label",null,"Snapping: ")],-1),tt=i(" Normal (pieces snap to final destination and to each other)"),nt=n("br",null,null,-1),ot=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),lt={class:"area-buttons"};Oe.render=function(e,o,i,d,c,h){const m=a("responsive-image");return s(),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",Be,[n("div",Ue,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",Re,[e.image.title?(s(),t("span",$e,'"'+r(e.image.title)+'"',1)):l("",!0),e.image.width||e.image.height?(s(),t("span",Ge,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):l("",!0)])):l("",!0)]),n("div",Le,[n("table",null,[n("tr",null,[Fe,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,[je,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]]),We]),Ke,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]]),He])])]),n("tr",null,[Ye,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]]),qe]),Qe,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]]),Ze]),Xe,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]]),Je])])]),n("tr",null,[et,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]]),tt]),nt,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]]),ot])])])])]),n("div",lt,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};const at=async(e,t,n)=>new Promise(((o,l)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.addEventListener("load",(function(e){o({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){l(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body)}));var st=(e,t)=>at("post",e,t),it=e({components:{ImageLibrary:Y,NewImageDialog:ae,EditImageDialog:be,NewGameDialog:Oe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await fetch(`/api/newgame-data${X.asQueryArgs(this.filters)}`),t=await e.json();this.images=t.images,this.tags=t.tags},async filtersChanged(){await this.loadImages()},onImageClicked(e){this.image=e,this.dialog="new-game"},onImageEditClicked(e){this.image=e,this.dialog="edit-image"},async uploadImage(e){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await st("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await fetch("/api/save-image",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({id:e.id,title:e.title,tags:e.tags})});return await t.json()},async onSaveImageClick(e){await this.saveImage(e),this.dialog="",await this.loadImages()},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await fetch("/api/newgame",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)});if(200===t.status){const e=await t.json();this.$router.push({name:"game",params:{id:e.id}})}}}});const rt={class:"upload-image-teaser"},dt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ct={key:0},ut=i(" Tags: "),pt=i(" Sort by: "),gt=n("option",{value:"date_desc"},"Newest first",-1),ht=n("option",{value:"date_asc"},"Oldest first",-1),mt=n("option",{value:"alpha_asc"},"A-Z",-1),yt=n("option",{value:"alpha_desc"},"Z-A",-1);it.render=function(e,o,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",rt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),dt]),n("div",null,[e.tags.length>0?(s(),t("label",ct,[ut,(s(!0),t(d,null,c(e.relevantTags,((n,o)=>(s(),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,[pt,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))},[gt,ht,mt,yt],544),[[w,e.filters.sort]])])]),n(m,{images:e.images,onImageClicked:e.onImageClicked,onImageEditClicked:e.onImageEditClicked},null,8,["images","onImageClicked","onImageEditClicked"]),"new-image"===e.dialog?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(s(),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?(s(),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 ft=e({name:"scores",props:{activePlayers:{type:Array,required:!0},idlePlayers:{type:Array,required:!0}},computed:{actives(){return this.activePlayers.sort(((e,t)=>t.points-e.points)),this.activePlayers},idles(){return this.idlePlayers.sort(((e,t)=>t.points-e.points)),this.idlePlayers}}});const vt={class:"scores"},wt=n("div",null,"Scores",-1),bt=n("td",null,"⚡",-1),Ct=n("td",null,"💤",-1);ft.render=function(e,o,l,a,i,u){return s(),t("div",vt,[wt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[bt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[Ct,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var xt=e({name:"puzzle-status",props:{finished:{type:Boolean,required:!0},duration:{type:Number,required:!0},piecesDone:{type:Number,required:!0},piecesTotal:{type:Number,required:!0}},computed:{icon(){return this.finished?"🏁":"⏳"},durationStr(){return B(this.duration)}}});const kt={class:"timer"};xt.render=function(e,o,l,a,i,d){return s(),t("div",kt,[n("div",null," 🧩 "+r(e.piecesDone)+"/"+r(e.piecesTotal),1),n("div",null,r(e.icon)+" "+r(e.durationStr),1),b(e.$slots,"default")])};var Pt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const At=m();y("data-v-4d56fc17");const St=n("td",null,[n("label",null,"Background: ")],-1),zt=n("td",null,[n("label",null,"Color: ")],-1),Tt=n("td",null,[n("label",null,"Name: ")],-1),It=n("td",null,[n("label",null,"Sounds: ")],-1),Mt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Et={class:"sound-volume"},Dt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Nt=At(((e,o,l,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:o[10]||(o[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[9]||(o[9]=u((()=>{}),["stop"]))},[n("tr",null,[St,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,[zt,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,[Tt,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,[It,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Mt,n("td",Et,[n("span",{onClick:o[5]||(o[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:o[6]||(o[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:o[7]||(o[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[8]||(o[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));Pt.render=Nt,Pt.__scopeId="data-v-4d56fc17";var _t=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const Vt={class:"preview"};_t.render=function(e,o,l,a,i,r){return s(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",Vt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Ot=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Me.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Me.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case De.FLAT:return["Flat","all pieces flat on all sides"];case De.ANY:return["Any","flat pieces can occur anywhere"];case De.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case _e.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case _e.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Bt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ut=n("td",null,"Image Title: ",-1),Rt=n("td",null,"Snap Mode: ",-1),$t=n("td",null,"Shape Mode: ",-1),Gt=n("td",null,"Score Mode: ",-1);Ot.render=function(e,o,l,a,i,d){return s(),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"]))},[Bt,n("tr",null,[Ut,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[Rt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[$t,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Gt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Lt=1,Ft=4,jt=2,Wt=3,Kt=2,Ht=4,Yt=3,qt=9,Qt=1,Zt=2,Xt=3,Jt=4,en=5,tn=6,nn=7,on=8,ln=10,an=11,sn=12,rn=13,dn=14,cn=15,un=16,pn=17,gn=18,hn=1,mn=2,yn=3;const fn=Z("Communication.js");let vn,wn=[],bn=e=>{wn.push(e)},Cn=[],xn=e=>{Cn.push(e)};let kn=0;const Pn=e=>{kn!==e&&(kn=e,xn(e))};function An(e){if(2===kn)try{vn.send(JSON.stringify(e))}catch(t){fn.info("unable to send message.. maybe because ws is invalid?")}}let Sn,zn;var Tn={connect:function(e,t,n){return Sn=0,zn={},Pn(3),new Promise((o=>{vn=new WebSocket(e,n+"|"+t),vn.onopen=()=>{Pn(2),An([Wt])},vn.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===Ft){const e=t[1];o(e)}else{if(l!==Lt)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&zn[o])return void delete zn[o];bn(t)}}},vn.onerror=()=>{throw Pn(1),"[ 2021-05-15 onerror ]"},vn.onclose=e=>{4e3===e.code||1001===e.code?Pn(4):Pn(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},o=await fetch(`/api/replay-data${X.asQueryArgs(n)}`);return await o.json()},disconnect:function(){vn&&vn.close(4e3),Sn=0,zn={}},sendClientEvent:function(e){Sn++,zn[Sn]=e,An([jt,Sn,zn[Sn]])},onServerChange:function(e){bn=e;for(const t of wn)bn(t);wn=[]},onConnectionStateChange:function(e){xn=e;for(const t of Cn)xn(t);Cn=[]},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},In=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===Tn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===Tn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const Mn={key:0,class:"overlay connection-lost"},En={key:0,class:"overlay-content"},Dn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),Nn={key:1,class:"overlay-content"},_n=n("div",null,"Connecting...",-1);In.render=function(e,o,a,i,r,d){return e.show?(s(),t("div",Mn,[e.lostConnection?(s(),t("div",En,[Dn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(s(),t("div",Nn,[_n])):l("",!0)])):l("",!0)};var Vn=e({name:"help-overlay",emits:{bgclick:null}});const On=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Bn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Un=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),Rn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),$n=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Gn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),Ln=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),Fn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),jn=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Wn=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),Hn=n("tr",null,[n("td",null,"👤 Toggle player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Yn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),qn=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),Qn=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),Zn=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);Vn.render=function(e,o,l,a,i,r){return s(),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"]))},[On,Bn,Un,Rn,$n,Gn,Ln,Fn,jn,Wn,Kn,Hn,Yn,qn,Qn,Zn])])};var Xn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),Jn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),eo=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),to=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),no=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function oo(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var lo={createCanvas:oo,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=oo(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=oo(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 ao=Z("Debug.js");let so=0,io=0;var ro=e=>{so=performance.now(),io=e},co=e=>{const t=performance.now(),n=t-so;n>io&&ao.log(e+": "+n),so=t};function uo(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function po(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var go={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:uo,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:po,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 uo(po(e),po(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 ho=Z("PuzzleGraphics.js");function mo(e,t){const n=X.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var yo={loadPuzzleBitmaps:async function(e){const t=await lo.loadImageToBitmap(e.info.imageUrl),n=await lo.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){ho.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,s=o/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:l,y:l},r=go.pointAdd(a,{x:o,y:0}),c=go.pointAdd(r,{x:0,y:o}),u=go.pointSub(c,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oX.decodePiece(fo[e].puzzle.tiles[t]),Do=(e,t)=>Eo(e,t).group,No=(e,t)=>{const n=fo[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},_o=(e,t)=>{const n=fo[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=fo[e].puzzle.info,o=X.coordByPieceIdx(n,t),l=o.x*n.tileSize,a=o.y*n.tileSize;return{x:l,y:a}}(e,t);return go.pointAdd(o,l)},Vo=(e,t)=>Eo(e,t).pos,Oo=e=>{const t=Jo(e),n=el(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}},Bo=(e,t)=>{const n=Go(e),o=Eo(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},Uo=(e,t)=>Eo(e,t).z,Ro=(e,t)=>{for(const n of fo[e].puzzle.tiles){const e=X.decodePiece(n);if(e.owner===t)return e.idx}return-1},$o=e=>fo[e].puzzle.info.tileDrawSize,Go=e=>fo[e].puzzle.info.tileSize,Lo=e=>fo[e].puzzle.data.maxGroup,Fo=e=>fo[e].puzzle.data.maxZ;function jo(e,t){const n=fo[e].puzzle.info,o=X.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const Wo=(e,t,n)=>{for(const o of t)Mo(e,o,{z:n})},Ko=(e,t,n)=>{const o=Vo(e,t);Mo(e,t,{pos:go.pointAdd(o,n)})},Ho=(e,t,n)=>{const o=$o(e),l=Oo(e),a=n;for(const s of t){const t=Eo(e,s);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 s of t)Ko(e,s,a)},Yo=(e,t)=>Eo(e,t).owner,qo=(e,t)=>{for(const n of t)Mo(e,n,{owner:-1,z:1})},Qo=(e,t,n)=>{for(const o of t)Mo(e,o,{owner:n})};function Zo(e,t){const n=fo[e].puzzle.tiles,o=X.decodePiece(n[t]),l=[];if(o.group)for(const a of n){const e=X.decodePiece(a);e.group===o.group&&l.push(e.idx)}else l.push(o.idx);return l}const Xo=(e,t)=>{const n=wo(e,t);return n?n.points:0},Jo=e=>fo[e].puzzle.info.table.width,el=e=>fo[e].puzzle.info.table.height;var tl={setGame:function(e,t){fo[e]=t},exists:function(e){return!!fo[e]||!1},playerExists:Co,getActivePlayers:function(e,t){const n=t-30*_;return xo(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*_;return xo(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){Co(e,t)?To(e,t,{ts:n}):bo(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:zo,getPieceCount:ko,getImageUrl:function(e){var t;const n=(null==(t=fo[e].puzzle.info.image)?void 0:t.url)||fo[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return fo[e]||null},getAllGames:function(){return Object.values(fo).sort(((e,t)=>So(e.id)===So(t.id)?t.puzzle.data.started-e.puzzle.data.started:So(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=wo(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=wo(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=wo(e,t);return n?n.name:null},getPlayerIndexById:vo,getPlayerIdByIndex:function(e,t){return fo[e].players.length>t?X.decodePlayer(fo[e].players[t]).id:null},changePlayer:To,setPlayer:bo,setPiece:function(e,t,n){fo[e].puzzle.tiles[t]=X.encodePiece(n)},setPuzzleData:function(e,t){fo[e].puzzle.data=t},getTableWidth:Jo,getTableHeight:el,getPuzzle:e=>fo[e].puzzle,getRng:e=>fo[e].rng.obj,getPuzzleWidth:e=>fo[e].puzzle.info.width,getPuzzleHeight:e=>fo[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return fo[e].puzzle.tiles.map(X.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Ro(e,t);return n<0?null:fo[e].puzzle.tiles[n]},getPieceDrawOffset:e=>fo[e].puzzle.info.tileDrawOffset,getPieceDrawSize:$o,getFinalPiecePos:_o,getStartTs:e=>fo[e].puzzle.data.started,getFinishTs:e=>fo[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=fo[e].puzzle,s=function(e,t){return t in fo[e].evtInfos?fo[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([hn,a.data])},d=t=>{i.push([mn,X.encodePiece(Eo(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=wo(e,t);n&&i.push([yn,X.encodePlayer(n)])},p=n[0];if(p===tn){const l=n[1];To(e,t,{bgcolor:l,ts:o}),u()}else if(p===nn){const l=n[1];To(e,t,{color:l,ts:o}),u()}else if(p===on){const l=`${n[1]}`.substr(0,16);To(e,t,{name:l,ts:o}),u()}else if(p===qt){const l=n[1],a=n[2],s=wo(e,t);if(s){const n=s.x-l,i=s.y-a;To(e,t,{ts:o,x:n,y:i}),u()}}else if(p===Qt){const l={x:n[1],y:n[2]};To(e,t,{d:1,ts:o}),u(),s._last_mouse_down=l;const a=((e,t)=>{const n=fo[e].puzzle.info,o=fo[e].puzzle.tiles;let l=-1,a=-1;for(let s=0;sl)&&(l=e.z,a=s)}return a})(e,l);if(a>=0){const n=Fo(e)+1;Io(e,{maxZ:n}),r();const o=Zo(e,a);Wo(e,o,Fo(e)),Qo(e,o,t),c(o)}s._last_mouse=l}else if(p===Xt){const l=n[1],a=n[2],i={x:l,y:a};if(null===s._last_mouse_down)To(e,t,{x:l,y:a,ts:o}),u();else{const n=Ro(e,t);if(n>=0){To(e,t,{x:l,y:a,ts:o}),u();const r=Zo(e,n);let d=go.pointInBounds(i,Oo(e))&&go.pointInBounds(s._last_mouse_down,Oo(e));for(const t of r){const n=Bo(e,t);if(go.pointInBounds(i,n)){d=!0;break}}if(d){const t=l-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Ho(e,r,{x:t,y:n}),c(r)}}else To(e,t,{ts:o}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===Zt){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Ro(e,t);if(g>=0){const n=Zo(e,g);Qo(e,n,0),c(n);const s=Vo(e,g),i=_o(e,g);let h=!1;if(Ao(e)===_e.REAL){for(const t of n)if(No(e,t)){h=!0;break}}else h=!0;if(h&&go.pointDistance(i,s){const l=fo[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=Do(e,t),l=Do(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=Vo(e,t),s=go.pointAdd(Vo(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(go.pointDistance(a,s){const o=fo[e].puzzle.tiles,l=Do(e,t),a=Do(e,n);let s;const i=[];l&&i.push(l),a&&i.push(a),l?s=l:a?s=a:(Io(e,{maxGroup:Lo(e)+1}),r(),s=Lo(e));if(Mo(e,t,{group:s}),d(t),Mo(e,n,{group:s}),d(n),i.length>0)for(const r of o){const t=X.decodePiece(r);i.includes(t.group)&&(Mo(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),l=Zo(e,t),((e,t)=>-1===Yo(e,t))(e,n))qo(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=Uo(e,o);t>n&&(n=t)}return n})(e,l);Wo(e,l,t)}return c(l),!0}return!1};let a=!1;for(const t of Zo(e,g)){const o=jo(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&&Po(e)===Me.ANY){const n=Xo(e,t)+1;To(e,t,{d:p,ts:o,points:n}),u()}else To(e,t,{d:p,ts:o}),u();a&&Ao(e)===_e.REAL&&zo(e)===ko(e)&&(Io(e,{finished:o}),r()),a&&l&&l(t)}}else To(e,t,{d:p,ts:o}),u();s._last_mouse=i}else if(p===Jt){const l=n[1],a=n[2];To(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else if(p===en){const l=n[1],a=n[2];To(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else To(e,t,{ts:o}),u();return function(e,t,n){fo[e].evtInfos[t]=n}(e,t,s),i}};let nl=-10,ol=20,ll=2,al=15;class sl{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=nl+Math.random()*ol,this.vy=-1*(ll+Math.random()*al),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;ll=t/2,al=t-ll;const n=1/4*this.canvas.width/(t/2);nl=-n,ol=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new sl(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new sl(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{localStorage.setItem(e,t)},yl=e=>localStorage.getItem(e);var fl=(e,t)=>{ml(e,`${t}`)},vl=(e,t)=>{const n=yl(e);if(null===n)return t;const o=parseInt(n,10);return isNaN(o)?t:o},wl=(e,t)=>{ml(e,t?"1":"0")},bl=(e,t)=>{const n=yl(e);return null===n?t:"1"===n},Cl=(e,t)=>{ml(e,t)},xl=(e,t)=>{const n=yl(e);return null===n?t:n};const kl={"./grab.png":Jn,"./grab_mask.png":eo,"./hand.png":to,"./hand_mask.png":no},Pl={"./click.mp3":Xn},Al="replay";let Sl=!0,zl=!0;let Tl=!0;async function Il(e,t,n,o,l,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=Pl["./click.mp3"].default,i=new Audio(s),r=await lo.loadImageToBitmap(kl["./grab.png"].default),d=await lo.loadImageToBitmap(kl["./hand.png"].default),c=await lo.loadImageToBitmap(kl["./grab_mask.png"].default),u=await lo.loadImageToBitmap(kl["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?c:u;y[t]=await createImageBitmap(lo.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,Tl=!0})),t}(l,lo.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};Tn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Tn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===o){const o=await Tn.connect(n,e,t),l=X.decodeGame(o);tl.setGame(l.id,l),C=()=>V()}else{if(o!==Al)throw"[ 2020-12-22 MODE invalid, must be play|replay ]";{const t=await b(e);if(!t.game)throw"[ 2021-05-29 no game received ]";const n=X.decodeGame(t.game);tl.setGame(n.id,n),w.lastRealTs=V(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Tl=!0};await x();const k=tl.getPieceDrawOffset(e),P=tl.getPieceDrawSize(e),A=tl.getPuzzleWidth(e),S=tl.getPuzzleHeight(e),z=tl.getTableWidth(e),T=tl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},M={w:A,h:S},E={w:P,h:P},D=await yo.loadPuzzleBitmaps(tl.getPuzzle(e)),_=new rl(v,tl.getRng(e));_.init();const O=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const B=function(){let e=0,t=0,n=1;const 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=(e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0},s=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>a(l(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),U=()=>{B.reset(),B.move(-(z-v.width)/2,-(T-v.height)/2);const e=B.worldDimToViewport(M),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([Qt,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([Zt,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([Xt,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Jt:en;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([ln]),o===Al&&("KeyI"===e.code&&v([rn]),"KeyO"===e.code&&v([dn]),"KeyP"===e.code&&v([sn])),"KeyF"===e.code&&v([pn]),"KeyG"===e.code&&v([gn]),"KeyM"===e.code&&v([an]),"KeyN"===e.code&&v([cn]),"KeyC"===e.code&&v([un]))}));const v=e=>{l.push(e)};return{addEvent:v,consumeAll:()=>{if(0===l.length)return[];const e=l.slice();return l=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const o=(p?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});v([qt,l.w,l.h]),f&&(f[0]-=l.w,f[1]-=l.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([Jt,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([en,...e])}},setHotkeys:e=>{a=e}}}(v,window,B,o),$=tl.getImageUrl(e),G=()=>{const t=tl.getStartTs(e),n=tl.getFinishTs(e),o=C();a.setFinished(!!n),a.setDuration((n||o)-t)};G(),a.setPiecesDone(tl.getFinishedPiecesCount(e)),a.setPiecesTotal(tl.getPieceCount(e));const L=C();a.setActivePlayers(tl.getActivePlayers(e,L)),a.setIdlePlayers(tl.getIdlePlayers(e,L));const F=!!tl.getFinishTs(e);let j=F;const W=()=>j&&!F,K=()=>vl(dl,100),H=()=>bl(cl,!1),Y=()=>bl(hl,!0),q=()=>{const e=K();i.volume=e/100,i.play()},Q=()=>o===Al?xl(ul,"#222222"):tl.getPlayerBgColor(e,t)||xl(ul,"#222222"),Z=()=>o===Al?xl(pl,"#ffffff"):tl.getPlayerColor(e,t)||xl(pl,"#ffffff");let J="",ee="",te=!1;const ne=e=>{te=e;const[t,n]=e?[J,"grab"]:[ee,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},oe=e=>{J=lo.colorizedCanvas(r,c,e).toDataURL(),ee=lo.colorizedCanvas(d,u,e).toDataURL(),ne(te)};oe(Z());const le=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},ae=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,le())},ie=()=>{w.paused=!w.paused,le()},re=[];let de;let ce;if("play"===o?re.push(setInterval((()=>{G()}),1e3)):o===Al&&le(),"play"===o)Tn.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case yn:{const n=X.decodePlayer(a);n.id!==t&&(tl.setPlayer(e,n.id,n),Tl=!0)}break;case mn:{const t=X.decodePiece(a);tl.setPiece(e,t.idx,t),Tl=!0}break;case hn:tl.setPuzzleData(e,a),Tl=!0}j=!!tl.getFinishTs(e)}));else if(o===Al){const t=(t,n)=>{const o=t;if(o[0]===Kt){const t=o[1];return tl.addPlayer(e,t,n),!0}if(o[0]===Ht){const t=tl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return tl.addPlayer(e,t,n),!0}if(o[0]===Yt){const t=tl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const l=o[2];return tl.handleInput(e,t,l,n),!0}return!1};let n=w.lastGameTs;const o=async()=>{w.logPointer+1>=w.log.length&&await b(e);const l=V();if(w.paused)return w.lastRealTs=l,void(de=setTimeout(o,50));const a=(l-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const o=w.log[w.logPointer],l=n+o[o.length-1],a=w.log[e],i=a[a.length-1],r=l+i;if(r>s){s+500*N{let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=o*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,l(i);a(c/o),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===o){const o=n[0];if(o===qt){const e=n[1],t=n[2],o=B.worldDimToViewport({w:e,h:t});Tl=!0,B.move(o.w,o.h)}else if(o===Xt){if(ue&&!tl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Tl=!0,B.move(o,l),ue=t}}else if(o===nn)oe(n[1]);else if(o===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(o===Zt)ue=null,ne(!1);else if(o===Jt){const e={x:n[1],y:n[2]};Tl=!0,B.zoom("in",B.worldToViewport(e))}else if(o===en){const e={x:n[1],y:n[2]};Tl=!0,B.zoom("out",B.worldToViewport(e))}else o===ln?a.togglePreview():o===an?a.toggleSoundsEnabled():o===cn?a.togglePlayerNames():o===un?U():o===pn?(Sl=!Sl,Tl=!0):o===gn&&(zl=!zl,Tl=!0);const l=C();tl.handleInput(e,t,n,l,(e=>{H()&&q()})).length>0&&(Tl=!0),Tn.sendClientEvent(n)}else if(o===Al){const e=n[0];if(e===sn)ie();else if(e===dn)se();else if(e===rn)ae();else if(e===qt){const e=n[1],t=n[2];Tl=!0,B.move(e,t)}else if(e===Xt){if(ue){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Tl=!0,B.move(o,l),ue=t}}else if(e===nn)oe(n[1]);else if(e===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(e===Zt)ue=null,ne(!1);else if(e===Jt){const e={x:n[1],y:n[2]};Tl=!0,B.zoom("in",B.worldToViewport(e))}else if(e===en){const e={x:n[1],y:n[2]};Tl=!0,B.zoom("out",B.worldToViewport(e))}else e===ln?a.togglePreview():e===an?a.toggleSoundsEnabled():e===cn?a.togglePlayerNames():e===un?U():e===pn?(Sl=!Sl,Tl=!0):e===gn&&(zl=!zl,Tl=!0)}j=!!tl.getFinishTs(e),W()&&(_.update(),Tl=!0)},render:async()=>{if(!Tl)return;const n=C();let l,s,i;window.DEBUG&&ro(0),O.fillStyle=Q(),O.fillRect(0,0,v.width,v.height),window.DEBUG&&co("clear done"),l=B.worldToViewportRaw(I),s=B.worldDimToViewportRaw(M),O.fillStyle="rgba(255, 255, 255, .3)",O.fillRect(l.x,l.y,s.w,s.h),window.DEBUG&&co("board done");const r=tl.getPiecesSortedByZIndex(e);window.DEBUG&&co("get tiles done"),s=B.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?Sl:zl)&&(i=D[e.idx],l=B.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),O.drawImage(i,0,0,i.width,i.height,l.x,l.y,s.w,s.h));window.DEBUG&&co("tiles done");const d=[];for(const a of tl.getActivePlayers(e,n))c=a,(o===Al||c.id!==t)&&(i=await f(a),l=B.worldToViewport(a),O.drawImage(i,l.x-g,l.y-m),Y()&&d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var c;O.fillStyle="white",O.textAlign="center";for(const[e,t,o]of d)O.fillText(e,t,o);window.DEBUG&&co("players done"),a.setActivePlayers(tl.getActivePlayers(e,n)),a.setIdlePlayers(tl.getIdlePlayers(e,n)),a.setPiecesDone(tl.getFinishedPiecesCount(e)),window.DEBUG&&co("HUD done"),W()&&_.render(),Tl=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{Cl(ul,e),R.addEvent([tn,e])},onColorChange:e=>{Cl(pl,e),R.addEvent([nn,e])},onNameChange:e=>{Cl(gl,e),R.addEvent([on,e])},onSoundsEnabledChange:e=>{wl(cl,e)},onSoundsVolumeChange:e=>{fl(dl,e),q()},onShowPlayerNamesChange:e=>{wl(hl,e)},replayOnSpeedUp:ae,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:$,player:{background:Q(),color:Z(),name:o===Al?xl(gl,"anon"):tl.getPlayerName(e,t)||xl(gl,"anon"),soundsEnabled:H(),soundsVolume:K(),showPlayerNames:Y()},game:tl.get(e),disconnect:Tn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var Ml=e({name:"game",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,ConnectionOverlay:In,HelpOverlay:Vn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await Il(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const El={id:"game"},Dl={key:1,class:"overlay"},Nl=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),_l={class:"menu"},Vl={class:"tabs"},Ol=i("🧩 Puzzles");Ml.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",El,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Dl,[Nl])):l("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",_l,[n("div",Vl,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Ol])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Bl=e({name:"replay",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,HelpOverlay:Vn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await Il(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,Al,this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Ul={id:"replay"},Rl={key:1,class:"overlay"},$l=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Gl={class:"menu"},Ll={class:"tabs"},Fl=i("🧩 Puzzles");Bl.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Ul,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Rl,[$l])):l("",!0),n(v,{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:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Gl,[n("div",Ll,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Fl])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=await fetch("/api/conf"),t=await e.json();const n=k({history:P(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:it},{name:"game",path:"/g/:id",component:Ml},{name:"replay",path:"/replay/:id",component:Bl}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const o=A(S);o.config.globalProperties.$config=t,o.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=X.uniqId(),localStorage.setItem("ID",e)),e}(),o.use(n),o.mount("#app")})(); diff --git a/build/public/assets/index.93936dee.js b/build/public/assets/index.93936dee.js deleted file mode 100644 index e6ab743..0000000 --- a/build/public/assets/index.93936dee.js +++ /dev/null @@ -1 +0,0 @@ -import{d as e,c as t,a as n,w as l,b as o,r as a,o as s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),M=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:l((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:l((()=>[M])),_:1})])])):o("",!0),n(g)])};const E=864e5,D=e=>{const t=Math.floor(e/E);e%=E;const n=Math.floor(e/36e5);e%=36e5;const l=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${l}m ${Math.floor(e/1e3)}s`};var N=1,_=1e3,V=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},O=(e,t)=>D(t-e),B=D,U=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",l=e,o=t||V();return`${n} ${O(l,o)}`}}});const R={class:"game-info-text"},$=n("br",null,null,-1),G=n("br",null,null,-1),L=n("br",null,null,-1),F=i(" ↪️ Watch replay ");U.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:l((()=>[n("span",R,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),$,i(" 👥 "+r(e.game.players),1),G,i(" "+r(e.time(e.game.started,e.game.finished)),1),L])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:l((()=>[F])),_:1},8,["to"])):o("",!0)],4)};var j=e({components:{GameTeaser:U},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await fetch("/api/index-data"),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const W=n("h1",null,"Running games",-1),K=n("h1",null,"Finished games",-1);j.render=function(e,l,o,i,r,u){const p=a("game-teaser");return s(),t("div",null,[W,(s(!0),t(d,null,c(e.gamesRunning,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128)),K,(s(!0),t(d,null,c(e.gamesFinished,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128))])};var H=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});H.render=function(e,l,o,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:l[2]||(l[2]=(...t)=>e.onClick&&e.onClick(...t))},[n("div",{class:"btn edit",onClick:l[1]||(l[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")],4)};var Y=e({name:"image-library",components:{ImageTeaser:H},props:{images:{type:Array,required:!0}},emits:{imageClicked:null,imageEditClicked:null},methods:{imageClicked(e){this.$emit("imageClicked",e)},imageEditClicked(e){this.$emit("imageEditClicked",e)}}});Y.render=function(e,n,l,o,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,l)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:l},null,8,["image","onClick","onEditClick"])))),128))])};class q{constructor(e){this.rand_high=e||3735929054,this.rand_low=1231121986^e}random(e,t){this.rand_high=(this.rand_high<<16)+(this.rand_high>>16)+this.rand_low&4294967295,this.rand_low=this.rand_low+this.rand_high&4294967295;return e+(this.rand_high>>>0)/4294967295*(t-e+1)|0}choice(e){return e[this.random(0,e.length-1)]}shuffle(e){const t=e.slice();for(let n=0;n<=t.length-2;n++){const e=this.random(n,t.length-1),l=t[n];t[n]=t[e],t[e]=l}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new q(0);return t.rand_high=e.rand_high,t.rand_low=e.rand_low,t}}const Q=(e,t)=>{const n=`${e}`;return n.length>=t.length?n:t.substr(0,t.length-n.length)+n},Z=(...e)=>{const t=t=>(...n)=>{const l=new Date,o=Q(l.getHours(),"00"),a=Q(l.getMinutes(),"00"),s=Q(l.getSeconds(),"00");console[t](`${o}:${a}:${s}`,...e,...n)};return{log:t("log"),error:t("error"),info:t("info")}};var X={hash:e=>{let t=0;for(let n=0;n{let t=e.toLowerCase();return t=t.replace(/[^a-z0-9]+/g,"-"),t=t.replace(/^-|-$/,""),t},uniqId:()=>Date.now().toString(36)+Math.random().toString(36).substring(2),encodeShape:function(e){return e.top+1<<0|e.right+1<<2|e.bottom+1<<4|e.left+1<<6},decodeShape:function(e){return{top:(e>>0&3)-1,right:(e>>2&3)-1,bottom:(e>>4&3)-1,left:(e>>6&3)-1}},encodePiece:function(e){return[e.idx,e.pos.x,e.pos.y,e.z,e.owner,e.group]},decodePiece:function(e){return{idx:e[0],pos:{x:e[1],y:e[2]},z:e[3],owner:e[4],group:e[5]}},encodePlayer:function(e){return[e.id,e.x,e.y,e.d,e.name,e.color,e.bgcolor,e.points,e.ts]},decodePlayer:function(e){return{id:e[0],x:e[1],y:e[2],d:e[3],name:e[4],color:e[5],bgcolor:e[6],points:e[7],ts:e[8]}},encodeGame:function(e){return[e.id,e.rng.type||"",q.serialize(e.rng.obj),e.puzzle,e.players,e.evtInfos,e.scoreMode,e.shapeMode,e.snapMode]},decodeGame:function(e){return{id:e[0],rng:{type:e[1],obj:q.unserialize(e[2])},puzzle:e[3],players:e[4],evtInfos:e[5],scoreMode:e[6],shapeMode:e[7],snapMode:e[8]}},coordByPieceIdx:function(e,t){const n=e.width/e.tileSize;return{x:t%n,y:Math.floor(t/n)}},asQueryArgs:function(e){const t=[];for(const n in e){const l=[n,e[n]].map(encodeURIComponent);t.push(l.join("="))}return 0===t.length?"":`?${t.join("&")}`}};const J={name:"responsive-image",props:{src:String,title:{type:String,default:""},height:{type:String,default:"100%"},width:{type:String,default:"100%"}},computed:{style(){return{display:"inline-block",verticalAlign:"text-bottom",backgroundImage:`url('${this.src}')`,backgroundRepeat:"no-repeat",backgroundSize:"contain",backgroundPosition:"center",width:this.width,height:this.height}}}};J.render=function(e,n,l,o,a,i){return s(),t("div",{style:i.style,title:l.title},null,12,["title"])};var ee=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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 te=m();y("data-v-a4fa5e7e");const ne={key:0,class:"autocomplete"};f();const le=te(((e,l,a,i,u,m)=>(s(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.input=t),placeholder:"Plants, People",onChange:l[2]||(l[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:l[3]||(l[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:l[4]||(l[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(s(),t("div",ne,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,l)=>(s(),t("li",{key:l,class:{active:l===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):o("",!0),(s(!0),t(d,null,c(e.values,((n,l)=>(s(),t("span",{key:l,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ee.render=le,ee.__scopeId="data-v-a4fa5e7e";const oe=Z("NewImageDialog.vue");var ae=e({name:"new-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const l=n[0];return l.type.startsWith("image/")?l:null},onFileSelect(e){const t=e.target;if(!t.files)return;const n=t.files[0];n&&this.preview(n)},preview(e){const t=new FileReader;t.readAsDataURL(e),t.onload=t=>{this.previewUrl=t.target.result,this.file=e}},postToGallery(){this.$emit("postToGalleryClick",{file:this.file,title:this.title,tags:this.tags})},setupGameClick(){this.$emit("setupGameClick",{file:this.file,title:this.title,tags:this.tags})},onDrop(e){this.droppable=!1;const t=this.imageFromDragEvt(e);if(!t)return!1;const n=t.getAsFile();return!!n&&(this.file=n,this.preview(n),e.preventDefault(),!1)},onDragover(e){return!!this.imageFromDragEvt(e)&&(this.droppable=!0,e.preventDefault(),!1)},onDragleave(){oe.info("onDragleave"),this.droppable=!1}}});const se=n("div",{class:"drop-target"},null,-1),ie={key:0,class:"has-image"},re={key:1},de={class:"upload"},ce=n("span",{class:"btn"},"Upload File",-1),ue={class:"area-settings"},pe=n("td",null,[n("label",null,"Title")],-1),ge=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),he=n("td",null,[n("label",null,"Tags")],-1),me={class:"area-buttons"},ye=i("🖼️ Post to gallery"),fe=i("🧩 Post to gallery "),ve=n("br",null,null,-1),we=i(" + set up game");ae.render=function(e,l,o,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),t("div",{class:"overlay new-image-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:l[3]||(l[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:l[4]||(l[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:l[5]||(l[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[se,e.previewUrl?(s(),t("div",ie,[n("span",{class:"remove btn",onClick:l[1]||(l[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",re,[n("label",de,[n("input",{type:"file",style:{display:"none"},onChange:l[2]||(l[2]=(...t)=>e.onFileSelect&&e.onFileSelect(...t)),accept:"image/*"},null,32),ce])]))],34),n("div",ue,[n("table",null,[n("tr",null,[pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[6]||(l[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),ge,n("tr",null,[he,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":l[7]||(l[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",me,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:l[8]||(l[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ye],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:l[9]||(l[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[fe,ve,we],64))],8,["disabled"])])])])};var be=e({name:"edit-image-dialog",components:{ResponsiveImage:J,TagsInput:ee},props:{image:{type:Object,required:!0},autocompleteTags:{type:Function}},emits:{bgclick:null,saveClick:null},data:()=>({title:"",tags:[]}),created(){this.title=this.image.title,this.tags=this.image.tags.map((e=>e.title))},methods:{saveImage(){this.$emit("saveClick",{id:this.image.id,title:this.title,tags:this.tags})}}});const Ce={class:"area-image"},xe={class:"has-image"},ke={class:"area-settings"},Pe=n("td",null,[n("label",null,"Title")],-1),Ae=n("tr",null,[n("td",{colspan:"2"},[n("div",{class:"hint"},"Feel free to leave a credit to the artist/photographer in the title :)")])],-1),Se=n("td",null,[n("label",null,"Tags")],-1),ze={class:"area-buttons"};var Te,Ie,Me,Ee,De,Ne,_e,Ve;be.render=function(e,l,o,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),t("div",{class:"overlay edit-image-dialog",onClick:l[5]||(l[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[4]||(l[4]=u((()=>{}),["stop"]))},[n("div",Ce,[n("div",xe,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",ke,[n("table",null,[n("tr",null,[Pe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),Ae,n("tr",null,[Se,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":l[2]||(l[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",ze,[n("button",{class:"btn",onClick:l[3]||(l[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Ie=Te||(Te={}))[Ie.Flat=0]="Flat",Ie[Ie.Out=1]="Out",Ie[Ie.In=-1]="In",(Ee=Me||(Me={}))[Ee.FINAL=0]="FINAL",Ee[Ee.ANY=1]="ANY",(Ne=De||(De={}))[Ne.NORMAL=0]="NORMAL",Ne[Ne.ANY=1]="ANY",Ne[Ne.FLAT=2]="FLAT",(Ve=_e||(_e={}))[Ve.NORMAL=0]="NORMAL",Ve[Ve.REAL=1]="REAL";var Oe=e({name:"new-game-dialog",components:{ResponsiveImage:J},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Me.ANY,shapeMode:De.NORMAL,snapMode:_e.NORMAL}),methods:{onNewGameClick(){this.$emit("newGame",{tiles:this.tilesInt,image:this.image,scoreMode:this.scoreModeInt,shapeMode:this.shapeModeInt,snapMode:this.snapModeInt})}},computed:{canStartNewGame(){return!!(this.tilesInt&&this.image&&this.image.url&&[0,1].includes(this.scoreModeInt))},scoreModeInt(){return parseInt(`${this.scoreMode}`,10)},shapeModeInt(){return parseInt(`${this.shapeMode}`,10)},snapModeInt(){return parseInt(`${this.snapMode}`,10)},tilesInt(){return parseInt(`${this.tiles}`,10)}}});const Be={class:"area-image"},Ue={class:"has-image"},Re={key:0,class:"image-title"},$e={key:0,class:"image-title-title"},Ge={key:1,class:"image-title-dim"},Le={class:"area-settings"},Fe=n("td",null,[n("label",null,"Pieces")],-1),je=n("td",null,[n("label",null,"Scoring: ")],-1),We=i(" Any (Score when pieces are connected to each other or on final location)"),Ke=n("br",null,null,-1),He=i(" Final (Score when pieces are put to their final location)"),Ye=n("td",null,[n("label",null,"Shapes: ")],-1),qe=i(" Normal"),Qe=n("br",null,null,-1),Ze=i(" Any (flat pieces can occur anywhere)"),Xe=n("br",null,null,-1),Je=i(" Flat (all pieces flat on all sides)"),et=n("td",null,[n("label",null,"Snapping: ")],-1),tt=i(" Normal (pieces snap to final destination and to each other)"),nt=n("br",null,null,-1),lt=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ot={class:"area-buttons"};Oe.render=function(e,l,i,d,c,h){const m=a("responsive-image");return s(),t("div",{class:"overlay new-game-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",Be,[n("div",Ue,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",Re,[e.image.title?(s(),t("span",$e,'"'+r(e.image.title)+'"',1)):o("",!0),e.image.width||e.image.height?(s(),t("span",Ge,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):o("",!0)])):o("",!0)]),n("div",Le,[n("table",null,[n("tr",null,[Fe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[je,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[2]||(l[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),We]),Ke,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[3]||(l[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),He])])]),n("tr",null,[Ye,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[4]||(l[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),qe]),Qe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[5]||(l[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),Ze]),Xe,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[6]||(l[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),Je])])]),n("tr",null,[et,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[7]||(l[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),tt]),nt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[8]||(l[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),lt])])])])]),n("div",ot,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:l[9]||(l[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};const at=async(e,t,n)=>new Promise(((l,o)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.addEventListener("load",(function(e){l({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){o(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body)}));var st=(e,t)=>at("post",e,t),it=e({components:{ImageLibrary:Y,NewImageDialog:ae,EditImageDialog:be,NewGameDialog:Oe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await fetch(`/api/newgame-data${X.asQueryArgs(this.filters)}`),t=await e.json();this.images=t.images,this.tags=t.tags},async filtersChanged(){await this.loadImages()},onImageClicked(e){this.image=e,this.dialog="new-game"},onImageEditClicked(e){this.image=e,this.dialog="edit-image"},async uploadImage(e){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await st("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await fetch("/api/save-image",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({id:e.id,title:e.title,tags:e.tags})});return await t.json()},async onSaveImageClick(e){await this.saveImage(e),this.dialog="",await this.loadImages()},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await fetch("/api/newgame",{method:"post",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)});if(200===t.status){const e=await t.json();this.$router.push({name:"game",params:{id:e.id}})}}}});const rt={class:"upload-image-teaser"},dt=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),ct={key:0},ut=i(" Tags: "),pt=i(" Sort by: "),gt=n("option",{value:"date_desc"},"Newest first",-1),ht=n("option",{value:"date_asc"},"Oldest first",-1),mt=n("option",{value:"alpha_asc"},"A-Z",-1),yt=n("option",{value:"alpha_desc"},"Z-A",-1);it.render=function(e,l,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",rt,[n("div",{class:"btn btn-big",onClick:l[1]||(l[1]=t=>e.dialog="new-image")},"Upload your image"),dt]),n("div",null,[e.tags.length>0?(s(),t("label",ct,[ut,(s(!0),t(d,null,c(e.relevantTags,((n,l)=>(s(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:l,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):o("",!0),n("label",null,[pt,p(n("select",{"onUpdate:modelValue":l[2]||(l[2]=t=>e.filters.sort=t),onChange:l[3]||(l[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[gt,ht,mt,yt],544),[[w,e.filters.sort]])])]),n(m,{images:e.images,onImageClicked:e.onImageClicked,onImageEditClicked:e.onImageEditClicked},null,8,["images","onImageClicked","onImageEditClicked"]),"new-image"===e.dialog?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:l[4]||(l[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):o("",!0),"edit-image"===e.dialog?(s(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:l[5]||(l[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):o("",!0),e.image&&"new-game"===e.dialog?(s(),t(v,{key:2,onBgclick:l[6]||(l[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):o("",!0)])};var ft=e({name:"scores",props:{activePlayers:{type:Array,required:!0},idlePlayers:{type:Array,required:!0}},computed:{actives(){return this.activePlayers.sort(((e,t)=>t.points-e.points)),this.activePlayers},idles(){return this.idlePlayers.sort(((e,t)=>t.points-e.points)),this.idlePlayers}}});const vt={class:"scores"},wt=n("div",null,"Scores",-1),bt=n("td",null,"⚡",-1),Ct=n("td",null,"💤",-1);ft.render=function(e,l,o,a,i,u){return s(),t("div",vt,[wt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[bt,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[Ct,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var xt=e({name:"puzzle-status",props:{finished:{type:Boolean,required:!0},duration:{type:Number,required:!0},piecesDone:{type:Number,required:!0},piecesTotal:{type:Number,required:!0}},computed:{icon(){return this.finished?"🏁":"⏳"},durationStr(){return B(this.duration)}}});const kt={class:"timer"};xt.render=function(e,l,o,a,i,d){return s(),t("div",kt,[n("div",null," 🧩 "+r(e.piecesDone)+"/"+r(e.piecesTotal),1),n("div",null,r(e.icon)+" "+r(e.durationStr),1),b(e.$slots,"default")])};var Pt=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const At=m();y("data-v-4d56fc17");const St=n("td",null,[n("label",null,"Background: ")],-1),zt=n("td",null,[n("label",null,"Color: ")],-1),Tt=n("td",null,[n("label",null,"Name: ")],-1),It=n("td",null,[n("label",null,"Sounds: ")],-1),Mt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Et={class:"sound-volume"},Dt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Nt=At(((e,l,o,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:l[10]||(l[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:l[9]||(l[9]=u((()=>{}),["stop"]))},[n("tr",null,[St,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[1]||(l[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[zt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[2]||(l[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[Tt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":l[3]||(l[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[It,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[4]||(l[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Mt,n("td",Et,[n("span",{onClick:l[5]||(l[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:l[6]||(l[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:l[7]||(l[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[8]||(l[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));Pt.render=Nt,Pt.__scopeId="data-v-4d56fc17";var _t=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const Vt={class:"preview"};_t.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay",onClick:l[1]||(l[1]=t=>e.$emit("bgclick"))},[n("div",Vt,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Ot=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Me.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Me.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case De.FLAT:return["Flat","all pieces flat on all sides"];case De.ANY:return["Any","flat pieces can occur anywhere"];case De.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case _e.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case _e.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Bt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ut=n("td",null,"Image Title: ",-1),Rt=n("td",null,"Snap Mode: ",-1),$t=n("td",null,"Shape Mode: ",-1),Gt=n("td",null,"Score Mode: ",-1);Ot.render=function(e,l,o,a,i,d){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Bt,n("tr",null,[Ut,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[Rt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[$t,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Gt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Lt=1,Ft=4,jt=2,Wt=3,Kt=2,Ht=4,Yt=3,qt=9,Qt=1,Zt=2,Xt=3,Jt=4,en=5,tn=6,nn=7,ln=8,on=10,an=11,sn=12,rn=13,dn=14,cn=15,un=16,pn=1,gn=2,hn=3;const mn=Z("Communication.js");let yn,fn=[],vn=e=>{fn.push(e)},wn=[],bn=e=>{wn.push(e)};let Cn=0;const xn=e=>{Cn!==e&&(Cn=e,bn(e))};function kn(e){if(2===Cn)try{yn.send(JSON.stringify(e))}catch(t){mn.info("unable to send message.. maybe because ws is invalid?")}}let Pn,An;var Sn={connect:function(e,t,n){return Pn=0,An={},xn(3),new Promise((l=>{yn=new WebSocket(e,n+"|"+t),yn.onopen=()=>{xn(2),kn([Wt])},yn.onmessage=e=>{const t=JSON.parse(e.data),o=t[0];if(o===Ft){const e=t[1];l(e)}else{if(o!==Lt)throw`[ 2021-05-09 invalid connect msgType ${o} ]`;{const e=t[1],l=t[2];if(e===n&&An[l])return void delete An[l];vn(t)}}},yn.onerror=()=>{throw xn(1),"[ 2021-05-15 onerror ]"},yn.onclose=e=>{4e3===e.code||1001===e.code?xn(4):xn(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},l=await fetch(`/api/replay-data${X.asQueryArgs(n)}`);return await l.json()},disconnect:function(){yn&&yn.close(4e3),Pn=0,An={}},sendClientEvent:function(e){Pn++,An[Pn]=e,kn([jt,Pn,An[Pn]])},onServerChange:function(e){vn=e;for(const t of fn)vn(t);fn=[]},onConnectionStateChange:function(e){bn=e;for(const t of wn)bn(t);wn=[]},CODE_CUSTOM_DISCONNECT:4e3,CONN_STATE_NOT_CONNECTED:0,CONN_STATE_DISCONNECTED:1,CONN_STATE_CLOSED:4,CONN_STATE_CONNECTED:2,CONN_STATE_CONNECTING:3},zn=e({name:"connection-overlay",emits:{reconnect:null},props:{connectionState:Number},computed:{lostConnection(){return this.connectionState===Sn.CONN_STATE_DISCONNECTED},connecting(){return this.connectionState===Sn.CONN_STATE_CONNECTING},show(){return!(!this.lostConnection&&!this.connecting)}}});const Tn={key:0,class:"overlay connection-lost"},In={key:0,class:"overlay-content"},Mn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),En={key:1,class:"overlay-content"},Dn=n("div",null,"Connecting...",-1);zn.render=function(e,l,a,i,r,d){return e.show?(s(),t("div",Tn,[e.lostConnection?(s(),t("div",In,[Mn,n("span",{class:"btn",onClick:l[1]||(l[1]=t=>e.$emit("reconnect"))},"Reconnect")])):o("",!0),e.connecting?(s(),t("div",En,[Dn])):o("",!0)])):o("",!0)};var Nn=e({name:"help-overlay",emits:{bgclick:null}});const _n=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Vn=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),On=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),Bn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Un=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Rn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),$n=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),Gn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Ln=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Fn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),jn=n("tr",null,[n("td",null,"🧩❓ Toggle loose pieces:"),n("td",null,[n("div",null,[n("kbd",null,"G")])])],-1),Wn=n("tr",null,[n("td",null,"👤 Toggle player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Kn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),Hn=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),Yn=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),qn=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);Nn.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[_n,Vn,On,Bn,Un,Rn,$n,Gn,Ln,Fn,jn,Wn,Kn,Hn,Yn,qn])])};var Qn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),Zn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),Xn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),Jn=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),el=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function tl(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var nl={createCanvas:tl,loadImageToBitmap:async function(e){return new Promise((t=>{const n=new Image;n.onload=()=>{createImageBitmap(n).then(t)},n.src=e}))},resizeBitmap:async function(e,t,n){const l=tl(t,n);return l.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(l)},colorizedCanvas:function(e,t,n){const l=tl(e.width,e.height),o=l.getContext("2d");return o.save(),o.drawImage(t,0,0),o.fillStyle=n,o.globalCompositeOperation="source-in",o.fillRect(0,0,t.width,t.height),o.restore(),o.save(),o.globalCompositeOperation="destination-over",o.drawImage(e,0,0),o.restore(),l}};const ll=Z("Debug.js");let ol=0,al=0;var sl=e=>{ol=performance.now(),al=e},il=e=>{const t=performance.now(),n=t-ol;n>al&&ll.log(e+": "+n),ol=t};function rl(e,t){const n=e.x-t.x,l=e.y-t.y;return Math.sqrt(n*n+l*l)}function dl(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var cl={pointSub:function(e,t){return{x:e.x-t.x,y:e.y-t.y}},pointAdd:function(e,t){return{x:e.x+t.x,y:e.y+t.y}},pointDistance:rl,pointInBounds:function(e,t){return e.x>=t.x&&e.x<=t.x+t.w&&e.y>=t.y&&e.y<=t.y+t.h},rectCenter:dl,rectMoved:function(e,t,n){return{x:e.x+t,y:e.y+n,w:e.w,h:e.h}},rectCenterDistance:function(e,t){return rl(dl(e),dl(t))},rectsOverlap:function(e,t){return!(t.x>e.x+e.w||e.x>t.x+t.w||t.y>e.y+e.h||e.y>t.y+t.h)}};const ul=Z("PuzzleGraphics.js");function pl(e,t){const n=X.coordByPieceIdx(e,t);return{x:n.x*e.tileSize,y:n.y*e.tileSize,w:e.tileSize,h:e.tileSize}}var gl={loadPuzzleBitmaps:async function(e){const t=await nl.loadImageToBitmap(e.info.imageUrl),n=await nl.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){ul.log("start createPuzzleTileBitmaps");const l=n.tileSize,o=n.tileMarginWidth,a=n.tileDrawSize,s=l/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:o,y:o},r=cl.pointAdd(a,{x:l,y:0}),c=cl.pointAdd(r,{x:0,y:l}),u=cl.pointSub(c,{x:l,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let l=0;lX.decodePiece(hl[e].puzzle.tiles[t]),Il=(e,t)=>Tl(e,t).group,Ml=(e,t)=>{const n=hl[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},El=(e,t)=>{const n=hl[e].puzzle.info,l={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},o=function(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t),o=l.x*n.tileSize,a=l.y*n.tileSize;return{x:o,y:a}}(e,t);return cl.pointAdd(l,o)},Dl=(e,t)=>Tl(e,t).pos,Nl=e=>{const t=Ql(e),n=Zl(e),l=Math.round(t/4),o=Math.round(n/4);return{x:0-l,y:0-o,w:t+2*l,h:n+2*o}},_l=(e,t)=>{const n=Ul(e),l=Tl(e,t);return{x:l.pos.x,y:l.pos.y,w:n,h:n}},Vl=(e,t)=>Tl(e,t).z,Ol=(e,t)=>{for(const n of hl[e].puzzle.tiles){const e=X.decodePiece(n);if(e.owner===t)return e.idx}return-1},Bl=e=>hl[e].puzzle.info.tileDrawSize,Ul=e=>hl[e].puzzle.info.tileSize,Rl=e=>hl[e].puzzle.data.maxGroup,$l=e=>hl[e].puzzle.data.maxZ;function Gl(e,t){const n=hl[e].puzzle.info,l=X.coordByPieceIdx(n,t);return[l.y>0?t-n.tilesX:-1,l.x0?t-1:-1]}const Ll=(e,t,n)=>{for(const l of t)zl(e,l,{z:n})},Fl=(e,t,n)=>{const l=Dl(e,t);zl(e,t,{pos:cl.pointAdd(l,n)})},jl=(e,t,n)=>{const l=Bl(e),o=Nl(e),a=n;for(const s of t){const t=Tl(e,s);t.pos.x+n.xo.x+o.w&&(a.x=Math.min(o.x+o.w-t.pos.x+l,a.x)),t.pos.y+n.yo.y+o.h&&(a.y=Math.min(o.y+o.h-t.pos.y+l,a.y))}for(const s of t)Fl(e,s,a)},Wl=(e,t)=>Tl(e,t).owner,Kl=(e,t)=>{for(const n of t)zl(e,n,{owner:-1,z:1})},Hl=(e,t,n)=>{for(const l of t)zl(e,l,{owner:n})};function Yl(e,t){const n=hl[e].puzzle.tiles,l=X.decodePiece(n[t]),o=[];if(l.group)for(const a of n){const e=X.decodePiece(a);e.group===l.group&&o.push(e.idx)}else o.push(l.idx);return o}const ql=(e,t)=>{const n=yl(e,t);return n?n.points:0},Ql=e=>hl[e].puzzle.info.table.width,Zl=e=>hl[e].puzzle.info.table.height;var Xl={setGame:function(e,t){hl[e]=t},exists:function(e){return!!hl[e]||!1},playerExists:vl,getActivePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*_;return wl(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){vl(e,t)?Al(e,t,{ts:n}):fl(e,t,function(e,t){return{id:e,x:0,y:0,d:0,name:null,color:null,bgcolor:null,points:0,ts:t}}(t,n))},getFinishedPiecesCount:Pl,getPieceCount:bl,getImageUrl:function(e){var t;const n=(null==(t=hl[e].puzzle.info.image)?void 0:t.url)||hl[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return hl[e]||null},getAllGames:function(){return Object.values(hl).sort(((e,t)=>kl(e.id)===kl(t.id)?t.puzzle.data.started-e.puzzle.data.started:kl(e.id)?1:-1))},getPlayerBgColor:(e,t)=>{const n=yl(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=yl(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=yl(e,t);return n?n.name:null},getPlayerIndexById:ml,getPlayerIdByIndex:function(e,t){return hl[e].players.length>t?X.decodePlayer(hl[e].players[t]).id:null},changePlayer:Al,setPlayer:fl,setPiece:function(e,t,n){hl[e].puzzle.tiles[t]=X.encodePiece(n)},setPuzzleData:function(e,t){hl[e].puzzle.data=t},getTableWidth:Ql,getTableHeight:Zl,getPuzzle:e=>hl[e].puzzle,getRng:e=>hl[e].rng.obj,getPuzzleWidth:e=>hl[e].puzzle.info.width,getPuzzleHeight:e=>hl[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return hl[e].puzzle.tiles.map(X.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Ol(e,t);return n<0?null:hl[e].puzzle.tiles[n]},getPieceDrawOffset:e=>hl[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Bl,getFinalPiecePos:El,getStartTs:e=>hl[e].puzzle.data.started,getFinishTs:e=>hl[e].puzzle.data.finished,handleInput:function(e,t,n,l,o){const a=hl[e].puzzle,s=function(e,t){return t in hl[e].evtInfos?hl[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([pn,a.data])},d=t=>{i.push([gn,X.encodePiece(Tl(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=yl(e,t);n&&i.push([hn,X.encodePlayer(n)])},p=n[0];if(p===tn){const o=n[1];Al(e,t,{bgcolor:o,ts:l}),u()}else if(p===nn){const o=n[1];Al(e,t,{color:o,ts:l}),u()}else if(p===ln){const o=`${n[1]}`.substr(0,16);Al(e,t,{name:o,ts:l}),u()}else if(p===qt){const o=n[1],a=n[2],s=yl(e,t);if(s){const n=s.x-o,i=s.y-a;Al(e,t,{ts:l,x:n,y:i}),u()}}else if(p===Qt){const o={x:n[1],y:n[2]};Al(e,t,{d:1,ts:l}),u(),s._last_mouse_down=o;const a=((e,t)=>{const n=hl[e].puzzle.info,l=hl[e].puzzle.tiles;let o=-1,a=-1;for(let s=0;so)&&(o=e.z,a=s)}return a})(e,o);if(a>=0){const n=$l(e)+1;Sl(e,{maxZ:n}),r();const l=Yl(e,a);Ll(e,l,$l(e)),Hl(e,l,t),c(l)}s._last_mouse=o}else if(p===Xt){const o=n[1],a=n[2],i={x:o,y:a};if(null===s._last_mouse_down)Al(e,t,{x:o,y:a,ts:l}),u();else{const n=Ol(e,t);if(n>=0){Al(e,t,{x:o,y:a,ts:l}),u();const r=Yl(e,n);let d=cl.pointInBounds(i,Nl(e))&&cl.pointInBounds(s._last_mouse_down,Nl(e));for(const t of r){const n=_l(e,t);if(cl.pointInBounds(i,n)){d=!0;break}}if(d){const t=o-s._last_mouse_down.x,n=a-s._last_mouse_down.y;jl(e,r,{x:t,y:n}),c(r)}}else Al(e,t,{ts:l}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===Zt){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Ol(e,t);if(g>=0){const n=Yl(e,g);Hl(e,n,0),c(n);const s=Dl(e,g),i=El(e,g);let h=!1;if(xl(e)===_e.REAL){for(const t of n)if(Ml(e,t)){h=!0;break}}else h=!0;if(h&&cl.pointDistance(i,s){const o=hl[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const l=Il(e,t),o=Il(e,n);return!(!l||l!==o)})(e,t,n))return!1;const a=Dl(e,t),s=cl.pointAdd(Dl(e,n),{x:l[0]*o.tileSize,y:l[1]*o.tileSize});if(cl.pointDistance(a,s){const l=hl[e].puzzle.tiles,o=Il(e,t),a=Il(e,n);let s;const i=[];o&&i.push(o),a&&i.push(a),o?s=o:a?s=a:(Sl(e,{maxGroup:Rl(e)+1}),r(),s=Rl(e));if(zl(e,t,{group:s}),d(t),zl(e,n,{group:s}),d(n),i.length>0)for(const r of l){const t=X.decodePiece(r);i.includes(t.group)&&(zl(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),o=Yl(e,t),((e,t)=>-1===Wl(e,t))(e,n))Kl(e,o);else{const t=((e,t)=>{let n=0;for(const l of t){const t=Vl(e,l);t>n&&(n=t)}return n})(e,o);Ll(e,o,t)}return c(o),!0}return!1};let a=!1;for(const t of Yl(e,g)){const l=Gl(e,t);if(n(e,t,l[0],[0,1])||n(e,t,l[1],[-1,0])||n(e,t,l[2],[0,-1])||n(e,t,l[3],[1,0])){a=!0;break}}if(a&&Cl(e)===Me.ANY){const n=ql(e,t)+1;Al(e,t,{d:p,ts:l,points:n}),u()}else Al(e,t,{d:p,ts:l}),u();a&&xl(e)===_e.REAL&&Pl(e)===bl(e)&&(Sl(e,{finished:l}),r()),a&&o&&o(t)}}else Al(e,t,{d:p,ts:l}),u();s._last_mouse=i}else if(p===Jt){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else if(p===en){const o=n[1],a=n[2];Al(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else Al(e,t,{ts:l}),u();return function(e,t,n){hl[e].evtInfos[t]=n}(e,t,s),i}};let Jl=-10,eo=20,to=2,no=15;class lo{constructor(e){this.radius=10,this.previousRadius=10,this.explodingDuration=100,this.hasExploded=!1,this.alive=!0,this.color=function(e){return"rgba("+e.random(0,255)+","+e.random(0,255)+","+e.random(0,255)+", 0.8)"}(e),this.px=window.innerWidth/4+Math.random()*window.innerWidth/2,this.py=window.innerHeight,this.vx=Jl+Math.random()*eo,this.vy=-1*(to+Math.random()*no),this.duration=0}update(e){if(this.hasExploded){const e=200-this.radius;this.previousRadius=this.radius,this.radius+=e/10,this.explodingDuration--,0==this.explodingDuration&&(this.alive=!1)}else this.vx+=0,this.vy+=1,this.vy>=0&&e&&this.explode(e),this.px+=this.vx,this.py+=this.vy}draw(e){e.beginPath(),e.arc(this.px,this.py,this.previousRadius,0,2*Math.PI,!1),this.hasExploded||(e.fillStyle=this.color,e.lineWidth=1,e.fill())}explode(e){this.hasExploded=!0;const t=3+Math.floor(3*Math.random());for(let n=0;n{this.resize()}))}setSpeedParams(){let e=0,t=0;for(;e=0;)t+=1,e+=t;to=t/2,no=t-to;const n=1/4*this.canvas.width/(t/2);Jl=-n,eo=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new lo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new lo(this.rng));const e=[];for(;this.explodedBombs.length>0;){const t=this.explodedBombs.shift();if(!t)break;t.update(),t.alive&&e.push(t)}this.explodedBombs=e;const t=[];for(;this.readyBombs.length>0;){const e=this.readyBombs.shift();if(!e)break;e.update(this.particles),e.hasExploded?this.explodedBombs.push(e):t.push(e)}this.readyBombs=t;const n=[];for(;this.particles.length>0;){const e=this.particles.shift();if(!e)break;e.update(),e.alive&&n.push(e)}this.particles=n}render(){this.ctx.beginPath(),this.ctx.fillStyle="rgba(0, 0, 0, 0.1)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height);for(let e=0;e{localStorage.setItem(e,t)},ho=e=>localStorage.getItem(e);var mo=(e,t)=>{go(e,`${t}`)},yo=(e,t)=>{const n=ho(e);if(null===n)return t;const l=parseInt(n,10);return isNaN(l)?t:l},fo=(e,t)=>{go(e,t?"1":"0")},vo=(e,t)=>{const n=ho(e);return null===n?t:"1"===n},wo=(e,t)=>{go(e,t)},bo=(e,t)=>{const n=ho(e);return null===n?t:n};const Co={"./grab.png":Zn,"./grab_mask.png":Xn,"./hand.png":Jn,"./hand_mask.png":el},xo={"./click.mp3":Qn};let ko=!0,Po=!0;let Ao=!0;async function So(e,t,n,l,o,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=xo["./click.mp3"].default,i=new Audio(s),r=await nl.loadImageToBitmap(Co["./grab.png"].default),d=await nl.loadImageToBitmap(Co["./hand.png"].default),c=await nl.loadImageToBitmap(Co["./grab_mask.png"].default),u=await nl.loadImageToBitmap(Co["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const l=e.d?c:u;y[t]=await createImageBitmap(nl.colorizedCanvas(n,l,e.color))}else y[t]=n}return y[t]},v=function(e,t){return t.width=window.innerWidth,t.height=window.innerHeight,e.appendChild(t),window.addEventListener("resize",(()=>{t.width=window.innerWidth,t.height=window.innerHeight,Ao=!0})),t}(o,nl.createCanvas()),w={final:!1,log:[],logPointer:0,speeds:[.5,1,2,5,10,20,50,100,250,500],speedIdx:1,paused:!1,lastRealTs:0,lastGameTs:0,gameStartTs:0,skipNonActionPhases:!0,dataOffset:0};Sn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Sn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===l){const l=await Sn.connect(n,e,t),o=X.decodeGame(l);Xl.setGame(o.id,o),C=()=>V()}else{if("replay"!==l)throw"[ 2020-12-22 MODE invalid, must be play|replay ]";{const t=await b(e);if(!t.game)throw"[ 2021-05-29 no game received ]";const n=X.decodeGame(t.game);Xl.setGame(n.id,n),w.lastRealTs=V(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Ao=!0};await x();const k=Xl.getPieceDrawOffset(e),P=Xl.getPieceDrawSize(e),A=Xl.getPuzzleWidth(e),S=Xl.getPuzzleHeight(e),z=Xl.getTableWidth(e),T=Xl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},M={w:A,h:S},E={w:P,h:P},D=await gl.loadPuzzleBitmaps(Xl.getPuzzle(e)),_=new ao(v,Xl.getRng(e));_.init();const O=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const B=function(){let e=0,t=0,n=1;const l=(l,o)=>{e+=l/n,t+=o/n},o=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=(e,t)=>{if(n==e)return!1;const o=1-n/e;return l(-t.x*o,-t.y*o),n=e,!0},s=l=>({x:l.x/n-e,y:l.y/n-t}),i=l=>({x:(l.x+e)*n,y:(l.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:l,canZoom:e=>n!=o(e),zoom:(e,t)=>a(o(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),U=()=>{B.reset(),B.move(-(z-v.width)/2,-(T-v.height)/2);const e=B.worldDimToViewport(M),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const l=n.viewportToWorld({x:e,y:t});return[l.x,l.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([Qt,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([Zt,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([Xt,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?Jt:en;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([on]),"replay"===l&&("KeyI"===e.code&&v([rn]),"KeyO"===e.code&&v([dn]),"KeyP"===e.code&&v([sn])),"KeyF"===e.code&&(ko=!ko,Ao=!0),"KeyG"===e.code&&(Po=!Po,Ao=!0),"KeyM"===e.code&&v([an]),"KeyN"===e.code&&v([cn]),"KeyC"===e.code&&v([un]))}));const v=e=>{o.push(e)};return{addEvent:v,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const l=(p?24:12)*Math.sqrt(n.getCurrentZoom()),o=n.viewportDimToWorld({w:e*l,h:t*l});v([qt,o.w,o.h]),f&&(f[0]-=o.w,f[1]-=o.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([Jt,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([en,...e])}},setHotkeys:e=>{a=e}}}(v,window,B,l),$=Xl.getImageUrl(e),G=()=>{const t=Xl.getStartTs(e),n=Xl.getFinishTs(e),l=C();a.setFinished(!!n),a.setDuration((n||l)-t)};G(),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),a.setPiecesTotal(Xl.getPieceCount(e));const L=C();a.setActivePlayers(Xl.getActivePlayers(e,L)),a.setIdlePlayers(Xl.getIdlePlayers(e,L));const F=!!Xl.getFinishTs(e);let j=F;const W=()=>j&&!F,K=()=>yo(so,100),H=()=>vo(io,!1),Y=()=>vo(po,!0),q=()=>{const e=K();i.volume=e/100,i.play()},Q=()=>"replay"===l?bo(ro,"#222222"):Xl.getPlayerBgColor(e,t)||bo(ro,"#222222"),Z=()=>"replay"===l?bo(co,"#ffffff"):Xl.getPlayerColor(e,t)||bo(co,"#ffffff");let J="",ee="",te=!1;const ne=e=>{te=e;const[t,n]=e?[J,"grab"]:[ee,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},le=e=>{J=nl.colorizedCanvas(r,c,e).toDataURL(),ee=nl.colorizedCanvas(d,u,e).toDataURL(),ne(te)};le(Z());const oe=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},ae=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,oe())},ie=()=>{w.paused=!w.paused,oe()},re=[];let de;let ce;if("play"===l?re.push(setInterval((()=>{G()}),1e3)):"replay"===l&&oe(),"play"===l)Sn.onServerChange((n=>{n[0],n[1],n[2];const l=n[3];for(const[o,a]of l)switch(o){case hn:{const n=X.decodePlayer(a);n.id!==t&&(Xl.setPlayer(e,n.id,n),Ao=!0)}break;case gn:{const t=X.decodePiece(a);Xl.setPiece(e,t.idx,t),Ao=!0}break;case pn:Xl.setPuzzleData(e,a),Ao=!0}j=!!Xl.getFinishTs(e)}));else if("replay"===l){const t=(t,n)=>{const l=t;if(l[0]===Kt){const t=l[1];return Xl.addPlayer(e,t,n),!0}if(l[0]===Ht){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return Xl.addPlayer(e,t,n),!0}if(l[0]===Yt){const t=Xl.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const o=l[2];return Xl.handleInput(e,t,o,n),!0}return!1};let n=w.lastGameTs;const l=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=V();if(w.paused)return w.lastRealTs=o,void(de=setTimeout(l,50));const a=(o-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const l=w.log[w.logPointer],o=n+l[l.length-1],a=w.log[e],i=a[a.length-1],r=o+i;if(r>s){s+500*N{let t=!1;const n=e.fps||60,l=e.slow||1,o=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=l*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,o(i);a(c/l),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{R.createKeyEvents();for(const n of R.consumeAll())if("play"===l){const l=n[0];if(l===qt){const e=n[1],t=n[2],l=B.worldDimToViewport({w:e,h:t});Ao=!0,B.move(l.w,l.h)}else if(l===Xt){if(ue&&!Xl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(l===nn)le(n[1]);else if(l===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(l===Zt)ue=null,ne(!1);else if(l===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(l===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else l===on?a.togglePreview():l===an?a.toggleSoundsEnabled():l===cn?a.togglePlayerNames():l===un&&U();const o=C();Xl.handleInput(e,t,n,o,(e=>{H()&&q()})).length>0&&(Ao=!0),Sn.sendClientEvent(n)}else if("replay"===l){const e=n[0];if(e===sn)ie();else if(e===dn)se();else if(e===rn)ae();else if(e===qt){const e=n[1],t=n[2];Ao=!0,B.move(e,t)}else if(e===Xt){if(ue){const e={x:n[1],y:n[2]},t=B.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);Ao=!0,B.move(l,o),ue=t}}else if(e===nn)le(n[1]);else if(e===Qt){const e={x:n[1],y:n[2]};ue=B.worldToViewport(e),ne(!0)}else if(e===Zt)ue=null,ne(!1);else if(e===Jt){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("in",B.worldToViewport(e))}else if(e===en){const e={x:n[1],y:n[2]};Ao=!0,B.zoom("out",B.worldToViewport(e))}else e===on?a.togglePreview():e===an?a.toggleSoundsEnabled():e===cn?a.togglePlayerNames():e===un&&U()}j=!!Xl.getFinishTs(e),W()&&(_.update(),Ao=!0)},render:async()=>{if(!Ao)return;const n=C();let o,s,i;window.DEBUG&&sl(0),O.fillStyle=Q(),O.fillRect(0,0,v.width,v.height),window.DEBUG&&il("clear done"),o=B.worldToViewportRaw(I),s=B.worldDimToViewportRaw(M),O.fillStyle="rgba(255, 255, 255, .3)",O.fillRect(o.x,o.y,s.w,s.h),window.DEBUG&&il("board done");const r=Xl.getPiecesSortedByZIndex(e);window.DEBUG&&il("get tiles done"),s=B.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?ko:Po)&&(i=D[e.idx],o=B.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),O.drawImage(i,0,0,i.width,i.height,o.x,o.y,s.w,s.h));window.DEBUG&&il("tiles done");const d=[];for(const a of Xl.getActivePlayers(e,n))c=a,("replay"===l||c.id!==t)&&(i=await f(a),o=B.worldToViewport(a),O.drawImage(i,o.x-g,o.y-m),Y()&&d.push([`${a.name} (${a.points})`,o.x,o.y+h]));var c;O.fillStyle="white",O.textAlign="center";for(const[e,t,l]of d)O.fillText(e,t,l);window.DEBUG&&il("players done"),a.setActivePlayers(Xl.getActivePlayers(e,n)),a.setIdlePlayers(Xl.getIdlePlayers(e,n)),a.setPiecesDone(Xl.getFinishedPiecesCount(e)),window.DEBUG&&il("HUD done"),W()&&_.render(),Ao=!1}}),{setHotkeys:e=>{R.setHotkeys(e)},onBgChange:e=>{wo(ro,e),R.addEvent([tn,e])},onColorChange:e=>{wo(co,e),R.addEvent([nn,e])},onNameChange:e=>{wo(uo,e),R.addEvent([ln,e])},onSoundsEnabledChange:e=>{fo(io,e)},onSoundsVolumeChange:e=>{mo(so,e),q()},onShowPlayerNamesChange:e=>{fo(po,e)},replayOnSpeedUp:ae,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:$,player:{background:Q(),color:Z(),name:"replay"===l?bo(uo,"anon"):Xl.getPlayerName(e,t)||bo(uo,"anon"),soundsEnabled:H(),soundsVolume:K(),showPlayerNames:Y()},game:Xl.get(e),disconnect:Sn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var zo=e({name:"game",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,ConnectionOverlay:zn,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const To={id:"game"},Io={key:1,class:"overlay"},Mo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Eo={class:"menu"},Do={class:"tabs"},No=i("🧩 Puzzles");zo.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",To,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Io,[Mo])):o("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Eo,[n("div",Do,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[No])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var _o=e({name:"replay",components:{PuzzleStatus:xt,Scores:ft,SettingsOverlay:Pt,PreviewOverlay:_t,InfoOverlay:Ot,HelpOverlay:Nn},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await So(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"replay",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Vo={id:"replay"},Oo={key:1,class:"overlay"},Bo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Uo={class:"menu"},Ro={class:"tabs"},$o=i("🧩 Puzzles");_o.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Vo,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Oo,[Bo])):o("",!0),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:l((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Uo,[n("div",Ro,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[$o])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=await fetch("/api/conf"),t=await e.json();const n=k({history:P(),routes:[{name:"index",path:"/",component:j},{name:"new-game",path:"/new-game",component:it},{name:"game",path:"/g/:id",component:zo},{name:"replay",path:"/replay/:id",component:_o}]});n.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const l=A(S);l.config.globalProperties.$config=t,l.config.globalProperties.$clientId=function(){let e=localStorage.getItem("ID");return e||(e=X.uniqId(),localStorage.setItem("ID",e)),e}(),l.use(n),l.mount("#app")})(); diff --git a/build/public/index.html b/build/public/index.html index 3df4956..3fc9389 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 82e7590..3f60a65 100644 --- a/build/server/main.js +++ b/build/server/main.js @@ -340,6 +340,8 @@ const INPUT_EV_REPLAY_SPEED_UP = 13; const INPUT_EV_REPLAY_SPEED_DOWN = 14; const INPUT_EV_TOGGLE_PLAYER_NAMES = 15; const INPUT_EV_CENTER_FIT_PUZZLE = 16; +const INPUT_EV_TOGGLE_FIXED_PIECES = 17; +const INPUT_EV_TOGGLE_LOOSE_PIECES = 18; const CHANGE_DATA = 1; const CHANGE_TILE = 2; const CHANGE_PLAYER = 3; @@ -368,6 +370,8 @@ var Protocol = { INPUT_EV_REPLAY_SPEED_DOWN, INPUT_EV_TOGGLE_PLAYER_NAMES, INPUT_EV_CENTER_FIT_PUZZLE, + INPUT_EV_TOGGLE_FIXED_PIECES, + INPUT_EV_TOGGLE_LOOSE_PIECES, CHANGE_DATA, CHANGE_TILE, CHANGE_PLAYER, diff --git a/src/common/Protocol.ts b/src/common/Protocol.ts index 0370c1d..1f868c1 100644 --- a/src/common/Protocol.ts +++ b/src/common/Protocol.ts @@ -67,6 +67,9 @@ const INPUT_EV_REPLAY_SPEED_DOWN = 14 const INPUT_EV_TOGGLE_PLAYER_NAMES = 15 const INPUT_EV_CENTER_FIT_PUZZLE = 16 +const INPUT_EV_TOGGLE_FIXED_PIECES = 17 +const INPUT_EV_TOGGLE_LOOSE_PIECES = 18 + const CHANGE_DATA = 1 const CHANGE_TILE = 2 const CHANGE_PLAYER = 3 @@ -104,6 +107,9 @@ export default { INPUT_EV_TOGGLE_PLAYER_NAMES, INPUT_EV_CENTER_FIT_PUZZLE, + INPUT_EV_TOGGLE_FIXED_PIECES, + INPUT_EV_TOGGLE_LOOSE_PIECES, + CHANGE_DATA, CHANGE_TILE, CHANGE_PLAYER, diff --git a/src/frontend/EventAdapter.ts b/src/frontend/EventAdapter.ts new file mode 100644 index 0000000..d0166fe --- /dev/null +++ b/src/frontend/EventAdapter.ts @@ -0,0 +1,177 @@ +import Protocol from "../common/Protocol" +import { GameEvent } from "../common/Types" +import { MODE_REPLAY } from "./game" + +function EventAdapter ( + canvas: HTMLCanvasElement, + window: any, + viewport: any, + MODE: string +) { + let events: Array = [] + + let KEYS_ON = true + + let LEFT = false + let RIGHT = false + let UP = false + let DOWN = false + let ZOOM_IN = false + let ZOOM_OUT = false + let SHIFT = false + + const toWorldPoint = (x: number, y: number): [number, number] => { + const pos = viewport.viewportToWorld({x, y}) + return [pos.x, pos.y] + } + + const mousePos = (ev: MouseEvent) => toWorldPoint(ev.offsetX, ev.offsetY) + const canvasCenter = () => toWorldPoint(canvas.width / 2, canvas.height / 2) + + const key = (state: boolean, ev: KeyboardEvent) => { + if (!KEYS_ON) { + return + } + + if (ev.code === 'ShiftLeft' || ev.code === 'ShiftRight') { + SHIFT = state + } else if (ev.code === 'ArrowUp' || ev.code === 'KeyW') { + UP = state + } else if (ev.code === 'ArrowDown' || ev.code === 'KeyS') { + DOWN = state + } else if (ev.code === 'ArrowLeft' || ev.code === 'KeyA') { + LEFT = state + } else if (ev.code === 'ArrowRight' || ev.code === 'KeyD') { + RIGHT = state + } else if (ev.code === 'KeyQ') { + ZOOM_OUT = state + } else if (ev.code === 'KeyE') { + ZOOM_IN = state + } + } + + let lastMouse: [number, number]|null = null + canvas.addEventListener('mousedown', (ev) => { + lastMouse = mousePos(ev) + if (ev.button === 0) { + addEvent([Protocol.INPUT_EV_MOUSE_DOWN, ...lastMouse]) + } + }) + + canvas.addEventListener('mouseup', (ev) => { + lastMouse = mousePos(ev) + if (ev.button === 0) { + addEvent([Protocol.INPUT_EV_MOUSE_UP, ...lastMouse]) + } + }) + + canvas.addEventListener('mousemove', (ev) => { + lastMouse = mousePos(ev) + addEvent([Protocol.INPUT_EV_MOUSE_MOVE, ...lastMouse]) + }) + + canvas.addEventListener('wheel', (ev) => { + lastMouse = mousePos(ev) + if (viewport.canZoom(ev.deltaY < 0 ? 'in' : 'out')) { + const evt = ev.deltaY < 0 + ? Protocol.INPUT_EV_ZOOM_IN + : Protocol.INPUT_EV_ZOOM_OUT + addEvent([evt, ...lastMouse]) + } + }) + + window.addEventListener('keydown', (ev: KeyboardEvent) => key(true, ev)) + window.addEventListener('keyup', (ev: KeyboardEvent) => key(false, ev)) + + window.addEventListener('keypress', (ev: KeyboardEvent) => { + if (!KEYS_ON) { + return + } + if (ev.code === 'Space') { + addEvent([Protocol.INPUT_EV_TOGGLE_PREVIEW]) + } + + if (MODE === MODE_REPLAY) { + if (ev.code === 'KeyI') { + addEvent([Protocol.INPUT_EV_REPLAY_SPEED_UP]) + } + + if (ev.code === 'KeyO') { + addEvent([Protocol.INPUT_EV_REPLAY_SPEED_DOWN]) + } + + if (ev.code === 'KeyP') { + addEvent([Protocol.INPUT_EV_REPLAY_TOGGLE_PAUSE]) + } + } + if (ev.code === 'KeyF') { + addEvent([Protocol.INPUT_EV_TOGGLE_FIXED_PIECES]) + } + if (ev.code === 'KeyG') { + addEvent([Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES]) + } + if (ev.code === 'KeyM') { + addEvent([Protocol.INPUT_EV_TOGGLE_SOUNDS]) + } + if (ev.code === 'KeyN') { + addEvent([Protocol.INPUT_EV_TOGGLE_PLAYER_NAMES]) + } + if (ev.code === 'KeyC') { + addEvent([Protocol.INPUT_EV_CENTER_FIT_PUZZLE]) + } + }) + + const addEvent = (event: GameEvent) => { + events.push(event) + } + + const consumeAll = (): GameEvent[] => { + if (events.length === 0) { + return [] + } + const all = events.slice() + events = [] + return all + } + + const createKeyEvents = (): void => { + const w = (LEFT ? 1 : 0) - (RIGHT ? 1 : 0) + const h = (UP ? 1 : 0) - (DOWN ? 1 : 0) + if (w !== 0 || h !== 0) { + const amount = (SHIFT ? 24 : 12) * Math.sqrt(viewport.getCurrentZoom()) + const pos = viewport.viewportDimToWorld({w: w * amount, h: h * amount}) + addEvent([Protocol.INPUT_EV_MOVE, pos.w, pos.h]) + if (lastMouse) { + lastMouse[0] -= pos.w + lastMouse[1] -= pos.h + } + } + + if (ZOOM_IN && ZOOM_OUT) { + // cancel each other out + } else if (ZOOM_IN) { + if (viewport.canZoom('in')) { + const target = lastMouse || canvasCenter() + addEvent([Protocol.INPUT_EV_ZOOM_IN, ...target]) + } + } else if (ZOOM_OUT) { + if (viewport.canZoom('out')) { + const target = lastMouse || canvasCenter() + addEvent([Protocol.INPUT_EV_ZOOM_OUT, ...target]) + } + } + } + + const setHotkeys = (state: boolean) => { + KEYS_ON = state + } + + return { + addEvent, + consumeAll, + createKeyEvents, + setHotkeys, + } +} + +export default EventAdapter diff --git a/src/frontend/game.ts b/src/frontend/game.ts index ea457d1..9d7cb47 100644 --- a/src/frontend/game.ts +++ b/src/frontend/game.ts @@ -22,9 +22,9 @@ import { EncodedGame, ReplayData, Timestamp, - GameEvent, ServerEvent, } from '../common/Types' +import EventAdapter from './EventAdapter' declare global { interface Window { DEBUG?: boolean @@ -96,180 +96,6 @@ function addCanvasToDom(TARGET_EL: HTMLElement, canvas: HTMLCanvasElement) { return canvas } -function EventAdapter ( - canvas: HTMLCanvasElement, - window: any, - viewport: any, - MODE: string -) { - let events: Array = [] - - let KEYS_ON = true - - let LEFT = false - let RIGHT = false - let UP = false - let DOWN = false - let ZOOM_IN = false - let ZOOM_OUT = false - let SHIFT = false - - const toWorldPoint = (x: number, y: number): [number, number] => { - const pos = viewport.viewportToWorld({x, y}) - return [pos.x, pos.y] - } - - const mousePos = (ev: MouseEvent) => toWorldPoint(ev.offsetX, ev.offsetY) - const canvasCenter = () => toWorldPoint(canvas.width / 2, canvas.height / 2) - - const key = (state: boolean, ev: KeyboardEvent) => { - if (!KEYS_ON) { - return - } - - if (ev.code === 'ShiftLeft' || ev.code === 'ShiftRight') { - SHIFT = state - } else if (ev.code === 'ArrowUp' || ev.code === 'KeyW') { - UP = state - } else if (ev.code === 'ArrowDown' || ev.code === 'KeyS') { - DOWN = state - } else if (ev.code === 'ArrowLeft' || ev.code === 'KeyA') { - LEFT = state - } else if (ev.code === 'ArrowRight' || ev.code === 'KeyD') { - RIGHT = state - } else if (ev.code === 'KeyQ') { - ZOOM_OUT = state - } else if (ev.code === 'KeyE') { - ZOOM_IN = state - } - } - - let lastMouse: [number, number]|null = null - canvas.addEventListener('mousedown', (ev) => { - lastMouse = mousePos(ev) - if (ev.button === 0) { - addEvent([Protocol.INPUT_EV_MOUSE_DOWN, ...lastMouse]) - } - }) - - canvas.addEventListener('mouseup', (ev) => { - lastMouse = mousePos(ev) - if (ev.button === 0) { - addEvent([Protocol.INPUT_EV_MOUSE_UP, ...lastMouse]) - } - }) - - canvas.addEventListener('mousemove', (ev) => { - lastMouse = mousePos(ev) - addEvent([Protocol.INPUT_EV_MOUSE_MOVE, ...lastMouse]) - }) - - canvas.addEventListener('wheel', (ev) => { - lastMouse = mousePos(ev) - if (viewport.canZoom(ev.deltaY < 0 ? 'in' : 'out')) { - const evt = ev.deltaY < 0 - ? Protocol.INPUT_EV_ZOOM_IN - : Protocol.INPUT_EV_ZOOM_OUT - addEvent([evt, ...lastMouse]) - } - }) - - window.addEventListener('keydown', (ev: KeyboardEvent) => key(true, ev)) - window.addEventListener('keyup', (ev: KeyboardEvent) => key(false, ev)) - - window.addEventListener('keypress', (ev: KeyboardEvent) => { - if (!KEYS_ON) { - return - } - if (ev.code === 'Space') { - addEvent([Protocol.INPUT_EV_TOGGLE_PREVIEW]) - } - - if (MODE === MODE_REPLAY) { - if (ev.code === 'KeyI') { - addEvent([Protocol.INPUT_EV_REPLAY_SPEED_UP]) - } - - if (ev.code === 'KeyO') { - addEvent([Protocol.INPUT_EV_REPLAY_SPEED_DOWN]) - } - - if (ev.code === 'KeyP') { - addEvent([Protocol.INPUT_EV_REPLAY_TOGGLE_PAUSE]) - } - } - if (ev.code === 'KeyF') { - PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED - RERENDER = true - } - if (ev.code === 'KeyG') { - PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE - RERENDER = true - } - if (ev.code === 'KeyM') { - addEvent([Protocol.INPUT_EV_TOGGLE_SOUNDS]) - } - if (ev.code === 'KeyN') { - addEvent([Protocol.INPUT_EV_TOGGLE_PLAYER_NAMES]) - } - if (ev.code === 'KeyC') { - addEvent([Protocol.INPUT_EV_CENTER_FIT_PUZZLE]) - } - }) - - const addEvent = (event: GameEvent) => { - events.push(event) - } - - const consumeAll = (): GameEvent[] => { - if (events.length === 0) { - return [] - } - const all = events.slice() - events = [] - return all - } - - const createKeyEvents = (): void => { - const w = (LEFT ? 1 : 0) - (RIGHT ? 1 : 0) - const h = (UP ? 1 : 0) - (DOWN ? 1 : 0) - if (w !== 0 || h !== 0) { - const amount = (SHIFT ? 24 : 12) * Math.sqrt(viewport.getCurrentZoom()) - const pos = viewport.viewportDimToWorld({w: w * amount, h: h * amount}) - addEvent([Protocol.INPUT_EV_MOVE, pos.w, pos.h]) - if (lastMouse) { - lastMouse[0] -= pos.w - lastMouse[1] -= pos.h - } - } - - if (ZOOM_IN && ZOOM_OUT) { - // cancel each other out - } else if (ZOOM_IN) { - if (viewport.canZoom('in')) { - const target = lastMouse || canvasCenter() - addEvent([Protocol.INPUT_EV_ZOOM_IN, ...target]) - } - } else if (ZOOM_OUT) { - if (viewport.canZoom('out')) { - const target = lastMouse || canvasCenter() - addEvent([Protocol.INPUT_EV_ZOOM_OUT, ...target]) - } - } - } - - const setHotkeys = (state: boolean) => { - KEYS_ON = state - } - - return { - addEvent, - consumeAll, - createKeyEvents, - setHotkeys, - } -} - export async function main( gameId: string, clientId: string, @@ -746,6 +572,12 @@ export async function main( HUD.togglePlayerNames() } else if (type === Protocol.INPUT_EV_CENTER_FIT_PUZZLE) { centerPuzzle() + } else if (type === Protocol.INPUT_EV_TOGGLE_FIXED_PIECES) { + PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED + RERENDER = true + } else if (type === Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES) { + PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE + RERENDER = true } // LOCAL + SERVER CHANGES @@ -818,6 +650,12 @@ export async function main( HUD.togglePlayerNames() } else if (type === Protocol.INPUT_EV_CENTER_FIT_PUZZLE) { centerPuzzle() + } else if (type === Protocol.INPUT_EV_TOGGLE_FIXED_PIECES) { + PIECE_VIEW_FIXED = !PIECE_VIEW_FIXED + RERENDER = true + } else if (type === Protocol.INPUT_EV_TOGGLE_LOOSE_PIECES) { + PIECE_VIEW_LOOSE = !PIECE_VIEW_LOOSE + RERENDER = true } } } From e7628895c91c9b3eafa1b2fc3b2f7b7a0a3131f6 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 17:21:41 +0200 Subject: [PATCH 05/17] sort finished games by finish date --- src/common/GameCommon.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/common/GameCommon.ts b/src/common/GameCommon.ts index 7ce4599..8b7fde7 100644 --- a/src/common/GameCommon.ts +++ b/src/common/GameCommon.ts @@ -138,12 +138,16 @@ function setEvtInfo( function getAllGames(): Array { return Object.values(GAMES).sort((a: Game, b: Game) => { + const finished = isFinished(a.id) // when both have same finished state, sort by started - if (isFinished(a.id) === isFinished(b.id)) { + if (finished === isFinished(b.id)) { + if (finished) { + return b.puzzle.data.finished - a.puzzle.data.finished + } return b.puzzle.data.started - a.puzzle.data.started } // otherwise, sort: unfinished, finished - return isFinished(a.id) ? 1 : -1 + return finished ? 1 : -1 }) } From 8f31a669d5f81b87b5c40d5e1f55d6b0c2c1661d Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 17:48:49 +0200 Subject: [PATCH 06/17] send client id header with every request initiated from frontend to backend --- src/frontend/Communication.ts | 3 ++- src/frontend/components/Upload.vue | 4 ++-- src/frontend/main.ts | 18 +++++++++++------- src/frontend/views/Index.vue | 3 ++- src/frontend/views/NewGame.vue | 8 +++----- src/frontend/xhr.ts | 9 ++++++++- 6 files changed, 28 insertions(+), 17 deletions(-) diff --git a/src/frontend/Communication.ts b/src/frontend/Communication.ts index 70a61c8..899a269 100644 --- a/src/frontend/Communication.ts +++ b/src/frontend/Communication.ts @@ -3,6 +3,7 @@ import { ClientEvent, EncodedGame, GameEvent, ReplayData, ServerEvent } from '../common/Types' import Util, { logger } from '../common/Util' import Protocol from './../common/Protocol' +import xhr from './xhr' const log = logger('Communication.js') @@ -117,7 +118,7 @@ async function requestReplayData( offset: number ): Promise { const args = { gameId, offset } - const res = await fetch(`/api/replay-data${Util.asQueryArgs(args)}`) + const res = await xhr.get(`/api/replay-data${Util.asQueryArgs(args)}`, {}) const json: ReplayData = await res.json() return json } diff --git a/src/frontend/components/Upload.vue b/src/frontend/components/Upload.vue index a5a6949..ec030c6 100644 --- a/src/frontend/components/Upload.vue +++ b/src/frontend/components/Upload.vue @@ -6,6 +6,7 @@ + diff --git a/build/server/main.js b/build/server/main.js index 3f60a65..5e3f14e 100644 --- a/build/server/main.js +++ b/build/server/main.js @@ -610,12 +610,16 @@ function setEvtInfo(gameId, playerId, evtInfo) { } function getAllGames() { return Object.values(GAMES).sort((a, b) => { + const finished = isFinished(a.id); // when both have same finished state, sort by started - if (isFinished(a.id) === isFinished(b.id)) { + if (finished === isFinished(b.id)) { + if (finished) { + return b.puzzle.data.finished - a.puzzle.data.finished; + } return b.puzzle.data.started - a.puzzle.data.started; } // otherwise, sort: unfinished, finished - return isFinished(a.id) ? 1 : -1; + return finished ? 1 : -1; }); } function getAllPlayers(gameId) { @@ -1439,6 +1443,7 @@ const imageFromDb = (db, imageId) => { const i = db.get('images', { id: imageId }); return { id: i.id, + uploaderUserId: i.uploader_user_id, filename: i.filename, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, @@ -1477,6 +1482,7 @@ inner join images i on i.id = ixc.image_id ${where.sql}; const images = db.getMany('images', wheresRaw, orderByMap[orderBy]); return images.map(i => ({ id: i.id, + uploaderUserId: i.uploader_user_id, filename: i.filename, url: `${UPLOAD_URL}/${encodeURIComponent(i.filename)}`, title: i.title, @@ -1494,6 +1500,7 @@ const allImagesFromDisk = (tags, sort) => { .filter(f => f.toLowerCase().match(/\.(jpe?g|webp|png)$/)) .map(f => ({ id: 0, + uploaderUserId: null, filename: f, url: `${UPLOAD_URL}/${encodeURIComponent(f)}`, title: f.replace(/\.[a-z]+$/, ''), @@ -2093,6 +2100,16 @@ const storage = multer.diskStorage({ } }); const upload = multer({ storage }).single('file'); +app.get('/api/me', (req, res) => { + let user = db.get('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + }); + res.send({ + id: user ? user.id : null, + created: user ? user.created : null, + }); +}); app.get('/api/conf', (req, res) => { res.send({ WS_ADDRESS: config.ws.connectstring, @@ -2164,7 +2181,24 @@ const setImageTags = (db, imageId, tags) => { }); }; app.post('/api/save-image', express.json(), (req, res) => { + let user = db.get('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + }); + let userId = null; + if (user) { + userId = parseInt(user.id, 10); + } + else { + res.status(403).send({ ok: false, error: 'forbidden' }); + return; + } const data = req.body; + let image = db.get('images', { id: data.id }); + if (parseInt(image.uploader_user_id, 10) !== userId) { + res.status(403).send({ ok: false, error: 'forbidden' }); + return; + } db.update('images', { title: data.title, }, { @@ -2189,8 +2223,24 @@ app.post('/api/upload', (req, res) => { log.log(err); res.status(400).send("Something went wrong!"); } + let user = db.get('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + }); + let userId = null; + if (user) { + userId = user.id; + } + else { + userId = db.insert('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + 'created': Time.timestamp(), + }); + } const dim = await Images.getDimensions(`${UPLOAD_DIR}/${req.file.filename}`); const imageId = db.insert('images', { + uploader_user_id: userId, filename: req.file.filename, filename_original: req.file.originalname, title: req.body.title || '', From c11229a5e568a5684bbc0f72be51d88d3738a854 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 21:11:13 +0200 Subject: [PATCH 10/17] fix info overlay --- src/frontend/components/InfoOverlay.vue | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/frontend/components/InfoOverlay.vue b/src/frontend/components/InfoOverlay.vue index efc11fe..1bf6220 100644 --- a/src/frontend/components/InfoOverlay.vue +++ b/src/frontend/components/InfoOverlay.vue @@ -9,15 +9,15 @@ {{game.puzzle.info.image.title}} - Snap Mode: + Scoring: {{scoreMode[0]}} - Shape Mode: + Shapes: {{shapeMode[0]}} - Score Mode: + Snapping: {{snapMode[0]}} From e5fb49ecb1d9ee68f52931a3b869eaba0266aad4 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 21:14:25 +0200 Subject: [PATCH 11/17] build --- build/public/assets/index.97691b3e.js | 1 + build/public/assets/index.cbfa449f.js | 1 - build/public/index.html | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 build/public/assets/index.97691b3e.js delete mode 100644 build/public/assets/index.cbfa449f.js diff --git a/build/public/assets/index.97691b3e.js b/build/public/assets/index.97691b3e.js new file mode 100644 index 0000000..11c7d04 --- /dev/null +++ b/build/public/assets/index.97691b3e.js @@ -0,0 +1 @@ +import{d as e,c as t,a as n,w as l,b as o,r as a,o as s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),E=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:l((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:l((()=>[E])),_:1})])])):o("",!0),n(g)])};let M="",D="";const N=async(e,t,n)=>new Promise(((l,o)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.setRequestHeader("Client-Id",M),a.setRequestHeader("Client-Secret",D),a.addEventListener("load",(function(e){l({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){o(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body||null)}));var _=(e,t)=>N("get",e,t),V=(e,t)=>N("post",e,t),O=e=>{M=e},B=e=>{D=e};const U=864e5,R=e=>{const t=Math.floor(e/U);e%=U;const n=Math.floor(e/36e5);e%=36e5;const l=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${l}m ${Math.floor(e/1e3)}s`};var $=1,G=1e3,L=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},F=(e,t)=>R(t-e),j=R,W=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",l=e,o=t||L();return`${n} ${F(l,o)}`}}});const H={class:"game-info-text"},K=n("br",null,null,-1),q=n("br",null,null,-1),Y=n("br",null,null,-1),Q=i(" ↪️ Watch replay ");W.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:l((()=>[n("span",H,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),K,i(" 👥 "+r(e.game.players),1),q,i(" "+r(e.time(e.game.started,e.game.finished)),1),Y])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:l((()=>[Q])),_:1},8,["to"])):o("",!0)],4)};var Z=e({components:{GameTeaser:W},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await _("/api/index-data",{}),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const X=n("h1",null,"Running games",-1),J=n("h1",null,"Finished games",-1);Z.render=function(e,l,o,i,r,u){const p=a("game-teaser");return s(),t("div",null,[X,(s(!0),t(d,null,c(e.gamesRunning,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128)),J,(s(!0),t(d,null,c(e.gamesFinished,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128))])};var ee=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}},canEdit(){return!!this.$me.id&&this.$me.id===this.image.uploaderUserId}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});ee.render=function(e,n,l,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:n[2]||(n[2]=(...t)=>e.onClick&&e.onClick(...t))},[e.canEdit?(s(),t("div",{key:0,class:"btn edit",onClick:n[1]||(n[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")):o("",!0)],4)};var te=e({name:"image-library",components:{ImageTeaser:ee},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,l,o,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,l)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:l},null,8,["image","onClick","onEditClick"])))),128))])};class 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),l=t[n];t[n]=t[e],t[e]=l}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new ne(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},oe=(...e)=>{const t=t=>(...n)=>{const l=new Date,o=le(l.getHours(),"00"),a=le(l.getMinutes(),"00"),s=le(l.getSeconds(),"00");console[t](`${o}:${a}:${s}`,...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,e.shapeMode,e.snapMode]},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 l=[n,e[n]].map(encodeURIComponent);t.push(l.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,l,o,a,i){return s(),t("div",{style:i.style,title:l.title},null,12,["title"])};var ie=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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-a4fa5e7e");const de={key:0,class:"autocomplete"};f();const ce=re(((e,l,a,i,u,m)=>(s(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.input=t),placeholder:"Plants, People",onChange:l[2]||(l[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:l[3]||(l[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:l[4]||(l[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(s(),t("div",de,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,l)=>(s(),t("li",{key:l,class:{active:l===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):o("",!0),(s(!0),t(d,null,c(e.values,((n,l)=>(s(),t("span",{key:l,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ie.render=ce,ie.__scopeId="data-v-a4fa5e7e";const ue=oe("NewImageDialog.vue");var pe=e({name:"new-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const l=n[0];return l.type.startsWith("image/")?l:null},onFileSelect(e){const t=e.target;if(!t.files)return;const n=t.files[0];n&&this.preview(n)},preview(e){const t=new FileReader;t.readAsDataURL(e),t.onload=t=>{this.previewUrl=t.target.result,this.file=e}},postToGallery(){this.$emit("postToGalleryClick",{file:this.file,title:this.title,tags:this.tags})},setupGameClick(){this.$emit("setupGameClick",{file:this.file,title:this.title,tags:this.tags})},onDrop(e){this.droppable=!1;const t=this.imageFromDragEvt(e);if(!t)return!1;const n=t.getAsFile();return!!n&&(this.file=n,this.preview(n),e.preventDefault(),!1)},onDragover(e){return!!this.imageFromDragEvt(e)&&(this.droppable=!0,e.preventDefault(),!1)},onDragleave(){ue.info("onDragleave"),this.droppable=!1}}});const ge=n("div",{class:"drop-target"},null,-1),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),Ce=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},ke=i("🖼️ Post to gallery"),Pe=i("🧩 Post to gallery "),Ae=n("br",null,null,-1),Se=i(" + set up game");pe.render=function(e,l,o,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),t("div",{class:"overlay new-image-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:l[3]||(l[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:l[4]||(l[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:l[5]||(l[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[ge,e.previewUrl?(s(),t("div",he,[n("span",{class:"remove btn",onClick:l[1]||(l[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",me,[n("label",ye,[n("input",{type:"file",style:{display:"none"},onChange:l[2]||(l[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":l[6]||(l[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),be,n("tr",null,[Ce,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":l[7]||(l[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",xe,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:l[8]||(l[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ke],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:l[9]||(l[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[Pe,Ae,Se],64))],8,["disabled"])])])])};var ze=e({name:"edit-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},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 Te={class:"area-image"},Ie={class:"has-image"},Ee={class:"area-settings"},Me=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),Ne=n("td",null,[n("label",null,"Tags")],-1),_e={class:"area-buttons"};var Ve,Oe,Be,Ue,Re,$e,Ge,Le;ze.render=function(e,l,o,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),t("div",{class:"overlay edit-image-dialog",onClick:l[5]||(l[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[4]||(l[4]=u((()=>{}),["stop"]))},[n("div",Te,[n("div",Ie,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Ee,[n("table",null,[n("tr",null,[Me,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),De,n("tr",null,[Ne,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":l[2]||(l[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",_e,[n("button",{class:"btn",onClick:l[3]||(l[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Oe=Ve||(Ve={}))[Oe.Flat=0]="Flat",Oe[Oe.Out=1]="Out",Oe[Oe.In=-1]="In",(Ue=Be||(Be={}))[Ue.FINAL=0]="FINAL",Ue[Ue.ANY=1]="ANY",($e=Re||(Re={}))[$e.NORMAL=0]="NORMAL",$e[$e.ANY=1]="ANY",$e[$e.FLAT=2]="FLAT",(Le=Ge||(Ge={}))[Le.NORMAL=0]="NORMAL",Le[Le.REAL=1]="REAL";var Fe=e({name:"new-game-dialog",components:{ResponsiveImage:se},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Be.ANY,shapeMode:Re.NORMAL,snapMode:Ge.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 je={class:"area-image"},We={class:"has-image"},He={key:0,class:"image-title"},Ke={key:0,class:"image-title-title"},qe={key:1,class:"image-title-dim"},Ye={class:"area-settings"},Qe=n("td",null,[n("label",null,"Pieces")],-1),Ze=n("td",null,[n("label",null,"Scoring: ")],-1),Xe=i(" Any (Score when pieces are connected to each other or on final location)"),Je=n("br",null,null,-1),et=i(" Final (Score when pieces are put to their final location)"),tt=n("td",null,[n("label",null,"Shapes: ")],-1),nt=i(" Normal"),lt=n("br",null,null,-1),ot=i(" Any (flat pieces can occur anywhere)"),at=n("br",null,null,-1),st=i(" Flat (all pieces flat on all sides)"),it=n("td",null,[n("label",null,"Snapping: ")],-1),rt=i(" Normal (pieces snap to final destination and to each other)"),dt=n("br",null,null,-1),ct=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ut={class:"area-buttons"};Fe.render=function(e,l,i,d,c,h){const m=a("responsive-image");return s(),t("div",{class:"overlay new-game-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",je,[n("div",We,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",He,[e.image.title?(s(),t("span",Ke,'"'+r(e.image.title)+'"',1)):o("",!0),e.image.width||e.image.height?(s(),t("span",qe,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):o("",!0)])):o("",!0)]),n("div",Ye,[n("table",null,[n("tr",null,[Qe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[Ze,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[2]||(l[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),Xe]),Je,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[3]||(l[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),et])])]),n("tr",null,[tt,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[4]||(l[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),nt]),lt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[5]||(l[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),ot]),at,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[6]||(l[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),st])])]),n("tr",null,[it,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[7]||(l[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),rt]),dt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[8]||(l[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),ct])])])])]),n("div",ut,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:l[9]||(l[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var pt=e({components:{ImageLibrary:te,NewImageDialog:pe,EditImageDialog:ze,NewGameDialog:Fe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await _(`/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){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await V("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await V("/api/save-image",{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){const t=await this.saveImage(e);t.ok?(this.dialog="",await this.loadImages()):alert(t.error)},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await V("/api/newgame",{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 gt={class:"upload-image-teaser"},ht=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),mt={key:0},yt=i(" Tags: "),ft=i(" Sort by: "),vt=n("option",{value:"date_desc"},"Newest first",-1),wt=n("option",{value:"date_asc"},"Oldest first",-1),bt=n("option",{value:"alpha_asc"},"A-Z",-1),Ct=n("option",{value:"alpha_desc"},"Z-A",-1);pt.render=function(e,l,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",gt,[n("div",{class:"btn btn-big",onClick:l[1]||(l[1]=t=>e.dialog="new-image")},"Upload your image"),ht]),n("div",null,[e.tags.length>0?(s(),t("label",mt,[yt,(s(!0),t(d,null,c(e.relevantTags,((n,l)=>(s(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:l,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):o("",!0),n("label",null,[ft,p(n("select",{"onUpdate:modelValue":l[2]||(l[2]=t=>e.filters.sort=t),onChange:l[3]||(l[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[vt,wt,bt,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?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:l[4]||(l[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):o("",!0),"edit-image"===e.dialog?(s(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:l[5]||(l[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):o("",!0),e.image&&"new-game"===e.dialog?(s(),t(v,{key:2,onBgclick:l[6]||(l[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):o("",!0)])};var xt=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 kt={class:"scores"},Pt=n("div",null,"Scores",-1),At=n("td",null,"⚡",-1),St=n("td",null,"💤",-1);xt.render=function(e,l,o,a,i,u){return s(),t("div",kt,[Pt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[At,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[St,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var zt=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 j(this.duration)}}});const Tt={class:"timer"};zt.render=function(e,l,o,a,i,d){return s(),t("div",Tt,[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 It=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const Et=m();y("data-v-4d56fc17");const Mt=n("td",null,[n("label",null,"Background: ")],-1),Dt=n("td",null,[n("label",null,"Color: ")],-1),Nt=n("td",null,[n("label",null,"Name: ")],-1),_t=n("td",null,[n("label",null,"Sounds: ")],-1),Vt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Ot={class:"sound-volume"},Bt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Ut=Et(((e,l,o,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:l[10]||(l[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:l[9]||(l[9]=u((()=>{}),["stop"]))},[n("tr",null,[Mt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[1]||(l[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[2]||(l[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[Nt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":l[3]||(l[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[_t,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[4]||(l[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Vt,n("td",Ot,[n("span",{onClick:l[5]||(l[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:l[6]||(l[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:l[7]||(l[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Bt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[8]||(l[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));It.render=Ut,It.__scopeId="data-v-4d56fc17";var Rt=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const $t={class:"preview"};Rt.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay",onClick:l[1]||(l[1]=t=>e.$emit("bgclick"))},[n("div",$t,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Gt=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Be.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Be.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case Re.FLAT:return["Flat","all pieces flat on all sides"];case Re.ANY:return["Any","flat pieces can occur anywhere"];case Re.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case Ge.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case Ge.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Lt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ft=n("td",null,"Image Title: ",-1),jt=n("td",null,"Scoring: ",-1),Wt=n("td",null,"Shapes: ",-1),Ht=n("td",null,"Snapping: ",-1);Gt.render=function(e,l,o,a,i,d){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Lt,n("tr",null,[Ft,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[jt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[Wt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Ht,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Kt=1,qt=4,Yt=2,Qt=3,Zt=2,Xt=4,Jt=3,en=9,tn=1,nn=2,ln=3,on=4,an=5,sn=6,rn=7,dn=8,cn=10,un=11,pn=12,gn=13,hn=14,mn=15,yn=16,fn=17,vn=18,wn=1,bn=2,Cn=3;const xn=oe("Communication.js");let kn,Pn=[],An=e=>{Pn.push(e)},Sn=[],zn=e=>{Sn.push(e)};let Tn=0;const In=e=>{Tn!==e&&(Tn=e,zn(e))};function En(e){if(2===Tn)try{kn.send(JSON.stringify(e))}catch(t){xn.info("unable to send message.. maybe because ws is invalid?")}}let Mn,Dn;var Nn={connect:function(e,t,n){return Mn=0,Dn={},In(3),new Promise((l=>{kn=new WebSocket(e,n+"|"+t),kn.onopen=()=>{In(2),En([Qt])},kn.onmessage=e=>{const t=JSON.parse(e.data),o=t[0];if(o===qt){const e=t[1];l(e)}else{if(o!==Kt)throw`[ 2021-05-09 invalid connect msgType ${o} ]`;{const e=t[1],l=t[2];if(e===n&&Dn[l])return void delete Dn[l];An(t)}}},kn.onerror=()=>{throw In(1),"[ 2021-05-15 onerror ]"},kn.onclose=e=>{4e3===e.code||1001===e.code?In(4):In(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},l=await _(`/api/replay-data${ae.asQueryArgs(n)}`,{});return await l.json()},disconnect:function(){kn&&kn.close(4e3),Mn=0,Dn={}},sendClientEvent:function(e){Mn++,Dn[Mn]=e,En([Yt,Mn,Dn[Mn]])},onServerChange:function(e){An=e;for(const t of Pn)An(t);Pn=[]},onConnectionStateChange:function(e){zn=e;for(const t of Sn)zn(t);Sn=[]},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},_n=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 Vn={key:0,class:"overlay connection-lost"},On={key:0,class:"overlay-content"},Bn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),Un={key:1,class:"overlay-content"},Rn=n("div",null,"Connecting...",-1);_n.render=function(e,l,a,i,r,d){return e.show?(s(),t("div",Vn,[e.lostConnection?(s(),t("div",On,[Bn,n("span",{class:"btn",onClick:l[1]||(l[1]=t=>e.$emit("reconnect"))},"Reconnect")])):o("",!0),e.connecting?(s(),t("div",Un,[Rn])):o("",!0)])):o("",!0)};var $n=e({name:"help-overlay",emits:{bgclick:null}});const Gn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Ln=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Fn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),jn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Wn=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Hn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),Kn=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),qn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Yn=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Qn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),Zn=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 player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Jn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),el=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),tl=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),nl=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);$n.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Gn,Ln,Fn,jn,Wn,Hn,Kn,qn,Yn,Qn,Zn,Xn,Jn,el,tl,nl])])};var ll=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),ol=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),al=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),sl=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),il=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function rl(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var dl={createCanvas:rl,loadImageToBitmap:async function(e){return new Promise((t=>{const n=new Image;n.onload=()=>{createImageBitmap(n).then(t)},n.src=e}))},resizeBitmap:async function(e,t,n){const l=rl(t,n);return l.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(l)},colorizedCanvas:function(e,t,n){const l=rl(e.width,e.height),o=l.getContext("2d");return o.save(),o.drawImage(t,0,0),o.fillStyle=n,o.globalCompositeOperation="source-in",o.fillRect(0,0,t.width,t.height),o.restore(),o.save(),o.globalCompositeOperation="destination-over",o.drawImage(e,0,0),o.restore(),l}};const cl=oe("Debug.js");let ul=0,pl=0;var gl=e=>{ul=performance.now(),pl=e},hl=e=>{const t=performance.now(),n=t-ul;n>pl&&cl.log(e+": "+n),ul=t};function ml(e,t){const n=e.x-t.x,l=e.y-t.y;return Math.sqrt(n*n+l*l)}function yl(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var fl={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:ml,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:yl,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 ml(yl(e),yl(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 vl=oe("PuzzleGraphics.js");function wl(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 bl={loadPuzzleBitmaps:async function(e){const t=await dl.loadImageToBitmap(e.info.imageUrl),n=await dl.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){vl.log("start createPuzzleTileBitmaps");const l=n.tileSize,o=n.tileMarginWidth,a=n.tileDrawSize,s=l/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:o,y:o},r=fl.pointAdd(a,{x:l,y:0}),c=fl.pointAdd(r,{x:0,y:l}),u=fl.pointSub(c,{x:l,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let l=0;lae.decodePiece(Cl[e].puzzle.tiles[t]),Ol=(e,t)=>Vl(e,t).group,Bl=(e,t)=>{const n=Cl[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},Ul=(e,t)=>{const n=Cl[e].puzzle.info,l={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},o=function(e,t){const n=Cl[e].puzzle.info,l=ae.coordByPieceIdx(n,t),o=l.x*n.tileSize,a=l.y*n.tileSize;return{x:o,y:a}}(e,t);return fl.pointAdd(l,o)},Rl=(e,t)=>Vl(e,t).pos,$l=e=>{const t=lo(e),n=oo(e),l=Math.round(t/4),o=Math.round(n/4);return{x:0-l,y:0-o,w:t+2*l,h:n+2*o}},Gl=(e,t)=>{const n=Wl(e),l=Vl(e,t);return{x:l.pos.x,y:l.pos.y,w:n,h:n}},Ll=(e,t)=>Vl(e,t).z,Fl=(e,t)=>{for(const n of Cl[e].puzzle.tiles){const e=ae.decodePiece(n);if(e.owner===t)return e.idx}return-1},jl=e=>Cl[e].puzzle.info.tileDrawSize,Wl=e=>Cl[e].puzzle.info.tileSize,Hl=e=>Cl[e].puzzle.data.maxGroup,Kl=e=>Cl[e].puzzle.data.maxZ;function ql(e,t){const n=Cl[e].puzzle.info,l=ae.coordByPieceIdx(n,t);return[l.y>0?t-n.tilesX:-1,l.x0?t-1:-1]}const Yl=(e,t,n)=>{for(const l of t)_l(e,l,{z:n})},Ql=(e,t,n)=>{const l=Rl(e,t);_l(e,t,{pos:fl.pointAdd(l,n)})},Zl=(e,t,n)=>{const l=jl(e),o=$l(e),a=n;for(const s of t){const t=Vl(e,s);t.pos.x+n.xo.x+o.w&&(a.x=Math.min(o.x+o.w-t.pos.x+l,a.x)),t.pos.y+n.yo.y+o.h&&(a.y=Math.min(o.y+o.h-t.pos.y+l,a.y))}for(const s of t)Ql(e,s,a)},Xl=(e,t)=>Vl(e,t).owner,Jl=(e,t)=>{for(const n of t)_l(e,n,{owner:-1,z:1})},eo=(e,t,n)=>{for(const l of t)_l(e,l,{owner:n})};function to(e,t){const n=Cl[e].puzzle.tiles,l=ae.decodePiece(n[t]),o=[];if(l.group)for(const a of n){const e=ae.decodePiece(a);e.group===l.group&&o.push(e.idx)}else o.push(l.idx);return o}const no=(e,t)=>{const n=kl(e,t);return n?n.points:0},lo=e=>Cl[e].puzzle.info.table.width,oo=e=>Cl[e].puzzle.info.table.height;var ao={setGame:function(e,t){Cl[e]=t},exists:function(e){return!!Cl[e]||!1},playerExists:Al,getActivePlayers:function(e,t){const n=t-30*G;return Sl(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*G;return Sl(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){Al(e,t)?Dl(e,t,{ts:n}):Pl(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:Ml,getPieceCount:zl,getImageUrl:function(e){var t;const n=(null==(t=Cl[e].puzzle.info.image)?void 0:t.url)||Cl[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return Cl[e]||null},getAllGames:function(){return Object.values(Cl).sort(((e,t)=>{const n=El(e.id);return n===El(t.id)?n?t.puzzle.data.finished-e.puzzle.data.finished:t.puzzle.data.started-e.puzzle.data.started:n?1:-1}))},getPlayerBgColor:(e,t)=>{const n=kl(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=kl(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=kl(e,t);return n?n.name:null},getPlayerIndexById:xl,getPlayerIdByIndex:function(e,t){return Cl[e].players.length>t?ae.decodePlayer(Cl[e].players[t]).id:null},changePlayer:Dl,setPlayer:Pl,setPiece:function(e,t,n){Cl[e].puzzle.tiles[t]=ae.encodePiece(n)},setPuzzleData:function(e,t){Cl[e].puzzle.data=t},getTableWidth:lo,getTableHeight:oo,getPuzzle:e=>Cl[e].puzzle,getRng:e=>Cl[e].rng.obj,getPuzzleWidth:e=>Cl[e].puzzle.info.width,getPuzzleHeight:e=>Cl[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return Cl[e].puzzle.tiles.map(ae.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Fl(e,t);return n<0?null:Cl[e].puzzle.tiles[n]},getPieceDrawOffset:e=>Cl[e].puzzle.info.tileDrawOffset,getPieceDrawSize:jl,getFinalPiecePos:Ul,getStartTs:e=>Cl[e].puzzle.data.started,getFinishTs:e=>Cl[e].puzzle.data.finished,handleInput:function(e,t,n,l,o){const a=Cl[e].puzzle,s=function(e,t){return t in Cl[e].evtInfos?Cl[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([wn,a.data])},d=t=>{i.push([bn,ae.encodePiece(Vl(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=kl(e,t);n&&i.push([Cn,ae.encodePlayer(n)])},p=n[0];if(p===sn){const o=n[1];Dl(e,t,{bgcolor:o,ts:l}),u()}else if(p===rn){const o=n[1];Dl(e,t,{color:o,ts:l}),u()}else if(p===dn){const o=`${n[1]}`.substr(0,16);Dl(e,t,{name:o,ts:l}),u()}else if(p===en){const o=n[1],a=n[2],s=kl(e,t);if(s){const n=s.x-o,i=s.y-a;Dl(e,t,{ts:l,x:n,y:i}),u()}}else if(p===tn){const o={x:n[1],y:n[2]};Dl(e,t,{d:1,ts:l}),u(),s._last_mouse_down=o;const a=((e,t)=>{const n=Cl[e].puzzle.info,l=Cl[e].puzzle.tiles;let o=-1,a=-1;for(let s=0;so)&&(o=e.z,a=s)}return a})(e,o);if(a>=0){const n=Kl(e)+1;Nl(e,{maxZ:n}),r();const l=to(e,a);Yl(e,l,Kl(e)),eo(e,l,t),c(l)}s._last_mouse=o}else if(p===ln){const o=n[1],a=n[2],i={x:o,y:a};if(null===s._last_mouse_down)Dl(e,t,{x:o,y:a,ts:l}),u();else{const n=Fl(e,t);if(n>=0){Dl(e,t,{x:o,y:a,ts:l}),u();const r=to(e,n);let d=fl.pointInBounds(i,$l(e))&&fl.pointInBounds(s._last_mouse_down,$l(e));for(const t of r){const n=Gl(e,t);if(fl.pointInBounds(i,n)){d=!0;break}}if(d){const t=o-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Zl(e,r,{x:t,y:n}),c(r)}}else Dl(e,t,{ts:l}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===nn){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Fl(e,t);if(g>=0){const n=to(e,g);eo(e,n,0),c(n);const s=Rl(e,g),i=Ul(e,g);let h=!1;if(Il(e)===Ge.REAL){for(const t of n)if(Bl(e,t)){h=!0;break}}else h=!0;if(h&&fl.pointDistance(i,s){const o=Cl[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const l=Ol(e,t),o=Ol(e,n);return!(!l||l!==o)})(e,t,n))return!1;const a=Rl(e,t),s=fl.pointAdd(Rl(e,n),{x:l[0]*o.tileSize,y:l[1]*o.tileSize});if(fl.pointDistance(a,s){const l=Cl[e].puzzle.tiles,o=Ol(e,t),a=Ol(e,n);let s;const i=[];o&&i.push(o),a&&i.push(a),o?s=o:a?s=a:(Nl(e,{maxGroup:Hl(e)+1}),r(),s=Hl(e));if(_l(e,t,{group:s}),d(t),_l(e,n,{group:s}),d(n),i.length>0)for(const r of l){const t=ae.decodePiece(r);i.includes(t.group)&&(_l(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),o=to(e,t),((e,t)=>-1===Xl(e,t))(e,n))Jl(e,o);else{const t=((e,t)=>{let n=0;for(const l of t){const t=Ll(e,l);t>n&&(n=t)}return n})(e,o);Yl(e,o,t)}return c(o),!0}return!1};let a=!1;for(const t of to(e,g)){const l=ql(e,t);if(n(e,t,l[0],[0,1])||n(e,t,l[1],[-1,0])||n(e,t,l[2],[0,-1])||n(e,t,l[3],[1,0])){a=!0;break}}if(a&&Tl(e)===Be.ANY){const n=no(e,t)+1;Dl(e,t,{d:p,ts:l,points:n}),u()}else Dl(e,t,{d:p,ts:l}),u();a&&Il(e)===Ge.REAL&&Ml(e)===zl(e)&&(Nl(e,{finished:l}),r()),a&&o&&o(t)}}else Dl(e,t,{d:p,ts:l}),u();s._last_mouse=i}else if(p===on){const o=n[1],a=n[2];Dl(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else if(p===an){const o=n[1],a=n[2];Dl(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else Dl(e,t,{ts:l}),u();return function(e,t,n){Cl[e].evtInfos[t]=n}(e,t,s),i}};let so=-10,io=20,ro=2,co=15;class uo{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=so+Math.random()*io,this.vy=-1*(ro+Math.random()*co),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;ro=t/2,co=t-ro;const n=1/4*this.canvas.width/(t/2);so=-n,io=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new uo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new uo(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{localStorage.setItem(e,t)},Co=e=>localStorage.getItem(e);var xo=(e,t)=>{bo(e,`${t}`)},ko=(e,t)=>{const n=Co(e);if(null===n)return t;const l=parseInt(n,10);return isNaN(l)?t:l},Po=(e,t)=>{bo(e,t?"1":"0")},Ao=(e,t)=>{const n=Co(e);return null===n?t:"1"===n},So=(e,t)=>{bo(e,t)},zo=(e,t)=>{const n=Co(e);return null===n?t:n};const To={"./grab.png":ol,"./grab_mask.png":al,"./hand.png":sl,"./hand_mask.png":il},Io={"./click.mp3":ll},Eo="replay";let Mo=!0,Do=!0;let No=!0;async function _o(e,t,n,l,o,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=Io["./click.mp3"].default,i=new Audio(s),r=await dl.loadImageToBitmap(To["./grab.png"].default),d=await dl.loadImageToBitmap(To["./hand.png"].default),c=await dl.loadImageToBitmap(To["./grab_mask.png"].default),u=await dl.loadImageToBitmap(To["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const l=e.d?c:u;y[t]=await createImageBitmap(dl.colorizedCanvas(n,l,e.color))}else y[t]=n}return y[t]},v=function(e,t){return t.width=window.innerWidth,t.height=window.innerHeight,e.appendChild(t),window.addEventListener("resize",(()=>{t.width=window.innerWidth,t.height=window.innerHeight,No=!0})),t}(o,dl.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};Nn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Nn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===l){const l=await Nn.connect(n,e,t),o=ae.decodeGame(l);ao.setGame(o.id,o),C=()=>L()}else{if(l!==Eo)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);ao.setGame(n.id,n),w.lastRealTs=L(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}No=!0};await x();const k=ao.getPieceDrawOffset(e),P=ao.getPieceDrawSize(e),A=ao.getPuzzleWidth(e),S=ao.getPuzzleHeight(e),z=ao.getTableWidth(e),T=ao.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},E={w:A,h:S},M={w:P,h:P},D=await bl.loadPuzzleBitmaps(ao.getPuzzle(e)),N=new go(v,ao.getRng(e));N.init();const _=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const V=function(){let e=0,t=0,n=1;const l=(l,o)=>{e+=l/n,t+=o/n},o=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=(e,t)=>{if(n==e)return!1;const o=1-n/e;return l(-t.x*o,-t.y*o),n=e,!0},s=l=>({x:l.x/n-e,y:l.y/n-t}),i=l=>({x:(l.x+e)*n,y:(l.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:l,canZoom:e=>n!=o(e),zoom:(e,t)=>a(o(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),O=()=>{V.reset(),V.move(-(z-v.width)/2,-(T-v.height)/2);const e=V.worldDimToViewport(E),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const l=n.viewportToWorld({x:e,y:t});return[l.x,l.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([tn,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([nn,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([ln,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?on:an;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([cn]),l===Eo&&("KeyI"===e.code&&v([gn]),"KeyO"===e.code&&v([hn]),"KeyP"===e.code&&v([pn])),"KeyF"===e.code&&v([fn]),"KeyG"===e.code&&v([vn]),"KeyM"===e.code&&v([un]),"KeyN"===e.code&&v([mn]),"KeyC"===e.code&&v([yn]))}));const v=e=>{o.push(e)};return{addEvent:v,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const l=(p?24:12)*Math.sqrt(n.getCurrentZoom()),o=n.viewportDimToWorld({w:e*l,h:t*l});v([en,o.w,o.h]),f&&(f[0]-=o.w,f[1]-=o.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([on,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([an,...e])}},setHotkeys:e=>{a=e}}}(v,window,V,l),U=ao.getImageUrl(e),R=()=>{const t=ao.getStartTs(e),n=ao.getFinishTs(e),l=C();a.setFinished(!!n),a.setDuration((n||l)-t)};R(),a.setPiecesDone(ao.getFinishedPiecesCount(e)),a.setPiecesTotal(ao.getPieceCount(e));const G=C();a.setActivePlayers(ao.getActivePlayers(e,G)),a.setIdlePlayers(ao.getIdlePlayers(e,G));const F=!!ao.getFinishTs(e);let j=F;const W=()=>j&&!F,H=()=>ko(ho,100),K=()=>Ao(mo,!1),q=()=>Ao(wo,!0),Y=()=>{const e=H();i.volume=e/100,i.play()},Q=()=>l===Eo?zo(yo,"#222222"):ao.getPlayerBgColor(e,t)||zo(yo,"#222222"),Z=()=>l===Eo?zo(fo,"#ffffff"):ao.getPlayerColor(e,t)||zo(fo,"#ffffff");let X="",J="",ee=!1;const te=e=>{ee=e;const[t,n]=e?[X,"grab"]:[J,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},ne=e=>{X=dl.colorizedCanvas(r,c,e).toDataURL(),J=dl.colorizedCanvas(d,u,e).toDataURL(),te(ee)};ne(Z());const le=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},oe=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,le())},ie=()=>{w.paused=!w.paused,le()},re=[];let de;let ce;if("play"===l?re.push(setInterval((()=>{R()}),1e3)):l===Eo&&le(),"play"===l)Nn.onServerChange((n=>{n[0],n[1],n[2];const l=n[3];for(const[o,a]of l)switch(o){case Cn:{const n=ae.decodePlayer(a);n.id!==t&&(ao.setPlayer(e,n.id,n),No=!0)}break;case bn:{const t=ae.decodePiece(a);ao.setPiece(e,t.idx,t),No=!0}break;case wn:ao.setPuzzleData(e,a),No=!0}j=!!ao.getFinishTs(e)}));else if(l===Eo){const t=(t,n)=>{const l=t;if(l[0]===Zt){const t=l[1];return ao.addPlayer(e,t,n),!0}if(l[0]===Xt){const t=ao.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return ao.addPlayer(e,t,n),!0}if(l[0]===Jt){const t=ao.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const o=l[2];return ao.handleInput(e,t,o,n),!0}return!1};let n=w.lastGameTs;const l=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=L();if(w.paused)return w.lastRealTs=o,void(de=setTimeout(l,50));const a=(o-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const l=w.log[w.logPointer],o=n+l[l.length-1],a=w.log[e],i=a[a.length-1],r=o+i;if(r>s){s+500*${let t=!1;const n=e.fps||60,l=e.slow||1,o=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=l*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,o(i);a(c/l),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{B.createKeyEvents();for(const n of B.consumeAll())if("play"===l){const l=n[0];if(l===en){const e=n[1],t=n[2],l=V.worldDimToViewport({w:e,h:t});No=!0,V.move(l.w,l.h)}else if(l===ln){if(ue&&!ao.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);No=!0,V.move(l,o),ue=t}}else if(l===rn)ne(n[1]);else if(l===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(l===nn)ue=null,te(!1);else if(l===on){const e={x:n[1],y:n[2]};No=!0,V.zoom("in",V.worldToViewport(e))}else if(l===an){const e={x:n[1],y:n[2]};No=!0,V.zoom("out",V.worldToViewport(e))}else l===cn?a.togglePreview():l===un?a.toggleSoundsEnabled():l===mn?a.togglePlayerNames():l===yn?O():l===fn?(Mo=!Mo,No=!0):l===vn&&(Do=!Do,No=!0);const o=C();ao.handleInput(e,t,n,o,(e=>{K()&&Y()})).length>0&&(No=!0),Nn.sendClientEvent(n)}else if(l===Eo){const e=n[0];if(e===pn)ie();else if(e===hn)se();else if(e===gn)oe();else if(e===en){const e=n[1],t=n[2];No=!0,V.move(e,t)}else if(e===ln){if(ue){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);No=!0,V.move(l,o),ue=t}}else if(e===rn)ne(n[1]);else if(e===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(e===nn)ue=null,te(!1);else if(e===on){const e={x:n[1],y:n[2]};No=!0,V.zoom("in",V.worldToViewport(e))}else if(e===an){const e={x:n[1],y:n[2]};No=!0,V.zoom("out",V.worldToViewport(e))}else e===cn?a.togglePreview():e===un?a.toggleSoundsEnabled():e===mn?a.togglePlayerNames():e===yn?O():e===fn?(Mo=!Mo,No=!0):e===vn&&(Do=!Do,No=!0)}j=!!ao.getFinishTs(e),W()&&(N.update(),No=!0)},render:async()=>{if(!No)return;const n=C();let o,s,i;window.DEBUG&&gl(0),_.fillStyle=Q(),_.fillRect(0,0,v.width,v.height),window.DEBUG&&hl("clear done"),o=V.worldToViewportRaw(I),s=V.worldDimToViewportRaw(E),_.fillStyle="rgba(255, 255, 255, .3)",_.fillRect(o.x,o.y,s.w,s.h),window.DEBUG&&hl("board done");const r=ao.getPiecesSortedByZIndex(e);window.DEBUG&&hl("get tiles done"),s=V.worldDimToViewportRaw(M);for(const e of r)(-1===e.owner?Mo:Do)&&(i=D[e.idx],o=V.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),_.drawImage(i,0,0,i.width,i.height,o.x,o.y,s.w,s.h));window.DEBUG&&hl("tiles done");const d=[];for(const a of ao.getActivePlayers(e,n))c=a,(l===Eo||c.id!==t)&&(i=await f(a),o=V.worldToViewport(a),_.drawImage(i,o.x-g,o.y-m),q()&&d.push([`${a.name} (${a.points})`,o.x,o.y+h]));var c;_.fillStyle="white",_.textAlign="center";for(const[e,t,l]of d)_.fillText(e,t,l);window.DEBUG&&hl("players done"),a.setActivePlayers(ao.getActivePlayers(e,n)),a.setIdlePlayers(ao.getIdlePlayers(e,n)),a.setPiecesDone(ao.getFinishedPiecesCount(e)),window.DEBUG&&hl("HUD done"),W()&&N.render(),No=!1}}),{setHotkeys:e=>{B.setHotkeys(e)},onBgChange:e=>{So(yo,e),B.addEvent([sn,e])},onColorChange:e=>{So(fo,e),B.addEvent([rn,e])},onNameChange:e=>{So(vo,e),B.addEvent([dn,e])},onSoundsEnabledChange:e=>{Po(mo,e)},onSoundsVolumeChange:e=>{xo(ho,e),Y()},onShowPlayerNamesChange:e=>{Po(wo,e)},replayOnSpeedUp:oe,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:U,player:{background:Q(),color:Z(),name:l===Eo?zo(vo,"anon"):ao.getPlayerName(e,t)||zo(vo,"anon"),soundsEnabled:K(),soundsVolume:H(),showPlayerNames:q()},game:ao.get(e),disconnect:Nn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var Vo=e({name:"game",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,ConnectionOverlay:_n,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _o(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const Oo={id:"game"},Bo={key:1,class:"overlay"},Uo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Ro={class:"menu"},$o={class:"tabs"},Go=i("🧩 Puzzles");Vo.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Oo,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Bo,[Uo])):o("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Ro,[n("div",$o,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[Go])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Lo=e({name:"replay",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _o(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,Eo,this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Fo={id:"replay"},jo={key:1,class:"overlay"},Wo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Ho={class:"menu"},Ko={class:"tabs"},qo=i("🧩 Puzzles");Lo.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Fo,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",jo,[Wo])):o("",!0),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:l((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Ho,[n("div",Ko,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[qo])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=function(){let e=zo("ID","");return e||(e=ae.uniqId(),So("ID",e)),e}(),t=function(){let e=zo("SECRET","");return e||(e=ae.uniqId(),So("SECRET",e)),e}();O(e),B(t);const n=await _("/api/me",{}),l=await n.json(),o=await _("/api/conf",{}),a=await o.json(),s=k({history:P(),routes:[{name:"index",path:"/",component:Z},{name:"new-game",path:"/new-game",component:pt},{name:"game",path:"/g/:id",component:Vo},{name:"replay",path:"/replay/:id",component:Lo}]});s.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const i=A(S);i.config.globalProperties.$me=l,i.config.globalProperties.$config=a,i.config.globalProperties.$clientId=e,i.use(s),i.mount("#app")})(); diff --git a/build/public/assets/index.cbfa449f.js b/build/public/assets/index.cbfa449f.js deleted file mode 100644 index ad9c29a..0000000 --- a/build/public/assets/index.cbfa449f.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 s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),M=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:o((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:o((()=>[M])),_:1})])])):l("",!0),n(g)])};let E="",D="";const N=async(e,t,n)=>new Promise(((o,l)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.setRequestHeader("Client-Id",E),a.setRequestHeader("Client-Secret",D),a.addEventListener("load",(function(e){o({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){l(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body||null)}));var _=(e,t)=>N("get",e,t),V=(e,t)=>N("post",e,t),O=e=>{E=e},B=e=>{D=e};const U=864e5,R=e=>{const t=Math.floor(e/U);e%=U;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 $=1,G=1e3,L=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},F=(e,t)=>R(t-e),j=R,W=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||L();return`${n} ${F(o,l)}`}}});const H={class:"game-info-text"},K=n("br",null,null,-1),q=n("br",null,null,-1),Y=n("br",null,null,-1),Q=i(" ↪️ Watch replay ");W.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",H,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),K,i(" 👥 "+r(e.game.players),1),q,i(" "+r(e.time(e.game.started,e.game.finished)),1),Y])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[Q])),_:1},8,["to"])):l("",!0)],4)};var Z=e({components:{GameTeaser:W},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await _("/api/index-data",{}),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const X=n("h1",null,"Running games",-1),J=n("h1",null,"Finished games",-1);Z.render=function(e,o,l,i,r,u){const p=a("game-teaser");return s(),t("div",null,[X,(s(!0),t(d,null,c(e.gamesRunning,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),J,(s(!0),t(d,null,c(e.gamesFinished,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var ee=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}},canEdit(){return!!this.$me.id&&this.$me.id===this.image.uploaderUserId}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});ee.render=function(e,n,o,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:n[2]||(n[2]=(...t)=>e.onClick&&e.onClick(...t))},[e.canEdit?(s(),t("div",{key:0,class:"btn edit",onClick:n[1]||(n[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")):l("",!0)],4)};var te=e({name:"image-library",components:{ImageTeaser:ee},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,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,o)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])};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"),s=oe(o.getSeconds(),"00");console[t](`${l}:${a}:${s}`,...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,e.shapeMode,e.snapMode]},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 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,i){return s(),t("div",{style:i.style,title:o.title},null,12,["title"])};var ie=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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-a4fa5e7e");const de={key:0,class:"autocomplete"};f();const ce=re(((e,o,a,i,u,m)=>(s(),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?(s(),t("div",de,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,o)=>(s(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(s(!0),t(d,null,c(e.values,((n,o)=>(s(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ie.render=ce,ie.__scopeId="data-v-a4fa5e7e";const ue=le("NewImageDialog.vue");var pe=e({name:"new-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const 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=n("div",{class:"drop-target"},null,-1),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),Ce=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},ke=i("🖼️ Post to gallery"),Pe=i("🧩 Post to gallery "),Ae=n("br",null,null,-1),Se=i(" + set up game");pe.render=function(e,o,l,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),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))},[ge,e.previewUrl?(s(),t("div",he,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),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,[Ce,n("td",null,[n(f,{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))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ke],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[Pe,Ae,Se],64))],8,["disabled"])])])])};var ze=e({name:"edit-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},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 Te={class:"area-image"},Ie={class:"has-image"},Me={class:"area-settings"},Ee=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),Ne=n("td",null,[n("label",null,"Tags")],-1),_e={class:"area-buttons"};var Ve,Oe,Be,Ue,Re,$e,Ge,Le;ze.render=function(e,o,l,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),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",Te,[n("div",Ie,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Me,[n("table",null,[n("tr",null,[Ee,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,[Ne,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")])])])},(Oe=Ve||(Ve={}))[Oe.Flat=0]="Flat",Oe[Oe.Out=1]="Out",Oe[Oe.In=-1]="In",(Ue=Be||(Be={}))[Ue.FINAL=0]="FINAL",Ue[Ue.ANY=1]="ANY",($e=Re||(Re={}))[$e.NORMAL=0]="NORMAL",$e[$e.ANY=1]="ANY",$e[$e.FLAT=2]="FLAT",(Le=Ge||(Ge={}))[Le.NORMAL=0]="NORMAL",Le[Le.REAL=1]="REAL";var Fe=e({name:"new-game-dialog",components:{ResponsiveImage:se},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Be.ANY,shapeMode:Re.NORMAL,snapMode:Ge.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 je={class:"area-image"},We={class:"has-image"},He={key:0,class:"image-title"},Ke={key:0,class:"image-title-title"},qe={key:1,class:"image-title-dim"},Ye={class:"area-settings"},Qe=n("td",null,[n("label",null,"Pieces")],-1),Ze=n("td",null,[n("label",null,"Scoring: ")],-1),Xe=i(" Any (Score when pieces are connected to each other or on final location)"),Je=n("br",null,null,-1),et=i(" Final (Score when pieces are put to their final location)"),tt=n("td",null,[n("label",null,"Shapes: ")],-1),nt=i(" Normal"),ot=n("br",null,null,-1),lt=i(" Any (flat pieces can occur anywhere)"),at=n("br",null,null,-1),st=i(" Flat (all pieces flat on all sides)"),it=n("td",null,[n("label",null,"Snapping: ")],-1),rt=i(" Normal (pieces snap to final destination and to each other)"),dt=n("br",null,null,-1),ct=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ut={class:"area-buttons"};Fe.render=function(e,o,i,d,c,h){const m=a("responsive-image");return s(),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",je,[n("div",We,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",He,[e.image.title?(s(),t("span",Ke,'"'+r(e.image.title)+'"',1)):l("",!0),e.image.width||e.image.height?(s(),t("span",qe,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):l("",!0)])):l("",!0)]),n("div",Ye,[n("table",null,[n("tr",null,[Qe,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,[Ze,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]]),Xe]),Je,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]]),et])])]),n("tr",null,[tt,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]]),nt]),ot,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]]),lt]),at,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]]),st])])]),n("tr",null,[it,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]]),rt]),dt,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]]),ct])])])])]),n("div",ut,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var pt=e({components:{ImageLibrary:te,NewImageDialog:pe,EditImageDialog:ze,NewGameDialog:Fe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await _(`/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){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await V("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await V("/api/save-image",{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){const t=await this.saveImage(e);t.ok?(this.dialog="",await this.loadImages()):alert(t.error)},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await V("/api/newgame",{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 gt={class:"upload-image-teaser"},ht=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),mt={key:0},yt=i(" Tags: "),ft=i(" Sort by: "),vt=n("option",{value:"date_desc"},"Newest first",-1),wt=n("option",{value:"date_asc"},"Oldest first",-1),bt=n("option",{value:"alpha_asc"},"A-Z",-1),Ct=n("option",{value:"alpha_desc"},"Z-A",-1);pt.render=function(e,o,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",gt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),ht]),n("div",null,[e.tags.length>0?(s(),t("label",mt,[yt,(s(!0),t(d,null,c(e.relevantTags,((n,o)=>(s(),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,[ft,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))},[vt,wt,bt,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?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(s(),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?(s(),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 xt=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 kt={class:"scores"},Pt=n("div",null,"Scores",-1),At=n("td",null,"⚡",-1),St=n("td",null,"💤",-1);xt.render=function(e,o,l,a,i,u){return s(),t("div",kt,[Pt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[At,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[St,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var zt=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 j(this.duration)}}});const Tt={class:"timer"};zt.render=function(e,o,l,a,i,d){return s(),t("div",Tt,[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 It=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const Mt=m();y("data-v-4d56fc17");const Et=n("td",null,[n("label",null,"Background: ")],-1),Dt=n("td",null,[n("label",null,"Color: ")],-1),Nt=n("td",null,[n("label",null,"Name: ")],-1),_t=n("td",null,[n("label",null,"Sounds: ")],-1),Vt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Ot={class:"sound-volume"},Bt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Ut=Mt(((e,o,l,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:o[10]||(o[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[9]||(o[9]=u((()=>{}),["stop"]))},[n("tr",null,[Et,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,[Dt,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,[Nt,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,[_t,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Vt,n("td",Ot,[n("span",{onClick:o[5]||(o[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:o[6]||(o[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:o[7]||(o[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Bt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[8]||(o[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));It.render=Ut,It.__scopeId="data-v-4d56fc17";var Rt=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const $t={class:"preview"};Rt.render=function(e,o,l,a,i,r){return s(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",$t,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Gt=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Be.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Be.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case Re.FLAT:return["Flat","all pieces flat on all sides"];case Re.ANY:return["Any","flat pieces can occur anywhere"];case Re.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case Ge.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case Ge.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Lt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ft=n("td",null,"Image Title: ",-1),jt=n("td",null,"Snap Mode: ",-1),Wt=n("td",null,"Shape Mode: ",-1),Ht=n("td",null,"Score Mode: ",-1);Gt.render=function(e,o,l,a,i,d){return s(),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"]))},[Lt,n("tr",null,[Ft,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[jt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[Wt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Ht,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Kt=1,qt=4,Yt=2,Qt=3,Zt=2,Xt=4,Jt=3,en=9,tn=1,nn=2,on=3,ln=4,an=5,sn=6,rn=7,dn=8,cn=10,un=11,pn=12,gn=13,hn=14,mn=15,yn=16,fn=17,vn=18,wn=1,bn=2,Cn=3;const xn=le("Communication.js");let kn,Pn=[],An=e=>{Pn.push(e)},Sn=[],zn=e=>{Sn.push(e)};let Tn=0;const In=e=>{Tn!==e&&(Tn=e,zn(e))};function Mn(e){if(2===Tn)try{kn.send(JSON.stringify(e))}catch(t){xn.info("unable to send message.. maybe because ws is invalid?")}}let En,Dn;var Nn={connect:function(e,t,n){return En=0,Dn={},In(3),new Promise((o=>{kn=new WebSocket(e,n+"|"+t),kn.onopen=()=>{In(2),Mn([Qt])},kn.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===qt){const e=t[1];o(e)}else{if(l!==Kt)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&Dn[o])return void delete Dn[o];An(t)}}},kn.onerror=()=>{throw In(1),"[ 2021-05-15 onerror ]"},kn.onclose=e=>{4e3===e.code||1001===e.code?In(4):In(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},o=await _(`/api/replay-data${ae.asQueryArgs(n)}`,{});return await o.json()},disconnect:function(){kn&&kn.close(4e3),En=0,Dn={}},sendClientEvent:function(e){En++,Dn[En]=e,Mn([Yt,En,Dn[En]])},onServerChange:function(e){An=e;for(const t of Pn)An(t);Pn=[]},onConnectionStateChange:function(e){zn=e;for(const t of Sn)zn(t);Sn=[]},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},_n=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 Vn={key:0,class:"overlay connection-lost"},On={key:0,class:"overlay-content"},Bn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),Un={key:1,class:"overlay-content"},Rn=n("div",null,"Connecting...",-1);_n.render=function(e,o,a,i,r,d){return e.show?(s(),t("div",Vn,[e.lostConnection?(s(),t("div",On,[Bn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(s(),t("div",Un,[Rn])):l("",!0)])):l("",!0)};var $n=e({name:"help-overlay",emits:{bgclick:null}});const Gn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Ln=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Fn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),jn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Wn=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Hn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),Kn=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),qn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Yn=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Qn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),Zn=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 player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Jn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),eo=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),to=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),no=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);$n.render=function(e,o,l,a,i,r){return s(),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"]))},[Gn,Ln,Fn,jn,Wn,Hn,Kn,qn,Yn,Qn,Zn,Xn,Jn,eo,to,no])])};var oo=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),lo=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),ao=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),so=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),io=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function ro(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var co={createCanvas:ro,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=ro(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=ro(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 uo=le("Debug.js");let po=0,go=0;var ho=e=>{po=performance.now(),go=e},mo=e=>{const t=performance.now(),n=t-po;n>go&&uo.log(e+": "+n),po=t};function yo(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function fo(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var vo={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:yo,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:fo,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 yo(fo(e),fo(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 wo=le("PuzzleGraphics.js");function bo(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 Co={loadPuzzleBitmaps:async function(e){const t=await co.loadImageToBitmap(e.info.imageUrl),n=await co.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){wo.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,s=o/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:l,y:l},r=vo.pointAdd(a,{x:o,y:0}),c=vo.pointAdd(r,{x:0,y:o}),u=vo.pointSub(c,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oae.decodePiece(xo[e].puzzle.tiles[t]),Bo=(e,t)=>Oo(e,t).group,Uo=(e,t)=>{const n=xo[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},Ro=(e,t)=>{const n=xo[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=xo[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 vo.pointAdd(o,l)},$o=(e,t)=>Oo(e,t).pos,Go=e=>{const t=ll(e),n=al(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}},Lo=(e,t)=>{const n=Ho(e),o=Oo(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},Fo=(e,t)=>Oo(e,t).z,jo=(e,t)=>{for(const n of xo[e].puzzle.tiles){const e=ae.decodePiece(n);if(e.owner===t)return e.idx}return-1},Wo=e=>xo[e].puzzle.info.tileDrawSize,Ho=e=>xo[e].puzzle.info.tileSize,Ko=e=>xo[e].puzzle.data.maxGroup,qo=e=>xo[e].puzzle.data.maxZ;function Yo(e,t){const n=xo[e].puzzle.info,o=ae.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const Qo=(e,t,n)=>{for(const o of t)Vo(e,o,{z:n})},Zo=(e,t,n)=>{const o=$o(e,t);Vo(e,t,{pos:vo.pointAdd(o,n)})},Xo=(e,t,n)=>{const o=Wo(e),l=Go(e),a=n;for(const s of t){const t=Oo(e,s);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 s of t)Zo(e,s,a)},Jo=(e,t)=>Oo(e,t).owner,el=(e,t)=>{for(const n of t)Vo(e,n,{owner:-1,z:1})},tl=(e,t,n)=>{for(const o of t)Vo(e,o,{owner:n})};function nl(e,t){const n=xo[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 ol=(e,t)=>{const n=Po(e,t);return n?n.points:0},ll=e=>xo[e].puzzle.info.table.width,al=e=>xo[e].puzzle.info.table.height;var sl={setGame:function(e,t){xo[e]=t},exists:function(e){return!!xo[e]||!1},playerExists:So,getActivePlayers:function(e,t){const n=t-30*G;return zo(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*G;return zo(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){So(e,t)?No(e,t,{ts:n}):Ao(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:Do,getPieceCount:To,getImageUrl:function(e){var t;const n=(null==(t=xo[e].puzzle.info.image)?void 0:t.url)||xo[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return xo[e]||null},getAllGames:function(){return Object.values(xo).sort(((e,t)=>{const n=Eo(e.id);return n===Eo(t.id)?n?t.puzzle.data.finished-e.puzzle.data.finished:t.puzzle.data.started-e.puzzle.data.started:n?1:-1}))},getPlayerBgColor:(e,t)=>{const n=Po(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=Po(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=Po(e,t);return n?n.name:null},getPlayerIndexById:ko,getPlayerIdByIndex:function(e,t){return xo[e].players.length>t?ae.decodePlayer(xo[e].players[t]).id:null},changePlayer:No,setPlayer:Ao,setPiece:function(e,t,n){xo[e].puzzle.tiles[t]=ae.encodePiece(n)},setPuzzleData:function(e,t){xo[e].puzzle.data=t},getTableWidth:ll,getTableHeight:al,getPuzzle:e=>xo[e].puzzle,getRng:e=>xo[e].rng.obj,getPuzzleWidth:e=>xo[e].puzzle.info.width,getPuzzleHeight:e=>xo[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return xo[e].puzzle.tiles.map(ae.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=jo(e,t);return n<0?null:xo[e].puzzle.tiles[n]},getPieceDrawOffset:e=>xo[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Wo,getFinalPiecePos:Ro,getStartTs:e=>xo[e].puzzle.data.started,getFinishTs:e=>xo[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=xo[e].puzzle,s=function(e,t){return t in xo[e].evtInfos?xo[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([wn,a.data])},d=t=>{i.push([bn,ae.encodePiece(Oo(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=Po(e,t);n&&i.push([Cn,ae.encodePlayer(n)])},p=n[0];if(p===sn){const l=n[1];No(e,t,{bgcolor:l,ts:o}),u()}else if(p===rn){const l=n[1];No(e,t,{color:l,ts:o}),u()}else if(p===dn){const l=`${n[1]}`.substr(0,16);No(e,t,{name:l,ts:o}),u()}else if(p===en){const l=n[1],a=n[2],s=Po(e,t);if(s){const n=s.x-l,i=s.y-a;No(e,t,{ts:o,x:n,y:i}),u()}}else if(p===tn){const l={x:n[1],y:n[2]};No(e,t,{d:1,ts:o}),u(),s._last_mouse_down=l;const a=((e,t)=>{const n=xo[e].puzzle.info,o=xo[e].puzzle.tiles;let l=-1,a=-1;for(let s=0;sl)&&(l=e.z,a=s)}return a})(e,l);if(a>=0){const n=qo(e)+1;_o(e,{maxZ:n}),r();const o=nl(e,a);Qo(e,o,qo(e)),tl(e,o,t),c(o)}s._last_mouse=l}else if(p===on){const l=n[1],a=n[2],i={x:l,y:a};if(null===s._last_mouse_down)No(e,t,{x:l,y:a,ts:o}),u();else{const n=jo(e,t);if(n>=0){No(e,t,{x:l,y:a,ts:o}),u();const r=nl(e,n);let d=vo.pointInBounds(i,Go(e))&&vo.pointInBounds(s._last_mouse_down,Go(e));for(const t of r){const n=Lo(e,t);if(vo.pointInBounds(i,n)){d=!0;break}}if(d){const t=l-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Xo(e,r,{x:t,y:n}),c(r)}}else No(e,t,{ts:o}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===nn){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=jo(e,t);if(g>=0){const n=nl(e,g);tl(e,n,0),c(n);const s=$o(e,g),i=Ro(e,g);let h=!1;if(Mo(e)===Ge.REAL){for(const t of n)if(Uo(e,t)){h=!0;break}}else h=!0;if(h&&vo.pointDistance(i,s){const l=xo[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=Bo(e,t),l=Bo(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=$o(e,t),s=vo.pointAdd($o(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(vo.pointDistance(a,s){const o=xo[e].puzzle.tiles,l=Bo(e,t),a=Bo(e,n);let s;const i=[];l&&i.push(l),a&&i.push(a),l?s=l:a?s=a:(_o(e,{maxGroup:Ko(e)+1}),r(),s=Ko(e));if(Vo(e,t,{group:s}),d(t),Vo(e,n,{group:s}),d(n),i.length>0)for(const r of o){const t=ae.decodePiece(r);i.includes(t.group)&&(Vo(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),l=nl(e,t),((e,t)=>-1===Jo(e,t))(e,n))el(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=Fo(e,o);t>n&&(n=t)}return n})(e,l);Qo(e,l,t)}return c(l),!0}return!1};let a=!1;for(const t of nl(e,g)){const o=Yo(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&&Io(e)===Be.ANY){const n=ol(e,t)+1;No(e,t,{d:p,ts:o,points:n}),u()}else No(e,t,{d:p,ts:o}),u();a&&Mo(e)===Ge.REAL&&Do(e)===To(e)&&(_o(e,{finished:o}),r()),a&&l&&l(t)}}else No(e,t,{d:p,ts:o}),u();s._last_mouse=i}else if(p===ln){const l=n[1],a=n[2];No(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else if(p===an){const l=n[1],a=n[2];No(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else No(e,t,{ts:o}),u();return function(e,t,n){xo[e].evtInfos[t]=n}(e,t,s),i}};let il=-10,rl=20,dl=2,cl=15;class ul{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=il+Math.random()*rl,this.vy=-1*(dl+Math.random()*cl),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;dl=t/2,cl=t-dl;const n=1/4*this.canvas.width/(t/2);il=-n,rl=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new ul(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new ul(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{localStorage.setItem(e,t)},Cl=e=>localStorage.getItem(e);var xl=(e,t)=>{bl(e,`${t}`)},kl=(e,t)=>{const n=Cl(e);if(null===n)return t;const o=parseInt(n,10);return isNaN(o)?t:o},Pl=(e,t)=>{bl(e,t?"1":"0")},Al=(e,t)=>{const n=Cl(e);return null===n?t:"1"===n},Sl=(e,t)=>{bl(e,t)},zl=(e,t)=>{const n=Cl(e);return null===n?t:n};const Tl={"./grab.png":lo,"./grab_mask.png":ao,"./hand.png":so,"./hand_mask.png":io},Il={"./click.mp3":oo},Ml="replay";let El=!0,Dl=!0;let Nl=!0;async function _l(e,t,n,o,l,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=Il["./click.mp3"].default,i=new Audio(s),r=await co.loadImageToBitmap(Tl["./grab.png"].default),d=await co.loadImageToBitmap(Tl["./hand.png"].default),c=await co.loadImageToBitmap(Tl["./grab_mask.png"].default),u=await co.loadImageToBitmap(Tl["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?c:u;y[t]=await createImageBitmap(co.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,Nl=!0})),t}(l,co.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};Nn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Nn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===o){const o=await Nn.connect(n,e,t),l=ae.decodeGame(o);sl.setGame(l.id,l),C=()=>L()}else{if(o!==Ml)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);sl.setGame(n.id,n),w.lastRealTs=L(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Nl=!0};await x();const k=sl.getPieceDrawOffset(e),P=sl.getPieceDrawSize(e),A=sl.getPuzzleWidth(e),S=sl.getPuzzleHeight(e),z=sl.getTableWidth(e),T=sl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},M={w:A,h:S},E={w:P,h:P},D=await Co.loadPuzzleBitmaps(sl.getPuzzle(e)),N=new gl(v,sl.getRng(e));N.init();const _=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const V=function(){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=(e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0},s=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>a(l(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),O=()=>{V.reset(),V.move(-(z-v.width)/2,-(T-v.height)/2);const e=V.worldDimToViewport(M),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([tn,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([nn,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([on,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?ln:an;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([cn]),o===Ml&&("KeyI"===e.code&&v([gn]),"KeyO"===e.code&&v([hn]),"KeyP"===e.code&&v([pn])),"KeyF"===e.code&&v([fn]),"KeyG"===e.code&&v([vn]),"KeyM"===e.code&&v([un]),"KeyN"===e.code&&v([mn]),"KeyC"===e.code&&v([yn]))}));const v=e=>{l.push(e)};return{addEvent:v,consumeAll:()=>{if(0===l.length)return[];const e=l.slice();return l=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const o=(p?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});v([en,l.w,l.h]),f&&(f[0]-=l.w,f[1]-=l.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([ln,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([an,...e])}},setHotkeys:e=>{a=e}}}(v,window,V,o),U=sl.getImageUrl(e),R=()=>{const t=sl.getStartTs(e),n=sl.getFinishTs(e),o=C();a.setFinished(!!n),a.setDuration((n||o)-t)};R(),a.setPiecesDone(sl.getFinishedPiecesCount(e)),a.setPiecesTotal(sl.getPieceCount(e));const G=C();a.setActivePlayers(sl.getActivePlayers(e,G)),a.setIdlePlayers(sl.getIdlePlayers(e,G));const F=!!sl.getFinishTs(e);let j=F;const W=()=>j&&!F,H=()=>kl(hl,100),K=()=>Al(ml,!1),q=()=>Al(wl,!0),Y=()=>{const e=H();i.volume=e/100,i.play()},Q=()=>o===Ml?zl(yl,"#222222"):sl.getPlayerBgColor(e,t)||zl(yl,"#222222"),Z=()=>o===Ml?zl(fl,"#ffffff"):sl.getPlayerColor(e,t)||zl(fl,"#ffffff");let X="",J="",ee=!1;const te=e=>{ee=e;const[t,n]=e?[X,"grab"]:[J,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},ne=e=>{X=co.colorizedCanvas(r,c,e).toDataURL(),J=co.colorizedCanvas(d,u,e).toDataURL(),te(ee)};ne(Z());const oe=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},le=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,oe())},ie=()=>{w.paused=!w.paused,oe()},re=[];let de;let ce;if("play"===o?re.push(setInterval((()=>{R()}),1e3)):o===Ml&&oe(),"play"===o)Nn.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case Cn:{const n=ae.decodePlayer(a);n.id!==t&&(sl.setPlayer(e,n.id,n),Nl=!0)}break;case bn:{const t=ae.decodePiece(a);sl.setPiece(e,t.idx,t),Nl=!0}break;case wn:sl.setPuzzleData(e,a),Nl=!0}j=!!sl.getFinishTs(e)}));else if(o===Ml){const t=(t,n)=>{const o=t;if(o[0]===Zt){const t=o[1];return sl.addPlayer(e,t,n),!0}if(o[0]===Xt){const t=sl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return sl.addPlayer(e,t,n),!0}if(o[0]===Jt){const t=sl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const l=o[2];return sl.handleInput(e,t,l,n),!0}return!1};let n=w.lastGameTs;const o=async()=>{w.logPointer+1>=w.log.length&&await b(e);const l=L();if(w.paused)return w.lastRealTs=l,void(de=setTimeout(o,50));const a=(l-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const o=w.log[w.logPointer],l=n+o[o.length-1],a=w.log[e],i=a[a.length-1],r=l+i;if(r>s){s+500*${let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=o*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,l(i);a(c/o),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{B.createKeyEvents();for(const n of B.consumeAll())if("play"===o){const o=n[0];if(o===en){const e=n[1],t=n[2],o=V.worldDimToViewport({w:e,h:t});Nl=!0,V.move(o.w,o.h)}else if(o===on){if(ue&&!sl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Nl=!0,V.move(o,l),ue=t}}else if(o===rn)ne(n[1]);else if(o===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(o===nn)ue=null,te(!1);else if(o===ln){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("in",V.worldToViewport(e))}else if(o===an){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("out",V.worldToViewport(e))}else o===cn?a.togglePreview():o===un?a.toggleSoundsEnabled():o===mn?a.togglePlayerNames():o===yn?O():o===fn?(El=!El,Nl=!0):o===vn&&(Dl=!Dl,Nl=!0);const l=C();sl.handleInput(e,t,n,l,(e=>{K()&&Y()})).length>0&&(Nl=!0),Nn.sendClientEvent(n)}else if(o===Ml){const e=n[0];if(e===pn)ie();else if(e===hn)se();else if(e===gn)le();else if(e===en){const e=n[1],t=n[2];Nl=!0,V.move(e,t)}else if(e===on){if(ue){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Nl=!0,V.move(o,l),ue=t}}else if(e===rn)ne(n[1]);else if(e===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(e===nn)ue=null,te(!1);else if(e===ln){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("in",V.worldToViewport(e))}else if(e===an){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("out",V.worldToViewport(e))}else e===cn?a.togglePreview():e===un?a.toggleSoundsEnabled():e===mn?a.togglePlayerNames():e===yn?O():e===fn?(El=!El,Nl=!0):e===vn&&(Dl=!Dl,Nl=!0)}j=!!sl.getFinishTs(e),W()&&(N.update(),Nl=!0)},render:async()=>{if(!Nl)return;const n=C();let l,s,i;window.DEBUG&&ho(0),_.fillStyle=Q(),_.fillRect(0,0,v.width,v.height),window.DEBUG&&mo("clear done"),l=V.worldToViewportRaw(I),s=V.worldDimToViewportRaw(M),_.fillStyle="rgba(255, 255, 255, .3)",_.fillRect(l.x,l.y,s.w,s.h),window.DEBUG&&mo("board done");const r=sl.getPiecesSortedByZIndex(e);window.DEBUG&&mo("get tiles done"),s=V.worldDimToViewportRaw(E);for(const e of r)(-1===e.owner?El:Dl)&&(i=D[e.idx],l=V.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),_.drawImage(i,0,0,i.width,i.height,l.x,l.y,s.w,s.h));window.DEBUG&&mo("tiles done");const d=[];for(const a of sl.getActivePlayers(e,n))c=a,(o===Ml||c.id!==t)&&(i=await f(a),l=V.worldToViewport(a),_.drawImage(i,l.x-g,l.y-m),q()&&d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var c;_.fillStyle="white",_.textAlign="center";for(const[e,t,o]of d)_.fillText(e,t,o);window.DEBUG&&mo("players done"),a.setActivePlayers(sl.getActivePlayers(e,n)),a.setIdlePlayers(sl.getIdlePlayers(e,n)),a.setPiecesDone(sl.getFinishedPiecesCount(e)),window.DEBUG&&mo("HUD done"),W()&&N.render(),Nl=!1}}),{setHotkeys:e=>{B.setHotkeys(e)},onBgChange:e=>{Sl(yl,e),B.addEvent([sn,e])},onColorChange:e=>{Sl(fl,e),B.addEvent([rn,e])},onNameChange:e=>{Sl(vl,e),B.addEvent([dn,e])},onSoundsEnabledChange:e=>{Pl(ml,e)},onSoundsVolumeChange:e=>{xl(hl,e),Y()},onShowPlayerNamesChange:e=>{Pl(wl,e)},replayOnSpeedUp:le,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:U,player:{background:Q(),color:Z(),name:o===Ml?zl(vl,"anon"):sl.getPlayerName(e,t)||zl(vl,"anon"),soundsEnabled:K(),soundsVolume:H(),showPlayerNames:q()},game:sl.get(e),disconnect:Nn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var Vl=e({name:"game",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,ConnectionOverlay:_n,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _l(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const Ol={id:"game"},Bl={key:1,class:"overlay"},Ul=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Rl={class:"menu"},$l={class:"tabs"},Gl=i("🧩 Puzzles");Vl.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Ol,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Bl,[Ul])):l("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Rl,[n("div",$l,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Gl])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Ll=e({name:"replay",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _l(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,Ml,this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Fl={id:"replay"},jl={key:1,class:"overlay"},Wl=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Hl={class:"menu"},Kl={class:"tabs"},ql=i("🧩 Puzzles");Ll.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Fl,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",jl,[Wl])):l("",!0),n(v,{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:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Hl,[n("div",Kl,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[ql])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=function(){let e=zl("ID","");return e||(e=ae.uniqId(),Sl("ID",e)),e}(),t=function(){let e=zl("SECRET","");return e||(e=ae.uniqId(),Sl("SECRET",e)),e}();O(e),B(t);const n=await _("/api/me",{}),o=await n.json(),l=await _("/api/conf",{}),a=await l.json(),s=k({history:P(),routes:[{name:"index",path:"/",component:Z},{name:"new-game",path:"/new-game",component:pt},{name:"game",path:"/g/:id",component:Vl},{name:"replay",path:"/replay/:id",component:Ll}]});s.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const i=A(S);i.config.globalProperties.$me=o,i.config.globalProperties.$config=a,i.config.globalProperties.$clientId=e,i.use(s),i.mount("#app")})(); diff --git a/build/public/index.html b/build/public/index.html index 51d4f80..0974d69 100644 --- a/build/public/index.html +++ b/build/public/index.html @@ -4,7 +4,7 @@ 🧩 jigsaw.hyottoko.club - + From 126384e5bda5cffb8042a0b269b6542a4c145f4e Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 11 Jul 2021 22:56:52 +0200 Subject: [PATCH 12/17] upper case first letter of title --- src/frontend/components/InfoOverlay.vue | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/frontend/components/InfoOverlay.vue b/src/frontend/components/InfoOverlay.vue index 1bf6220..b6c1835 100644 --- a/src/frontend/components/InfoOverlay.vue +++ b/src/frontend/components/InfoOverlay.vue @@ -48,8 +48,8 @@ export default defineComponent({ }, shapeMode () { switch (this.game.shapeMode) { - case ShapeMode.FLAT: return ['Flat', 'all pieces flat on all sides'] - case ShapeMode.ANY: return ['Any', 'flat pieces can occur anywhere'] + case ShapeMode.FLAT: return ['Flat', 'All pieces flat on all sides'] + case ShapeMode.ANY: return ['Any', 'Flat pieces can occur anywhere'] case ShapeMode.NORMAL: default: return ['Normal', ''] @@ -57,10 +57,10 @@ export default defineComponent({ }, snapMode () { switch (this.game.snapMode) { - case SnapMode.REAL: return ['Real', 'pieces snap only to corners, already snapped pieces and to each other'] + case SnapMode.REAL: return ['Real', 'Pieces snap only to corners, already snapped pieces and to each other'] case SnapMode.NORMAL: default: - return ['Normal', 'pieces snap to final destination and to each other'] + return ['Normal', 'Pieces snap to final destination and to each other'] } }, }, From 4e528cc83d3ffab3c6685204273e608d39a7f814 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Mon, 12 Jul 2021 01:28:14 +0200 Subject: [PATCH 13/17] store games in db --- build/public/assets/index.63ff8630.js | 1 + build/public/assets/index.97691b3e.js | 1 - build/public/index.html | 2 +- build/server/main.js | 214 ++++++++++++++++++-------- scripts/fix_games_image_info.ts | 6 +- scripts/fix_tiles.ts | 9 +- scripts/import_games.ts | 27 ++++ src/common/Types.ts | 2 + src/common/Util.ts | 2 + src/dbpatches/04_games.sqlite | 11 ++ src/server/Game.ts | 13 +- src/server/GameLog.ts | 1 + src/server/GameStorage.ts | 143 +++++++++++++---- src/server/main.ts | 72 +++++---- 14 files changed, 371 insertions(+), 133 deletions(-) create mode 100644 build/public/assets/index.63ff8630.js delete mode 100644 build/public/assets/index.97691b3e.js create mode 100644 scripts/import_games.ts create mode 100644 src/dbpatches/04_games.sqlite diff --git a/build/public/assets/index.63ff8630.js b/build/public/assets/index.63ff8630.js new file mode 100644 index 0000000..bb8b554 --- /dev/null +++ b/build/public/assets/index.63ff8630.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 s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),E=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:o((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:o((()=>[E])),_:1})])])):l("",!0),n(g)])};let M="",D="";const N=async(e,t,n)=>new Promise(((o,l)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.setRequestHeader("Client-Id",M),a.setRequestHeader("Client-Secret",D),a.addEventListener("load",(function(e){o({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){l(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body||null)}));var _=(e,t)=>N("get",e,t),V=(e,t)=>N("post",e,t),O=e=>{M=e},B=e=>{D=e};const U=864e5,R=e=>{const t=Math.floor(e/U);e%=U;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 $=1,G=1e3,L=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},F=(e,t)=>R(t-e),j=R,W=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||L();return`${n} ${F(o,l)}`}}});const H={class:"game-info-text"},K=n("br",null,null,-1),q=n("br",null,null,-1),Y=n("br",null,null,-1),Q=i(" ↪️ Watch replay ");W.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:o((()=>[n("span",H,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),K,i(" 👥 "+r(e.game.players),1),q,i(" "+r(e.time(e.game.started,e.game.finished)),1),Y])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:o((()=>[Q])),_:1},8,["to"])):l("",!0)],4)};var Z=e({components:{GameTeaser:W},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await _("/api/index-data",{}),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const X=n("h1",null,"Running games",-1),J=n("h1",null,"Finished games",-1);Z.render=function(e,o,l,i,r,u){const p=a("game-teaser");return s(),t("div",null,[X,(s(!0),t(d,null,c(e.gamesRunning,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128)),J,(s(!0),t(d,null,c(e.gamesFinished,((e,o)=>(s(),t("div",{class:"game-teaser-wrap",key:o},[n(p,{game:e},null,8,["game"])])))),128))])};var ee=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}},canEdit(){return!!this.$me.id&&this.$me.id===this.image.uploaderUserId}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});ee.render=function(e,n,o,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:n[2]||(n[2]=(...t)=>e.onClick&&e.onClick(...t))},[e.canEdit?(s(),t("div",{key:0,class:"btn edit",onClick:n[1]||(n[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")):l("",!0)],4)};var te=e({name:"image-library",components:{ImageTeaser:ee},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,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,o)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:o},null,8,["image","onClick","onEditClick"])))),128))])};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"),s=oe(o.getSeconds(),"00");console[t](`${l}:${a}:${s}`,...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,e.shapeMode,e.snapMode,e.creatorUserId]},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],creatorUserId:e[9]}},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,i){return s(),t("div",{style:i.style,title:o.title},null,12,["title"])};var ie=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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-a4fa5e7e");const de={key:0,class:"autocomplete"};f();const ce=re(((e,o,a,i,u,m)=>(s(),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?(s(),t("div",de,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,o)=>(s(),t("li",{key:o,class:{active:o===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):l("",!0),(s(!0),t(d,null,c(e.values,((n,o)=>(s(),t("span",{key:o,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ie.render=ce,ie.__scopeId="data-v-a4fa5e7e";const ue=le("NewImageDialog.vue");var pe=e({name:"new-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const 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=n("div",{class:"drop-target"},null,-1),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),Ce=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},ke=i("🖼️ Post to gallery"),Pe=i("🧩 Post to gallery "),Ae=n("br",null,null,-1),Se=i(" + set up game");pe.render=function(e,o,l,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),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))},[ge,e.previewUrl?(s(),t("div",he,[n("span",{class:"remove btn",onClick:o[1]||(o[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),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,[Ce,n("td",null,[n(f,{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))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ke],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:o[9]||(o[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[Pe,Ae,Se],64))],8,["disabled"])])])])};var ze=e({name:"edit-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},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 Te={class:"area-image"},Ie={class:"has-image"},Ee={class:"area-settings"},Me=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),Ne=n("td",null,[n("label",null,"Tags")],-1),_e={class:"area-buttons"};var Ve,Oe,Be,Ue,Re,$e,Ge,Le;ze.render=function(e,o,l,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),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",Te,[n("div",Ie,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Ee,[n("table",null,[n("tr",null,[Me,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,[Ne,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")])])])},(Oe=Ve||(Ve={}))[Oe.Flat=0]="Flat",Oe[Oe.Out=1]="Out",Oe[Oe.In=-1]="In",(Ue=Be||(Be={}))[Ue.FINAL=0]="FINAL",Ue[Ue.ANY=1]="ANY",($e=Re||(Re={}))[$e.NORMAL=0]="NORMAL",$e[$e.ANY=1]="ANY",$e[$e.FLAT=2]="FLAT",(Le=Ge||(Ge={}))[Le.NORMAL=0]="NORMAL",Le[Le.REAL=1]="REAL";var Fe=e({name:"new-game-dialog",components:{ResponsiveImage:se},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Be.ANY,shapeMode:Re.NORMAL,snapMode:Ge.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 je={class:"area-image"},We={class:"has-image"},He={key:0,class:"image-title"},Ke={key:0,class:"image-title-title"},qe={key:1,class:"image-title-dim"},Ye={class:"area-settings"},Qe=n("td",null,[n("label",null,"Pieces")],-1),Ze=n("td",null,[n("label",null,"Scoring: ")],-1),Xe=i(" Any (Score when pieces are connected to each other or on final location)"),Je=n("br",null,null,-1),et=i(" Final (Score when pieces are put to their final location)"),tt=n("td",null,[n("label",null,"Shapes: ")],-1),nt=i(" Normal"),ot=n("br",null,null,-1),lt=i(" Any (flat pieces can occur anywhere)"),at=n("br",null,null,-1),st=i(" Flat (all pieces flat on all sides)"),it=n("td",null,[n("label",null,"Snapping: ")],-1),rt=i(" Normal (pieces snap to final destination and to each other)"),dt=n("br",null,null,-1),ct=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ut={class:"area-buttons"};Fe.render=function(e,o,i,d,c,h){const m=a("responsive-image");return s(),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",je,[n("div",We,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",He,[e.image.title?(s(),t("span",Ke,'"'+r(e.image.title)+'"',1)):l("",!0),e.image.width||e.image.height?(s(),t("span",qe,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):l("",!0)])):l("",!0)]),n("div",Ye,[n("table",null,[n("tr",null,[Qe,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,[Ze,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]]),Xe]),Je,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]]),et])])]),n("tr",null,[tt,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]]),nt]),ot,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]]),lt]),at,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]]),st])])]),n("tr",null,[it,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]]),rt]),dt,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]]),ct])])])])]),n("div",ut,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:o[9]||(o[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var pt=e({components:{ImageLibrary:te,NewImageDialog:pe,EditImageDialog:ze,NewGameDialog:Fe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await _(`/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){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await V("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await V("/api/save-image",{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){const t=await this.saveImage(e);t.ok?(this.dialog="",await this.loadImages()):alert(t.error)},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await V("/api/newgame",{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 gt={class:"upload-image-teaser"},ht=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),mt={key:0},yt=i(" Tags: "),ft=i(" Sort by: "),vt=n("option",{value:"date_desc"},"Newest first",-1),wt=n("option",{value:"date_asc"},"Oldest first",-1),bt=n("option",{value:"alpha_asc"},"A-Z",-1),Ct=n("option",{value:"alpha_desc"},"Z-A",-1);pt.render=function(e,o,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",gt,[n("div",{class:"btn btn-big",onClick:o[1]||(o[1]=t=>e.dialog="new-image")},"Upload your image"),ht]),n("div",null,[e.tags.length>0?(s(),t("label",mt,[yt,(s(!0),t(d,null,c(e.relevantTags,((n,o)=>(s(),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,[ft,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))},[vt,wt,bt,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?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:o[4]||(o[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):l("",!0),"edit-image"===e.dialog?(s(),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?(s(),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 xt=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 kt={class:"scores"},Pt=n("div",null,"Scores",-1),At=n("td",null,"⚡",-1),St=n("td",null,"💤",-1);xt.render=function(e,o,l,a,i,u){return s(),t("div",kt,[Pt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[At,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,o)=>(s(),t("tr",{key:o,style:{color:e.color}},[St,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var zt=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 j(this.duration)}}});const Tt={class:"timer"};zt.render=function(e,o,l,a,i,d){return s(),t("div",Tt,[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 It=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const Et=m();y("data-v-4d56fc17");const Mt=n("td",null,[n("label",null,"Background: ")],-1),Dt=n("td",null,[n("label",null,"Color: ")],-1),Nt=n("td",null,[n("label",null,"Name: ")],-1),_t=n("td",null,[n("label",null,"Sounds: ")],-1),Vt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Ot={class:"sound-volume"},Bt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Ut=Et(((e,o,l,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:o[10]||(o[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:o[9]||(o[9]=u((()=>{}),["stop"]))},[n("tr",null,[Mt,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,[Dt,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,[Nt,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,[_t,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[4]||(o[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Vt,n("td",Ot,[n("span",{onClick:o[5]||(o[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:o[6]||(o[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:o[7]||(o[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Bt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":o[8]||(o[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));It.render=Ut,It.__scopeId="data-v-4d56fc17";var Rt=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const $t={class:"preview"};Rt.render=function(e,o,l,a,i,r){return s(),t("div",{class:"overlay",onClick:o[1]||(o[1]=t=>e.$emit("bgclick"))},[n("div",$t,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Gt=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Be.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Be.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case Re.FLAT:return["Flat","All pieces flat on all sides"];case Re.ANY:return["Any","Flat pieces can occur anywhere"];case Re.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case Ge.REAL:return["Real","Pieces snap only to corners, already snapped pieces and to each other"];case Ge.NORMAL:default:return["Normal","Pieces snap to final destination and to each other"]}}}});const Lt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ft=n("td",null,"Image Title: ",-1),jt=n("td",null,"Scoring: ",-1),Wt=n("td",null,"Shapes: ",-1),Ht=n("td",null,"Snapping: ",-1);Gt.render=function(e,o,l,a,i,d){return s(),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"]))},[Lt,n("tr",null,[Ft,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[jt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[Wt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Ht,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Kt=1,qt=4,Yt=2,Qt=3,Zt=2,Xt=4,Jt=3,en=9,tn=1,nn=2,on=3,ln=4,an=5,sn=6,rn=7,dn=8,cn=10,un=11,pn=12,gn=13,hn=14,mn=15,yn=16,fn=17,vn=18,wn=1,bn=2,Cn=3;const xn=le("Communication.js");let kn,Pn=[],An=e=>{Pn.push(e)},Sn=[],zn=e=>{Sn.push(e)};let Tn=0;const In=e=>{Tn!==e&&(Tn=e,zn(e))};function En(e){if(2===Tn)try{kn.send(JSON.stringify(e))}catch(t){xn.info("unable to send message.. maybe because ws is invalid?")}}let Mn,Dn;var Nn={connect:function(e,t,n){return Mn=0,Dn={},In(3),new Promise((o=>{kn=new WebSocket(e,n+"|"+t),kn.onopen=()=>{In(2),En([Qt])},kn.onmessage=e=>{const t=JSON.parse(e.data),l=t[0];if(l===qt){const e=t[1];o(e)}else{if(l!==Kt)throw`[ 2021-05-09 invalid connect msgType ${l} ]`;{const e=t[1],o=t[2];if(e===n&&Dn[o])return void delete Dn[o];An(t)}}},kn.onerror=()=>{throw In(1),"[ 2021-05-15 onerror ]"},kn.onclose=e=>{4e3===e.code||1001===e.code?In(4):In(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},o=await _(`/api/replay-data${ae.asQueryArgs(n)}`,{});return await o.json()},disconnect:function(){kn&&kn.close(4e3),Mn=0,Dn={}},sendClientEvent:function(e){Mn++,Dn[Mn]=e,En([Yt,Mn,Dn[Mn]])},onServerChange:function(e){An=e;for(const t of Pn)An(t);Pn=[]},onConnectionStateChange:function(e){zn=e;for(const t of Sn)zn(t);Sn=[]},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},_n=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 Vn={key:0,class:"overlay connection-lost"},On={key:0,class:"overlay-content"},Bn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),Un={key:1,class:"overlay-content"},Rn=n("div",null,"Connecting...",-1);_n.render=function(e,o,a,i,r,d){return e.show?(s(),t("div",Vn,[e.lostConnection?(s(),t("div",On,[Bn,n("span",{class:"btn",onClick:o[1]||(o[1]=t=>e.$emit("reconnect"))},"Reconnect")])):l("",!0),e.connecting?(s(),t("div",Un,[Rn])):l("",!0)])):l("",!0)};var $n=e({name:"help-overlay",emits:{bgclick:null}});const Gn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Ln=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Fn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),jn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Wn=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Hn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),Kn=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),qn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Yn=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Qn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),Zn=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 player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Jn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),eo=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),to=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),no=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);$n.render=function(e,o,l,a,i,r){return s(),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"]))},[Gn,Ln,Fn,jn,Wn,Hn,Kn,qn,Yn,Qn,Zn,Xn,Jn,eo,to,no])])};var oo=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),lo=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),ao=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),so=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),io=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function ro(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var co={createCanvas:ro,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=ro(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=ro(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 uo=le("Debug.js");let po=0,go=0;var ho=e=>{po=performance.now(),go=e},mo=e=>{const t=performance.now(),n=t-po;n>go&&uo.log(e+": "+n),po=t};function yo(e,t){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}function fo(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var vo={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:yo,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:fo,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 yo(fo(e),fo(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 wo=le("PuzzleGraphics.js");function bo(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 Co={loadPuzzleBitmaps:async function(e){const t=await co.loadImageToBitmap(e.info.imageUrl),n=await co.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){wo.log("start createPuzzleTileBitmaps");const o=n.tileSize,l=n.tileMarginWidth,a=n.tileDrawSize,s=o/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:l,y:l},r=vo.pointAdd(a,{x:o,y:0}),c=vo.pointAdd(r,{x:0,y:o}),u=vo.pointSub(c,{x:o,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let o=0;oae.decodePiece(xo[e].puzzle.tiles[t]),Bo=(e,t)=>Oo(e,t).group,Uo=(e,t)=>{const n=xo[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},Ro=(e,t)=>{const n=xo[e].puzzle.info,o={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},l=function(e,t){const n=xo[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 vo.pointAdd(o,l)},$o=(e,t)=>Oo(e,t).pos,Go=e=>{const t=ll(e),n=al(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}},Lo=(e,t)=>{const n=Ho(e),o=Oo(e,t);return{x:o.pos.x,y:o.pos.y,w:n,h:n}},Fo=(e,t)=>Oo(e,t).z,jo=(e,t)=>{for(const n of xo[e].puzzle.tiles){const e=ae.decodePiece(n);if(e.owner===t)return e.idx}return-1},Wo=e=>xo[e].puzzle.info.tileDrawSize,Ho=e=>xo[e].puzzle.info.tileSize,Ko=e=>xo[e].puzzle.data.maxGroup,qo=e=>xo[e].puzzle.data.maxZ;function Yo(e,t){const n=xo[e].puzzle.info,o=ae.coordByPieceIdx(n,t);return[o.y>0?t-n.tilesX:-1,o.x0?t-1:-1]}const Qo=(e,t,n)=>{for(const o of t)Vo(e,o,{z:n})},Zo=(e,t,n)=>{const o=$o(e,t);Vo(e,t,{pos:vo.pointAdd(o,n)})},Xo=(e,t,n)=>{const o=Wo(e),l=Go(e),a=n;for(const s of t){const t=Oo(e,s);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 s of t)Zo(e,s,a)},Jo=(e,t)=>Oo(e,t).owner,el=(e,t)=>{for(const n of t)Vo(e,n,{owner:-1,z:1})},tl=(e,t,n)=>{for(const o of t)Vo(e,o,{owner:n})};function nl(e,t){const n=xo[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 ol=(e,t)=>{const n=Po(e,t);return n?n.points:0},ll=e=>xo[e].puzzle.info.table.width,al=e=>xo[e].puzzle.info.table.height;var sl={setGame:function(e,t){xo[e]=t},exists:function(e){return!!xo[e]||!1},playerExists:So,getActivePlayers:function(e,t){const n=t-30*G;return zo(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*G;return zo(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){So(e,t)?No(e,t,{ts:n}):Ao(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:Do,getPieceCount:To,getImageUrl:function(e){var t;const n=(null==(t=xo[e].puzzle.info.image)?void 0:t.url)||xo[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return xo[e]||null},getAllGames:function(){return Object.values(xo).sort(((e,t)=>{const n=Mo(e.id);return n===Mo(t.id)?n?t.puzzle.data.finished-e.puzzle.data.finished:t.puzzle.data.started-e.puzzle.data.started:n?1:-1}))},getPlayerBgColor:(e,t)=>{const n=Po(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=Po(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=Po(e,t);return n?n.name:null},getPlayerIndexById:ko,getPlayerIdByIndex:function(e,t){return xo[e].players.length>t?ae.decodePlayer(xo[e].players[t]).id:null},changePlayer:No,setPlayer:Ao,setPiece:function(e,t,n){xo[e].puzzle.tiles[t]=ae.encodePiece(n)},setPuzzleData:function(e,t){xo[e].puzzle.data=t},getTableWidth:ll,getTableHeight:al,getPuzzle:e=>xo[e].puzzle,getRng:e=>xo[e].rng.obj,getPuzzleWidth:e=>xo[e].puzzle.info.width,getPuzzleHeight:e=>xo[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return xo[e].puzzle.tiles.map(ae.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=jo(e,t);return n<0?null:xo[e].puzzle.tiles[n]},getPieceDrawOffset:e=>xo[e].puzzle.info.tileDrawOffset,getPieceDrawSize:Wo,getFinalPiecePos:Ro,getStartTs:e=>xo[e].puzzle.data.started,getFinishTs:e=>xo[e].puzzle.data.finished,handleInput:function(e,t,n,o,l){const a=xo[e].puzzle,s=function(e,t){return t in xo[e].evtInfos?xo[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([wn,a.data])},d=t=>{i.push([bn,ae.encodePiece(Oo(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=Po(e,t);n&&i.push([Cn,ae.encodePlayer(n)])},p=n[0];if(p===sn){const l=n[1];No(e,t,{bgcolor:l,ts:o}),u()}else if(p===rn){const l=n[1];No(e,t,{color:l,ts:o}),u()}else if(p===dn){const l=`${n[1]}`.substr(0,16);No(e,t,{name:l,ts:o}),u()}else if(p===en){const l=n[1],a=n[2],s=Po(e,t);if(s){const n=s.x-l,i=s.y-a;No(e,t,{ts:o,x:n,y:i}),u()}}else if(p===tn){const l={x:n[1],y:n[2]};No(e,t,{d:1,ts:o}),u(),s._last_mouse_down=l;const a=((e,t)=>{const n=xo[e].puzzle.info,o=xo[e].puzzle.tiles;let l=-1,a=-1;for(let s=0;sl)&&(l=e.z,a=s)}return a})(e,l);if(a>=0){const n=qo(e)+1;_o(e,{maxZ:n}),r();const o=nl(e,a);Qo(e,o,qo(e)),tl(e,o,t),c(o)}s._last_mouse=l}else if(p===on){const l=n[1],a=n[2],i={x:l,y:a};if(null===s._last_mouse_down)No(e,t,{x:l,y:a,ts:o}),u();else{const n=jo(e,t);if(n>=0){No(e,t,{x:l,y:a,ts:o}),u();const r=nl(e,n);let d=vo.pointInBounds(i,Go(e))&&vo.pointInBounds(s._last_mouse_down,Go(e));for(const t of r){const n=Lo(e,t);if(vo.pointInBounds(i,n)){d=!0;break}}if(d){const t=l-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Xo(e,r,{x:t,y:n}),c(r)}}else No(e,t,{ts:o}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===nn){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=jo(e,t);if(g>=0){const n=nl(e,g);tl(e,n,0),c(n);const s=$o(e,g),i=Ro(e,g);let h=!1;if(Eo(e)===Ge.REAL){for(const t of n)if(Uo(e,t)){h=!0;break}}else h=!0;if(h&&vo.pointDistance(i,s){const l=xo[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const o=Bo(e,t),l=Bo(e,n);return!(!o||o!==l)})(e,t,n))return!1;const a=$o(e,t),s=vo.pointAdd($o(e,n),{x:o[0]*l.tileSize,y:o[1]*l.tileSize});if(vo.pointDistance(a,s){const o=xo[e].puzzle.tiles,l=Bo(e,t),a=Bo(e,n);let s;const i=[];l&&i.push(l),a&&i.push(a),l?s=l:a?s=a:(_o(e,{maxGroup:Ko(e)+1}),r(),s=Ko(e));if(Vo(e,t,{group:s}),d(t),Vo(e,n,{group:s}),d(n),i.length>0)for(const r of o){const t=ae.decodePiece(r);i.includes(t.group)&&(Vo(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),l=nl(e,t),((e,t)=>-1===Jo(e,t))(e,n))el(e,l);else{const t=((e,t)=>{let n=0;for(const o of t){const t=Fo(e,o);t>n&&(n=t)}return n})(e,l);Qo(e,l,t)}return c(l),!0}return!1};let a=!1;for(const t of nl(e,g)){const o=Yo(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&&Io(e)===Be.ANY){const n=ol(e,t)+1;No(e,t,{d:p,ts:o,points:n}),u()}else No(e,t,{d:p,ts:o}),u();a&&Eo(e)===Ge.REAL&&Do(e)===To(e)&&(_o(e,{finished:o}),r()),a&&l&&l(t)}}else No(e,t,{d:p,ts:o}),u();s._last_mouse=i}else if(p===ln){const l=n[1],a=n[2];No(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else if(p===an){const l=n[1],a=n[2];No(e,t,{x:l,y:a,ts:o}),u(),s._last_mouse={x:l,y:a}}else No(e,t,{ts:o}),u();return function(e,t,n){xo[e].evtInfos[t]=n}(e,t,s),i}};let il=-10,rl=20,dl=2,cl=15;class ul{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=il+Math.random()*rl,this.vy=-1*(dl+Math.random()*cl),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;dl=t/2,cl=t-dl;const n=1/4*this.canvas.width/(t/2);il=-n,rl=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new ul(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new ul(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{localStorage.setItem(e,t)},Cl=e=>localStorage.getItem(e);var xl=(e,t)=>{bl(e,`${t}`)},kl=(e,t)=>{const n=Cl(e);if(null===n)return t;const o=parseInt(n,10);return isNaN(o)?t:o},Pl=(e,t)=>{bl(e,t?"1":"0")},Al=(e,t)=>{const n=Cl(e);return null===n?t:"1"===n},Sl=(e,t)=>{bl(e,t)},zl=(e,t)=>{const n=Cl(e);return null===n?t:n};const Tl={"./grab.png":lo,"./grab_mask.png":ao,"./hand.png":so,"./hand_mask.png":io},Il={"./click.mp3":oo},El="replay";let Ml=!0,Dl=!0;let Nl=!0;async function _l(e,t,n,o,l,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=Il["./click.mp3"].default,i=new Audio(s),r=await co.loadImageToBitmap(Tl["./grab.png"].default),d=await co.loadImageToBitmap(Tl["./hand.png"].default),c=await co.loadImageToBitmap(Tl["./grab_mask.png"].default),u=await co.loadImageToBitmap(Tl["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const o=e.d?c:u;y[t]=await createImageBitmap(co.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,Nl=!0})),t}(l,co.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};Nn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Nn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===o){const o=await Nn.connect(n,e,t),l=ae.decodeGame(o);sl.setGame(l.id,l),C=()=>L()}else{if(o!==El)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);sl.setGame(n.id,n),w.lastRealTs=L(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}Nl=!0};await x();const k=sl.getPieceDrawOffset(e),P=sl.getPieceDrawSize(e),A=sl.getPuzzleWidth(e),S=sl.getPuzzleHeight(e),z=sl.getTableWidth(e),T=sl.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},E={w:A,h:S},M={w:P,h:P},D=await Co.loadPuzzleBitmaps(sl.getPuzzle(e)),N=new gl(v,sl.getRng(e));N.init();const _=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const V=function(){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=(e,t)=>{if(n==e)return!1;const l=1-n/e;return o(-t.x*l,-t.y*l),n=e,!0},s=o=>({x:o.x/n-e,y:o.y/n-t}),i=o=>({x:(o.x+e)*n,y:(o.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:o,canZoom:e=>n!=l(e),zoom:(e,t)=>a(l(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),O=()=>{V.reset(),V.move(-(z-v.width)/2,-(T-v.height)/2);const e=V.worldDimToViewport(E),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const o=n.viewportToWorld({x:e,y:t});return[o.x,o.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([tn,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([nn,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([on,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?ln:an;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([cn]),o===El&&("KeyI"===e.code&&v([gn]),"KeyO"===e.code&&v([hn]),"KeyP"===e.code&&v([pn])),"KeyF"===e.code&&v([fn]),"KeyG"===e.code&&v([vn]),"KeyM"===e.code&&v([un]),"KeyN"===e.code&&v([mn]),"KeyC"===e.code&&v([yn]))}));const v=e=>{l.push(e)};return{addEvent:v,consumeAll:()=>{if(0===l.length)return[];const e=l.slice();return l=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const o=(p?24:12)*Math.sqrt(n.getCurrentZoom()),l=n.viewportDimToWorld({w:e*o,h:t*o});v([en,l.w,l.h]),f&&(f[0]-=l.w,f[1]-=l.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([ln,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([an,...e])}},setHotkeys:e=>{a=e}}}(v,window,V,o),U=sl.getImageUrl(e),R=()=>{const t=sl.getStartTs(e),n=sl.getFinishTs(e),o=C();a.setFinished(!!n),a.setDuration((n||o)-t)};R(),a.setPiecesDone(sl.getFinishedPiecesCount(e)),a.setPiecesTotal(sl.getPieceCount(e));const G=C();a.setActivePlayers(sl.getActivePlayers(e,G)),a.setIdlePlayers(sl.getIdlePlayers(e,G));const F=!!sl.getFinishTs(e);let j=F;const W=()=>j&&!F,H=()=>kl(hl,100),K=()=>Al(ml,!1),q=()=>Al(wl,!0),Y=()=>{const e=H();i.volume=e/100,i.play()},Q=()=>o===El?zl(yl,"#222222"):sl.getPlayerBgColor(e,t)||zl(yl,"#222222"),Z=()=>o===El?zl(fl,"#ffffff"):sl.getPlayerColor(e,t)||zl(fl,"#ffffff");let X="",J="",ee=!1;const te=e=>{ee=e;const[t,n]=e?[X,"grab"]:[J,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},ne=e=>{X=co.colorizedCanvas(r,c,e).toDataURL(),J=co.colorizedCanvas(d,u,e).toDataURL(),te(ee)};ne(Z());const oe=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},le=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,oe())},ie=()=>{w.paused=!w.paused,oe()},re=[];let de;let ce;if("play"===o?re.push(setInterval((()=>{R()}),1e3)):o===El&&oe(),"play"===o)Nn.onServerChange((n=>{n[0],n[1],n[2];const o=n[3];for(const[l,a]of o)switch(l){case Cn:{const n=ae.decodePlayer(a);n.id!==t&&(sl.setPlayer(e,n.id,n),Nl=!0)}break;case bn:{const t=ae.decodePiece(a);sl.setPiece(e,t.idx,t),Nl=!0}break;case wn:sl.setPuzzleData(e,a),Nl=!0}j=!!sl.getFinishTs(e)}));else if(o===El){const t=(t,n)=>{const o=t;if(o[0]===Zt){const t=o[1];return sl.addPlayer(e,t,n),!0}if(o[0]===Xt){const t=sl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return sl.addPlayer(e,t,n),!0}if(o[0]===Jt){const t=sl.getPlayerIdByIndex(e,o[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const l=o[2];return sl.handleInput(e,t,l,n),!0}return!1};let n=w.lastGameTs;const o=async()=>{w.logPointer+1>=w.log.length&&await b(e);const l=L();if(w.paused)return w.lastRealTs=l,void(de=setTimeout(o,50));const a=(l-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const o=w.log[w.logPointer],l=n+o[o.length-1],a=w.log[e],i=a[a.length-1],r=l+i;if(r>s){s+500*${let t=!1;const n=e.fps||60,o=e.slow||1,l=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=o*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,l(i);a(c/o),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{B.createKeyEvents();for(const n of B.consumeAll())if("play"===o){const o=n[0];if(o===en){const e=n[1],t=n[2],o=V.worldDimToViewport({w:e,h:t});Nl=!0,V.move(o.w,o.h)}else if(o===on){if(ue&&!sl.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Nl=!0,V.move(o,l),ue=t}}else if(o===rn)ne(n[1]);else if(o===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(o===nn)ue=null,te(!1);else if(o===ln){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("in",V.worldToViewport(e))}else if(o===an){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("out",V.worldToViewport(e))}else o===cn?a.togglePreview():o===un?a.toggleSoundsEnabled():o===mn?a.togglePlayerNames():o===yn?O():o===fn?(Ml=!Ml,Nl=!0):o===vn&&(Dl=!Dl,Nl=!0);const l=C();sl.handleInput(e,t,n,l,(e=>{K()&&Y()})).length>0&&(Nl=!0),Nn.sendClientEvent(n)}else if(o===El){const e=n[0];if(e===pn)ie();else if(e===hn)se();else if(e===gn)le();else if(e===en){const e=n[1],t=n[2];Nl=!0,V.move(e,t)}else if(e===on){if(ue){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),o=Math.round(t.x-ue.x),l=Math.round(t.y-ue.y);Nl=!0,V.move(o,l),ue=t}}else if(e===rn)ne(n[1]);else if(e===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(e===nn)ue=null,te(!1);else if(e===ln){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("in",V.worldToViewport(e))}else if(e===an){const e={x:n[1],y:n[2]};Nl=!0,V.zoom("out",V.worldToViewport(e))}else e===cn?a.togglePreview():e===un?a.toggleSoundsEnabled():e===mn?a.togglePlayerNames():e===yn?O():e===fn?(Ml=!Ml,Nl=!0):e===vn&&(Dl=!Dl,Nl=!0)}j=!!sl.getFinishTs(e),W()&&(N.update(),Nl=!0)},render:async()=>{if(!Nl)return;const n=C();let l,s,i;window.DEBUG&&ho(0),_.fillStyle=Q(),_.fillRect(0,0,v.width,v.height),window.DEBUG&&mo("clear done"),l=V.worldToViewportRaw(I),s=V.worldDimToViewportRaw(E),_.fillStyle="rgba(255, 255, 255, .3)",_.fillRect(l.x,l.y,s.w,s.h),window.DEBUG&&mo("board done");const r=sl.getPiecesSortedByZIndex(e);window.DEBUG&&mo("get tiles done"),s=V.worldDimToViewportRaw(M);for(const e of r)(-1===e.owner?Ml:Dl)&&(i=D[e.idx],l=V.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),_.drawImage(i,0,0,i.width,i.height,l.x,l.y,s.w,s.h));window.DEBUG&&mo("tiles done");const d=[];for(const a of sl.getActivePlayers(e,n))c=a,(o===El||c.id!==t)&&(i=await f(a),l=V.worldToViewport(a),_.drawImage(i,l.x-g,l.y-m),q()&&d.push([`${a.name} (${a.points})`,l.x,l.y+h]));var c;_.fillStyle="white",_.textAlign="center";for(const[e,t,o]of d)_.fillText(e,t,o);window.DEBUG&&mo("players done"),a.setActivePlayers(sl.getActivePlayers(e,n)),a.setIdlePlayers(sl.getIdlePlayers(e,n)),a.setPiecesDone(sl.getFinishedPiecesCount(e)),window.DEBUG&&mo("HUD done"),W()&&N.render(),Nl=!1}}),{setHotkeys:e=>{B.setHotkeys(e)},onBgChange:e=>{Sl(yl,e),B.addEvent([sn,e])},onColorChange:e=>{Sl(fl,e),B.addEvent([rn,e])},onNameChange:e=>{Sl(vl,e),B.addEvent([dn,e])},onSoundsEnabledChange:e=>{Pl(ml,e)},onSoundsVolumeChange:e=>{xl(hl,e),Y()},onShowPlayerNamesChange:e=>{Pl(wl,e)},replayOnSpeedUp:le,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:U,player:{background:Q(),color:Z(),name:o===El?zl(vl,"anon"):sl.getPlayerName(e,t)||zl(vl,"anon"),soundsEnabled:K(),soundsVolume:H(),showPlayerNames:q()},game:sl.get(e),disconnect:Nn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var Vl=e({name:"game",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,ConnectionOverlay:_n,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _l(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const Ol={id:"game"},Bl={key:1,class:"overlay"},Ul=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Rl={class:"menu"},$l={class:"tabs"},Gl=i("🧩 Puzzles");Vl.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Ol,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Bl,[Ul])):l("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Rl,[n("div",$l,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[Gl])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Ll=e({name:"replay",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _l(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,El,this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Fl={id:"replay"},jl={key:1,class:"overlay"},Wl=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Hl={class:"menu"},Kl={class:"tabs"},ql=i("🧩 Puzzles");Ll.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Fl,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):l("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",jl,[Wl])):l("",!0),n(v,{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:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Hl,[n("div",Kl,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:o((()=>[ql])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=function(){let e=zl("ID","");return e||(e=ae.uniqId(),Sl("ID",e)),e}(),t=function(){let e=zl("SECRET","");return e||(e=ae.uniqId(),Sl("SECRET",e)),e}();O(e),B(t);const n=await _("/api/me",{}),o=await n.json(),l=await _("/api/conf",{}),a=await l.json(),s=k({history:P(),routes:[{name:"index",path:"/",component:Z},{name:"new-game",path:"/new-game",component:pt},{name:"game",path:"/g/:id",component:Vl},{name:"replay",path:"/replay/:id",component:Ll}]});s.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const i=A(S);i.config.globalProperties.$me=o,i.config.globalProperties.$config=a,i.config.globalProperties.$clientId=e,i.use(s),i.mount("#app")})(); diff --git a/build/public/assets/index.97691b3e.js b/build/public/assets/index.97691b3e.js deleted file mode 100644 index 11c7d04..0000000 --- a/build/public/assets/index.97691b3e.js +++ /dev/null @@ -1 +0,0 @@ -import{d as e,c as t,a as n,w as l,b as o,r as a,o as s,e as i,t as r,F as d,f as c,g as u,h as p,v as g,i as h,j as m,p as y,k as f,l as v,m as w,n as b,q as C,s as x,u as k,x as P,y as A}from"./vendor.684f7bc8.js";var S=e({name:"app",computed:{showNav(){return!["game","replay"].includes(String(this.$route.name))}}});const z={id:"app"},T={key:0,class:"nav"},I=i("Games overview"),E=i("New game");S.render=function(e,i,r,d,c,u){const p=a("router-link"),g=a("router-view");return s(),t("div",z,[e.showNav?(s(),t("ul",T,[n("li",null,[n(p,{class:"btn",to:{name:"index"}},{default:l((()=>[I])),_:1})]),n("li",null,[n(p,{class:"btn",to:{name:"new-game"}},{default:l((()=>[E])),_:1})])])):o("",!0),n(g)])};let M="",D="";const N=async(e,t,n)=>new Promise(((l,o)=>{const a=new window.XMLHttpRequest;a.open(e,t,!0),a.withCredentials=!0;for(const e in n.headers||{})a.setRequestHeader(e,n.headers[e]);a.setRequestHeader("Client-Id",M),a.setRequestHeader("Client-Secret",D),a.addEventListener("load",(function(e){l({status:this.status,text:this.responseText,json:async()=>JSON.parse(this.responseText)})})),a.addEventListener("error",(function(e){o(new Error("xhr error"))})),a.upload&&n.onUploadProgress&&a.upload.addEventListener("progress",(function(e){n.onUploadProgress&&n.onUploadProgress(e)})),a.send(n.body||null)}));var _=(e,t)=>N("get",e,t),V=(e,t)=>N("post",e,t),O=e=>{M=e},B=e=>{D=e};const U=864e5,R=e=>{const t=Math.floor(e/U);e%=U;const n=Math.floor(e/36e5);e%=36e5;const l=Math.floor(e/6e4);e%=6e4;return`${t}d ${n}h ${l}m ${Math.floor(e/1e3)}s`};var $=1,G=1e3,L=()=>{const e=new Date;return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())},F=(e,t)=>R(t-e),j=R,W=e({name:"game-teaser",props:{game:{type:Object,required:!0}},computed:{style(){return{"background-image":`url("${this.game.imageUrl.replace("uploads/","uploads/r/")+"-375x210.webp"}")`}}},methods:{time(e,t){const n=t?"🏁":"⏳",l=e,o=t||L();return`${n} ${F(l,o)}`}}});const H={class:"game-info-text"},K=n("br",null,null,-1),q=n("br",null,null,-1),Y=n("br",null,null,-1),Q=i(" ↪️ Watch replay ");W.render=function(e,d,c,u,p,g){const h=a("router-link");return s(),t("div",{class:"game-teaser",style:e.style},[n(h,{class:"game-info",to:{name:"game",params:{id:e.game.id}}},{default:l((()=>[n("span",H,[i(" 🧩 "+r(e.game.tilesFinished)+"/"+r(e.game.tilesTotal),1),K,i(" 👥 "+r(e.game.players),1),q,i(" "+r(e.time(e.game.started,e.game.finished)),1),Y])])),_:1},8,["to"]),e.game.hasReplay?(s(),t(h,{key:0,class:"game-replay",to:{name:"replay",params:{id:e.game.id}}},{default:l((()=>[Q])),_:1},8,["to"])):o("",!0)],4)};var Z=e({components:{GameTeaser:W},data:()=>({gamesRunning:[],gamesFinished:[]}),async created(){const e=await _("/api/index-data",{}),t=await e.json();this.gamesRunning=t.gamesRunning,this.gamesFinished=t.gamesFinished}});const X=n("h1",null,"Running games",-1),J=n("h1",null,"Finished games",-1);Z.render=function(e,l,o,i,r,u){const p=a("game-teaser");return s(),t("div",null,[X,(s(!0),t(d,null,c(e.gamesRunning,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128)),J,(s(!0),t(d,null,c(e.gamesFinished,((e,l)=>(s(),t("div",{class:"game-teaser-wrap",key:l},[n(p,{game:e},null,8,["game"])])))),128))])};var ee=e({name:"image-teaser",props:{image:{type:Object,required:!0}},computed:{style(){return{backgroundImage:`url("${this.image.url.replace("uploads/","uploads/r/")+"-150x100.webp"}")`}},canEdit(){return!!this.$me.id&&this.$me.id===this.image.uploaderUserId}},emits:{click:null,editClick:null},methods:{onClick(){this.$emit("click")},onEditClick(){this.$emit("editClick")}}});ee.render=function(e,n,l,a,i,r){return s(),t("div",{class:"imageteaser",style:e.style,onClick:n[2]||(n[2]=(...t)=>e.onClick&&e.onClick(...t))},[e.canEdit?(s(),t("div",{key:0,class:"btn edit",onClick:n[1]||(n[1]=u(((...t)=>e.onEditClick&&e.onEditClick(...t)),["stop"]))},"✏️")):o("",!0)],4)};var te=e({name:"image-library",components:{ImageTeaser:ee},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,l,o,i,r){const u=a("image-teaser");return s(),t("div",null,[(s(!0),t(d,null,c(e.images,((n,l)=>(s(),t(u,{image:n,onClick:t=>e.imageClicked(n),onEditClick:t=>e.imageEditClicked(n),key:l},null,8,["image","onClick","onEditClick"])))),128))])};class 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),l=t[n];t[n]=t[e],t[e]=l}return t}static serialize(e){return{rand_high:e.rand_high,rand_low:e.rand_low}}static unserialize(e){const t=new ne(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},oe=(...e)=>{const t=t=>(...n)=>{const l=new Date,o=le(l.getHours(),"00"),a=le(l.getMinutes(),"00"),s=le(l.getSeconds(),"00");console[t](`${o}:${a}:${s}`,...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,e.shapeMode,e.snapMode]},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 l=[n,e[n]].map(encodeURIComponent);t.push(l.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,l,o,a,i){return s(),t("div",{style:i.style,title:l.title},null,12,["title"])};var ie=e({name:"tags-input",props:{modelValue:{type:Array,required:!0},autocompleteTags:{type:Function}},emits:{"update:modelValue":null},data:()=>({input:"",values:[],autocomplete:{idx:-1,values:[]}}),created(){this.values=this.modelValue},methods:{onKeyUp(e){return"ArrowDown"===e.code&&this.autocomplete.values.length>0?(this.autocomplete.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-a4fa5e7e");const de={key:0,class:"autocomplete"};f();const ce=re(((e,l,a,i,u,m)=>(s(),t("div",null,[p(n("input",{ref:"input",class:"input",type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.input=t),placeholder:"Plants, People",onChange:l[2]||(l[2]=(...t)=>e.onChange&&e.onChange(...t)),onKeydown:l[3]||(l[3]=h(((...t)=>e.add&&e.add(...t)),["enter"])),onKeyup:l[4]||(l[4]=(...t)=>e.onKeyUp&&e.onKeyUp(...t))},null,544),[[g,e.input]]),e.autocomplete.values?(s(),t("div",de,[n("ul",null,[(s(!0),t(d,null,c(e.autocomplete.values,((n,l)=>(s(),t("li",{key:l,class:{active:l===e.autocomplete.idx},onClick:t=>e.addVal(n)},r(n),11,["onClick"])))),128))])])):o("",!0),(s(!0),t(d,null,c(e.values,((n,l)=>(s(),t("span",{key:l,class:"bit",onClick:t=>e.rm(n)},r(n)+" ✖",9,["onClick"])))),128))]))));ie.render=ce,ie.__scopeId="data-v-a4fa5e7e";const ue=oe("NewImageDialog.vue");var pe=e({name:"new-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},props:{autocompleteTags:{type:Function},uploadProgress:{type:Number},uploading:{type:String}},emits:{bgclick:null,setupGameClick:null,postToGalleryClick:null},data:()=>({previewUrl:"",file:null,title:"",tags:[],droppable:!1}),computed:{uploadProgressPercent(){return this.uploadProgress?Math.round(100*this.uploadProgress):0},canPostToGallery(){return!this.uploading&&!(!this.previewUrl||!this.file)},canSetupGameClick(){return!this.uploading&&!(!this.previewUrl||!this.file)}},methods:{imageFromDragEvt(e){var t;const n=null==(t=e.dataTransfer)?void 0:t.items;if(!n||0===n.length)return null;const l=n[0];return l.type.startsWith("image/")?l:null},onFileSelect(e){const t=e.target;if(!t.files)return;const n=t.files[0];n&&this.preview(n)},preview(e){const t=new FileReader;t.readAsDataURL(e),t.onload=t=>{this.previewUrl=t.target.result,this.file=e}},postToGallery(){this.$emit("postToGalleryClick",{file:this.file,title:this.title,tags:this.tags})},setupGameClick(){this.$emit("setupGameClick",{file:this.file,title:this.title,tags:this.tags})},onDrop(e){this.droppable=!1;const t=this.imageFromDragEvt(e);if(!t)return!1;const n=t.getAsFile();return!!n&&(this.file=n,this.preview(n),e.preventDefault(),!1)},onDragover(e){return!!this.imageFromDragEvt(e)&&(this.droppable=!0,e.preventDefault(),!1)},onDragleave(){ue.info("onDragleave"),this.droppable=!1}}});const ge=n("div",{class:"drop-target"},null,-1),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),Ce=n("td",null,[n("label",null,"Tags")],-1),xe={class:"area-buttons"},ke=i("🖼️ Post to gallery"),Pe=i("🧩 Post to gallery "),Ae=n("br",null,null,-1),Se=i(" + set up game");pe.render=function(e,l,o,c,h,m){const y=a("responsive-image"),f=a("tags-input");return s(),t("div",{class:"overlay new-image-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",{class:["area-image",{"has-image":!!e.previewUrl,"no-image":!e.previewUrl,droppable:e.droppable}],onDrop:l[3]||(l[3]=(...t)=>e.onDrop&&e.onDrop(...t)),onDragover:l[4]||(l[4]=(...t)=>e.onDragover&&e.onDragover(...t)),onDragleave:l[5]||(l[5]=(...t)=>e.onDragleave&&e.onDragleave(...t))},[ge,e.previewUrl?(s(),t("div",he,[n("span",{class:"remove btn",onClick:l[1]||(l[1]=t=>e.previewUrl="")},"X"),n(y,{src:e.previewUrl},null,8,["src"])])):(s(),t("div",me,[n("label",ye,[n("input",{type:"file",style:{display:"none"},onChange:l[2]||(l[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":l[6]||(l[6]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),be,n("tr",null,[Ce,n("td",null,[n(f,{modelValue:e.tags,"onUpdate:modelValue":l[7]||(l[7]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",xe,[n("button",{class:"btn",disabled:!e.canPostToGallery,onClick:l[8]||(l[8]=(...t)=>e.postToGallery&&e.postToGallery(...t))},["postToGallery"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[ke],64))],8,["disabled"]),n("button",{class:"btn",disabled:!e.canSetupGameClick,onClick:l[9]||(l[9]=(...t)=>e.setupGameClick&&e.setupGameClick(...t))},["setupGame"===e.uploading?(s(),t(d,{key:0},[i("Uploading ("+r(e.uploadProgressPercent)+"%)",1)],64)):(s(),t(d,{key:1},[Pe,Ae,Se],64))],8,["disabled"])])])])};var ze=e({name:"edit-image-dialog",components:{ResponsiveImage:se,TagsInput:ie},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 Te={class:"area-image"},Ie={class:"has-image"},Ee={class:"area-settings"},Me=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),Ne=n("td",null,[n("label",null,"Tags")],-1),_e={class:"area-buttons"};var Ve,Oe,Be,Ue,Re,$e,Ge,Le;ze.render=function(e,l,o,i,r,d){const c=a("responsive-image"),h=a("tags-input");return s(),t("div",{class:"overlay edit-image-dialog",onClick:l[5]||(l[5]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[4]||(l[4]=u((()=>{}),["stop"]))},[n("div",Te,[n("div",Ie,[n(c,{src:e.image.url,title:e.image.title},null,8,["src","title"])])]),n("div",Ee,[n("table",null,[n("tr",null,[Me,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.title=t),placeholder:"Flower by @artist"},null,512),[[g,e.title]])])]),De,n("tr",null,[Ne,n("td",null,[n(h,{modelValue:e.tags,"onUpdate:modelValue":l[2]||(l[2]=t=>e.tags=t),autocompleteTags:e.autocompleteTags},null,8,["modelValue","autocompleteTags"])])])])]),n("div",_e,[n("button",{class:"btn",onClick:l[3]||(l[3]=(...t)=>e.saveImage&&e.saveImage(...t))},"🖼️ Save image")])])])},(Oe=Ve||(Ve={}))[Oe.Flat=0]="Flat",Oe[Oe.Out=1]="Out",Oe[Oe.In=-1]="In",(Ue=Be||(Be={}))[Ue.FINAL=0]="FINAL",Ue[Ue.ANY=1]="ANY",($e=Re||(Re={}))[$e.NORMAL=0]="NORMAL",$e[$e.ANY=1]="ANY",$e[$e.FLAT=2]="FLAT",(Le=Ge||(Ge={}))[Le.NORMAL=0]="NORMAL",Le[Le.REAL=1]="REAL";var Fe=e({name:"new-game-dialog",components:{ResponsiveImage:se},props:{image:{type:Object,required:!0}},emits:{newGame:null,bgclick:null},data:()=>({tiles:1e3,scoreMode:Be.ANY,shapeMode:Re.NORMAL,snapMode:Ge.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 je={class:"area-image"},We={class:"has-image"},He={key:0,class:"image-title"},Ke={key:0,class:"image-title-title"},qe={key:1,class:"image-title-dim"},Ye={class:"area-settings"},Qe=n("td",null,[n("label",null,"Pieces")],-1),Ze=n("td",null,[n("label",null,"Scoring: ")],-1),Xe=i(" Any (Score when pieces are connected to each other or on final location)"),Je=n("br",null,null,-1),et=i(" Final (Score when pieces are put to their final location)"),tt=n("td",null,[n("label",null,"Shapes: ")],-1),nt=i(" Normal"),lt=n("br",null,null,-1),ot=i(" Any (flat pieces can occur anywhere)"),at=n("br",null,null,-1),st=i(" Flat (all pieces flat on all sides)"),it=n("td",null,[n("label",null,"Snapping: ")],-1),rt=i(" Normal (pieces snap to final destination and to each other)"),dt=n("br",null,null,-1),ct=i(" Real (pieces snap only to corners, already snapped pieces and to each other)"),ut={class:"area-buttons"};Fe.render=function(e,l,i,d,c,h){const m=a("responsive-image");return s(),t("div",{class:"overlay new-game-dialog",onClick:l[11]||(l[11]=t=>e.$emit("bgclick"))},[n("div",{class:"overlay-content",onClick:l[10]||(l[10]=u((()=>{}),["stop"]))},[n("div",je,[n("div",We,[n(m,{src:e.image.url,title:e.image.title},null,8,["src","title"])]),e.image.title||e.image.width||e.image.height?(s(),t("div",He,[e.image.title?(s(),t("span",Ke,'"'+r(e.image.title)+'"',1)):o("",!0),e.image.width||e.image.height?(s(),t("span",qe,"("+r(e.image.width)+" ✕ "+r(e.image.height)+")",1)):o("",!0)])):o("",!0)]),n("div",Ye,[n("table",null,[n("tr",null,[Qe,n("td",null,[p(n("input",{type:"text","onUpdate:modelValue":l[1]||(l[1]=t=>e.tiles=t)},null,512),[[g,e.tiles]])])]),n("tr",null,[Ze,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[2]||(l[2]=t=>e.scoreMode=t),value:"1"},null,512),[[v,e.scoreMode]]),Xe]),Je,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[3]||(l[3]=t=>e.scoreMode=t),value:"0"},null,512),[[v,e.scoreMode]]),et])])]),n("tr",null,[tt,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[4]||(l[4]=t=>e.shapeMode=t),value:"0"},null,512),[[v,e.shapeMode]]),nt]),lt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[5]||(l[5]=t=>e.shapeMode=t),value:"1"},null,512),[[v,e.shapeMode]]),ot]),at,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[6]||(l[6]=t=>e.shapeMode=t),value:"2"},null,512),[[v,e.shapeMode]]),st])])]),n("tr",null,[it,n("td",null,[n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[7]||(l[7]=t=>e.snapMode=t),value:"0"},null,512),[[v,e.snapMode]]),rt]),dt,n("label",null,[p(n("input",{type:"radio","onUpdate:modelValue":l[8]||(l[8]=t=>e.snapMode=t),value:"1"},null,512),[[v,e.snapMode]]),ct])])])])]),n("div",ut,[n("button",{class:"btn",disabled:!e.canStartNewGame,onClick:l[9]||(l[9]=(...t)=>e.onNewGameClick&&e.onNewGameClick(...t))}," 🧩 Generate Puzzle ",8,["disabled"])])])])};var pt=e({components:{ImageLibrary:te,NewImageDialog:pe,EditImageDialog:ze,NewGameDialog:Fe},data:()=>({filters:{sort:"date_desc",tags:[]},images:[],tags:[],image:{id:0,filename:"",file:"",url:"",title:"",tags:[],created:0},dialog:"",uploading:"",uploadProgress:0}),async created(){await this.loadImages()},computed:{relevantTags(){return this.tags.filter((e=>e.total>0))}},methods:{autocompleteTags(e,t){return this.tags.filter((n=>!t.includes(n.title)&&n.title.toLowerCase().startsWith(e.toLowerCase()))).slice(0,10).map((e=>e.title))},toggleTag(e){this.filters.tags.includes(e.slug)?this.filters.tags=this.filters.tags.filter((t=>t!==e.slug)):this.filters.tags.push(e.slug),this.filtersChanged()},async loadImages(){const e=await _(`/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){this.uploadProgress=0;const t=new FormData;t.append("file",e.file,e.file.name),t.append("title",e.title),t.append("tags",e.tags);const n=await V("/api/upload",{body:t,onUploadProgress:e=>{this.uploadProgress=e.loaded/e.total}});return this.uploadProgress=1,await n.json()},async saveImage(e){const t=await V("/api/save-image",{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){const t=await this.saveImage(e);t.ok?(this.dialog="",await this.loadImages()):alert(t.error)},async postToGalleryClick(e){this.uploading="postToGallery",await this.uploadImage(e),this.uploading="",this.dialog="",await this.loadImages()},async setupGameClick(e){this.uploading="setupGame";const t=await this.uploadImage(e);this.uploading="",this.loadImages(),this.image=t,this.dialog="new-game"},async onNewGame(e){const t=await V("/api/newgame",{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 gt={class:"upload-image-teaser"},ht=n("div",{class:"hint"},"(The image you upload will be added to the public gallery.)",-1),mt={key:0},yt=i(" Tags: "),ft=i(" Sort by: "),vt=n("option",{value:"date_desc"},"Newest first",-1),wt=n("option",{value:"date_asc"},"Oldest first",-1),bt=n("option",{value:"alpha_asc"},"A-Z",-1),Ct=n("option",{value:"alpha_desc"},"Z-A",-1);pt.render=function(e,l,i,u,g,h){const m=a("image-library"),y=a("new-image-dialog"),f=a("edit-image-dialog"),v=a("new-game-dialog");return s(),t("div",null,[n("div",gt,[n("div",{class:"btn btn-big",onClick:l[1]||(l[1]=t=>e.dialog="new-image")},"Upload your image"),ht]),n("div",null,[e.tags.length>0?(s(),t("label",mt,[yt,(s(!0),t(d,null,c(e.relevantTags,((n,l)=>(s(),t("span",{class:["bit",{on:e.filters.tags.includes(n.slug)}],key:l,onClick:t=>e.toggleTag(n)},r(n.title)+" ("+r(n.total)+")",11,["onClick"])))),128))])):o("",!0),n("label",null,[ft,p(n("select",{"onUpdate:modelValue":l[2]||(l[2]=t=>e.filters.sort=t),onChange:l[3]||(l[3]=(...t)=>e.filtersChanged&&e.filtersChanged(...t))},[vt,wt,bt,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?(s(),t(y,{key:0,autocompleteTags:e.autocompleteTags,onBgclick:l[4]||(l[4]=t=>e.dialog=""),uploadProgress:e.uploadProgress,uploading:e.uploading,onPostToGalleryClick:e.postToGalleryClick,onSetupGameClick:e.setupGameClick},null,8,["autocompleteTags","uploadProgress","uploading","onPostToGalleryClick","onSetupGameClick"])):o("",!0),"edit-image"===e.dialog?(s(),t(f,{key:1,autocompleteTags:e.autocompleteTags,onBgclick:l[5]||(l[5]=t=>e.dialog=""),onSaveClick:e.onSaveImageClick,image:e.image},null,8,["autocompleteTags","onSaveClick","image"])):o("",!0),e.image&&"new-game"===e.dialog?(s(),t(v,{key:2,onBgclick:l[6]||(l[6]=t=>e.dialog=""),onNewGame:e.onNewGame,image:e.image},null,8,["onNewGame","image"])):o("",!0)])};var xt=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 kt={class:"scores"},Pt=n("div",null,"Scores",-1),At=n("td",null,"⚡",-1),St=n("td",null,"💤",-1);xt.render=function(e,l,o,a,i,u){return s(),t("div",kt,[Pt,n("table",null,[(s(!0),t(d,null,c(e.actives,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[At,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128)),(s(!0),t(d,null,c(e.idles,((e,l)=>(s(),t("tr",{key:l,style:{color:e.color}},[St,n("td",null,r(e.name),1),n("td",null,r(e.points),1)],4)))),128))])])};var zt=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 j(this.duration)}}});const Tt={class:"timer"};zt.render=function(e,l,o,a,i,d){return s(),t("div",Tt,[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 It=e({name:"settings-overlay",emits:{bgclick:null,"update:modelValue":null},props:{modelValue:{type:Object,required:!0}},methods:{updateVolume(e){this.modelValue.soundsVolume=e.target.value},decreaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)-5;this.modelValue.soundsVolume=Math.max(0,e)},increaseVolume(){const e=parseInt(this.modelValue.soundsVolume,10)+5;this.modelValue.soundsVolume=Math.min(100,e)}},created(){this.$watch("modelValue",(e=>{this.$emit("update:modelValue",e)}),{deep:!0})}});const Et=m();y("data-v-4d56fc17");const Mt=n("td",null,[n("label",null,"Background: ")],-1),Dt=n("td",null,[n("label",null,"Color: ")],-1),Nt=n("td",null,[n("label",null,"Name: ")],-1),_t=n("td",null,[n("label",null,"Sounds: ")],-1),Vt=n("td",null,[n("label",null,"Sounds Volume: ")],-1),Ot={class:"sound-volume"},Bt=n("td",null,[n("label",null,"Show player names: ")],-1);f();const Ut=Et(((e,l,o,a,i,r)=>(s(),t("div",{class:"overlay transparent",onClick:l[10]||(l[10]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content settings",onClick:l[9]||(l[9]=u((()=>{}),["stop"]))},[n("tr",null,[Mt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[1]||(l[1]=t=>e.modelValue.background=t)},null,512),[[g,e.modelValue.background]])])]),n("tr",null,[Dt,n("td",null,[p(n("input",{type:"color","onUpdate:modelValue":l[2]||(l[2]=t=>e.modelValue.color=t)},null,512),[[g,e.modelValue.color]])])]),n("tr",null,[Nt,n("td",null,[p(n("input",{type:"text",maxLength:"16","onUpdate:modelValue":l[3]||(l[3]=t=>e.modelValue.name=t)},null,512),[[g,e.modelValue.name]])])]),n("tr",null,[_t,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[4]||(l[4]=t=>e.modelValue.soundsEnabled=t)},null,512),[[C,e.modelValue.soundsEnabled]])])]),n("tr",null,[Vt,n("td",Ot,[n("span",{onClick:l[5]||(l[5]=(...t)=>e.decreaseVolume&&e.decreaseVolume(...t))},"🔉"),n("input",{type:"range",min:"0",max:"100",value:e.modelValue.soundsVolume,onChange:l[6]||(l[6]=(...t)=>e.updateVolume&&e.updateVolume(...t))},null,40,["value"]),n("span",{onClick:l[7]||(l[7]=(...t)=>e.increaseVolume&&e.increaseVolume(...t))},"🔊")])]),n("tr",null,[Bt,n("td",null,[p(n("input",{type:"checkbox","onUpdate:modelValue":l[8]||(l[8]=t=>e.modelValue.showPlayerNames=t)},null,512),[[C,e.modelValue.showPlayerNames]])])])])]))));It.render=Ut,It.__scopeId="data-v-4d56fc17";var Rt=e({name:"preview-overlay",props:{img:String},emits:{bgclick:null},computed:{previewStyle(){return{backgroundImage:`url('${this.img}')`}}}});const $t={class:"preview"};Rt.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay",onClick:l[1]||(l[1]=t=>e.$emit("bgclick"))},[n("div",$t,[n("div",{class:"img",style:e.previewStyle},null,4)])])};var Gt=e({name:"help-overlay",emits:{bgclick:null},props:{game:{type:Object,required:!0}},computed:{scoreMode(){switch(this.game.scoreMode){case Be.ANY:return["Any","Score when pieces are connected to each other or on final location"];case Be.FINAL:default:return["Final","Score when pieces are put to their final location"]}},shapeMode(){switch(this.game.shapeMode){case Re.FLAT:return["Flat","all pieces flat on all sides"];case Re.ANY:return["Any","flat pieces can occur anywhere"];case Re.NORMAL:default:return["Normal",""]}},snapMode(){switch(this.game.snapMode){case Ge.REAL:return["Real","pieces snap only to corners, already snapped pieces and to each other"];case Ge.NORMAL:default:return["Normal","pieces snap to final destination and to each other"]}}}});const Lt=n("tr",null,[n("td",{colspan:"2"},"Info about this puzzle")],-1),Ft=n("td",null,"Image Title: ",-1),jt=n("td",null,"Scoring: ",-1),Wt=n("td",null,"Shapes: ",-1),Ht=n("td",null,"Snapping: ",-1);Gt.render=function(e,l,o,a,i,d){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Lt,n("tr",null,[Ft,n("td",null,r(e.game.puzzle.info.image.title),1)]),n("tr",null,[jt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.scoreMode[0]),9,["title"])])]),n("tr",null,[Wt,n("td",null,[n("span",{title:e.snapMode[1]},r(e.shapeMode[0]),9,["title"])])]),n("tr",null,[Ht,n("td",null,[n("span",{title:e.snapMode[1]},r(e.snapMode[0]),9,["title"])])])])])};var Kt=1,qt=4,Yt=2,Qt=3,Zt=2,Xt=4,Jt=3,en=9,tn=1,nn=2,ln=3,on=4,an=5,sn=6,rn=7,dn=8,cn=10,un=11,pn=12,gn=13,hn=14,mn=15,yn=16,fn=17,vn=18,wn=1,bn=2,Cn=3;const xn=oe("Communication.js");let kn,Pn=[],An=e=>{Pn.push(e)},Sn=[],zn=e=>{Sn.push(e)};let Tn=0;const In=e=>{Tn!==e&&(Tn=e,zn(e))};function En(e){if(2===Tn)try{kn.send(JSON.stringify(e))}catch(t){xn.info("unable to send message.. maybe because ws is invalid?")}}let Mn,Dn;var Nn={connect:function(e,t,n){return Mn=0,Dn={},In(3),new Promise((l=>{kn=new WebSocket(e,n+"|"+t),kn.onopen=()=>{In(2),En([Qt])},kn.onmessage=e=>{const t=JSON.parse(e.data),o=t[0];if(o===qt){const e=t[1];l(e)}else{if(o!==Kt)throw`[ 2021-05-09 invalid connect msgType ${o} ]`;{const e=t[1],l=t[2];if(e===n&&Dn[l])return void delete Dn[l];An(t)}}},kn.onerror=()=>{throw In(1),"[ 2021-05-15 onerror ]"},kn.onclose=e=>{4e3===e.code||1001===e.code?In(4):In(1)}}))},requestReplayData:async function(e,t){const n={gameId:e,offset:t},l=await _(`/api/replay-data${ae.asQueryArgs(n)}`,{});return await l.json()},disconnect:function(){kn&&kn.close(4e3),Mn=0,Dn={}},sendClientEvent:function(e){Mn++,Dn[Mn]=e,En([Yt,Mn,Dn[Mn]])},onServerChange:function(e){An=e;for(const t of Pn)An(t);Pn=[]},onConnectionStateChange:function(e){zn=e;for(const t of Sn)zn(t);Sn=[]},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},_n=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 Vn={key:0,class:"overlay connection-lost"},On={key:0,class:"overlay-content"},Bn=n("div",null,"⁉️ LOST CONNECTION ⁉️",-1),Un={key:1,class:"overlay-content"},Rn=n("div",null,"Connecting...",-1);_n.render=function(e,l,a,i,r,d){return e.show?(s(),t("div",Vn,[e.lostConnection?(s(),t("div",On,[Bn,n("span",{class:"btn",onClick:l[1]||(l[1]=t=>e.$emit("reconnect"))},"Reconnect")])):o("",!0),e.connecting?(s(),t("div",Un,[Rn])):o("",!0)])):o("",!0)};var $n=e({name:"help-overlay",emits:{bgclick:null}});const Gn=n("tr",null,[n("td",null,"⬆️ Move up:"),n("td",null,[n("div",null,[n("kbd",null,"W"),i("/"),n("kbd",null,"↑"),i("/🖱️")])])],-1),Ln=n("tr",null,[n("td",null,"⬇️ Move down:"),n("td",null,[n("div",null,[n("kbd",null,"S"),i("/"),n("kbd",null,"↓"),i("/🖱️")])])],-1),Fn=n("tr",null,[n("td",null,"⬅️ Move left:"),n("td",null,[n("div",null,[n("kbd",null,"A"),i("/"),n("kbd",null,"←"),i("/🖱️")])])],-1),jn=n("tr",null,[n("td",null,"➡️ Move right:"),n("td",null,[n("div",null,[n("kbd",null,"D"),i("/"),n("kbd",null,"→"),i("/🖱️")])])],-1),Wn=n("tr",null,[n("td"),n("td",null,[n("div",null,[i("Move faster by holding "),n("kbd",null,"Shift")])])],-1),Hn=n("tr",null,[n("td",null,"🔍+ Zoom in:"),n("td",null,[n("div",null,[n("kbd",null,"E"),i("/🖱️-Wheel")])])],-1),Kn=n("tr",null,[n("td",null,"🔍- Zoom out:"),n("td",null,[n("div",null,[n("kbd",null,"Q"),i("/🖱️-Wheel")])])],-1),qn=n("tr",null,[n("td",null,"🖼️ Toggle preview:"),n("td",null,[n("div",null,[n("kbd",null,"Space")])])],-1),Yn=n("tr",null,[n("td",null,"🎯 Center puzzle in screen:"),n("td",null,[n("div",null,[n("kbd",null,"C")])])],-1),Qn=n("tr",null,[n("td",null,"🧩✔️ Toggle fixed pieces:"),n("td",null,[n("div",null,[n("kbd",null,"F")])])],-1),Zn=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 player names:"),n("td",null,[n("div",null,[n("kbd",null,"N")])])],-1),Jn=n("tr",null,[n("td",null,"🔉 Toggle sounds:"),n("td",null,[n("div",null,[n("kbd",null,"M")])])],-1),el=n("tr",null,[n("td",null,"⏫ Speed up (replay):"),n("td",null,[n("div",null,[n("kbd",null,"I")])])],-1),tl=n("tr",null,[n("td",null,"⏬ Speed down (replay):"),n("td",null,[n("div",null,[n("kbd",null,"O")])])],-1),nl=n("tr",null,[n("td",null,"⏸️ Pause (replay):"),n("td",null,[n("div",null,[n("kbd",null,"P")])])],-1);$n.render=function(e,l,o,a,i,r){return s(),t("div",{class:"overlay transparent",onClick:l[2]||(l[2]=t=>e.$emit("bgclick"))},[n("table",{class:"overlay-content help",onClick:l[1]||(l[1]=u((()=>{}),["stop"]))},[Gn,Ln,Fn,jn,Wn,Hn,Kn,qn,Yn,Qn,Zn,Xn,Jn,el,tl,nl])])};var ll=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"/assets/click.bb97cb07.mp3"}),ol=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAW0lEQVQ4je1RywrAIAxLxP//5exixRWlVgZelpOKeTQFfnDypgy3eLIkSLLL8mxGPoHsU2hPAgDHBLvRX6hZZw/fwT0BtlLSONqCbWAmEIqMZOCDDlaDR3N03gOyDCn+y4DWmAAAAABJRU5ErkJggg=="}),al=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAARElEQVQ4jWNgGAU0Af+hmBCbgYGBgYERhwHEAEYGBgYGJtIdiApYyLAZBVDsAqoagC1ACQJyY4ERg0GCISh6KA4DigEAou8LC+LnIJoAAAAASUVORK5CYII="}),sl=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAcUlEQVQ4ja1TQQ7AIAgD///n7jCozA2Hbk00jbG1KIrcARszTugoBs49qioZj7r2kKACptkyAOCJsJuA+GzglwHjvMSSWFVaENWVASxh5eRLiq5fN/ASjI89VcP2K3hHpq1cEXNaMfnrL3TDZP2tDuoOA6MzCCXWr38AAAAASUVORK5CYII="}),il=Object.freeze({__proto__:null,[Symbol.toStringTag]:"Module",default:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAU0lEQVQ4jWNgoAH4D8X42HDARKlt5BoAd82AuQAOGLGIYQQUPv0wF5CiCQUge4EsQ5C9QI4BjMguwBYeBAElscCIy1ZivMKIwSDBEBQ9FCckigEAU3QOD7TGvY4AAAAASUVORK5CYII="});function rl(e=0,t=0){const n=document.createElement("canvas");return n.width=e,n.height=t,n}var dl={createCanvas:rl,loadImageToBitmap:async function(e){return new Promise((t=>{const n=new Image;n.onload=()=>{createImageBitmap(n).then(t)},n.src=e}))},resizeBitmap:async function(e,t,n){const l=rl(t,n);return l.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t,n),await createImageBitmap(l)},colorizedCanvas:function(e,t,n){const l=rl(e.width,e.height),o=l.getContext("2d");return o.save(),o.drawImage(t,0,0),o.fillStyle=n,o.globalCompositeOperation="source-in",o.fillRect(0,0,t.width,t.height),o.restore(),o.save(),o.globalCompositeOperation="destination-over",o.drawImage(e,0,0),o.restore(),l}};const cl=oe("Debug.js");let ul=0,pl=0;var gl=e=>{ul=performance.now(),pl=e},hl=e=>{const t=performance.now(),n=t-ul;n>pl&&cl.log(e+": "+n),ul=t};function ml(e,t){const n=e.x-t.x,l=e.y-t.y;return Math.sqrt(n*n+l*l)}function yl(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}var fl={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:ml,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:yl,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 ml(yl(e),yl(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 vl=oe("PuzzleGraphics.js");function wl(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 bl={loadPuzzleBitmaps:async function(e){const t=await dl.loadImageToBitmap(e.info.imageUrl),n=await dl.resizeBitmap(t,e.info.width,e.info.height);return await async function(e,t,n){vl.log("start createPuzzleTileBitmaps");const l=n.tileSize,o=n.tileMarginWidth,a=n.tileDrawSize,s=l/100,i=[0,0,40,15,37,5,37,5,40,0,38,-5,38,-5,20,-20,50,-20,50,-20,80,-20,62,-5,62,-5,60,0,63,5,63,5,65,15,100,0],r=new Array(t.length),d={};function c(e){const t=`${e.top}${e.right}${e.left}${e.bottom}`;if(d[t])return d[t];const n=new Path2D,a={x:o,y:o},r=fl.pointAdd(a,{x:l,y:0}),c=fl.pointAdd(r,{x:0,y:l}),u=fl.pointSub(c,{x:l,y:0});if(n.moveTo(a.x,a.y),0!==e.top)for(let l=0;lae.decodePiece(Cl[e].puzzle.tiles[t]),Ol=(e,t)=>Vl(e,t).group,Bl=(e,t)=>{const n=Cl[e].puzzle.info;return 0===t||t===n.tilesX-1||t===n.tiles-n.tilesX||t===n.tiles-1},Ul=(e,t)=>{const n=Cl[e].puzzle.info,l={x:(n.table.width-n.width)/2,y:(n.table.height-n.height)/2},o=function(e,t){const n=Cl[e].puzzle.info,l=ae.coordByPieceIdx(n,t),o=l.x*n.tileSize,a=l.y*n.tileSize;return{x:o,y:a}}(e,t);return fl.pointAdd(l,o)},Rl=(e,t)=>Vl(e,t).pos,$l=e=>{const t=lo(e),n=oo(e),l=Math.round(t/4),o=Math.round(n/4);return{x:0-l,y:0-o,w:t+2*l,h:n+2*o}},Gl=(e,t)=>{const n=Wl(e),l=Vl(e,t);return{x:l.pos.x,y:l.pos.y,w:n,h:n}},Ll=(e,t)=>Vl(e,t).z,Fl=(e,t)=>{for(const n of Cl[e].puzzle.tiles){const e=ae.decodePiece(n);if(e.owner===t)return e.idx}return-1},jl=e=>Cl[e].puzzle.info.tileDrawSize,Wl=e=>Cl[e].puzzle.info.tileSize,Hl=e=>Cl[e].puzzle.data.maxGroup,Kl=e=>Cl[e].puzzle.data.maxZ;function ql(e,t){const n=Cl[e].puzzle.info,l=ae.coordByPieceIdx(n,t);return[l.y>0?t-n.tilesX:-1,l.x0?t-1:-1]}const Yl=(e,t,n)=>{for(const l of t)_l(e,l,{z:n})},Ql=(e,t,n)=>{const l=Rl(e,t);_l(e,t,{pos:fl.pointAdd(l,n)})},Zl=(e,t,n)=>{const l=jl(e),o=$l(e),a=n;for(const s of t){const t=Vl(e,s);t.pos.x+n.xo.x+o.w&&(a.x=Math.min(o.x+o.w-t.pos.x+l,a.x)),t.pos.y+n.yo.y+o.h&&(a.y=Math.min(o.y+o.h-t.pos.y+l,a.y))}for(const s of t)Ql(e,s,a)},Xl=(e,t)=>Vl(e,t).owner,Jl=(e,t)=>{for(const n of t)_l(e,n,{owner:-1,z:1})},eo=(e,t,n)=>{for(const l of t)_l(e,l,{owner:n})};function to(e,t){const n=Cl[e].puzzle.tiles,l=ae.decodePiece(n[t]),o=[];if(l.group)for(const a of n){const e=ae.decodePiece(a);e.group===l.group&&o.push(e.idx)}else o.push(l.idx);return o}const no=(e,t)=>{const n=kl(e,t);return n?n.points:0},lo=e=>Cl[e].puzzle.info.table.width,oo=e=>Cl[e].puzzle.info.table.height;var ao={setGame:function(e,t){Cl[e]=t},exists:function(e){return!!Cl[e]||!1},playerExists:Al,getActivePlayers:function(e,t){const n=t-30*G;return Sl(e).filter((e=>e.ts>=n))},getIdlePlayers:function(e,t){const n=t-30*G;return Sl(e).filter((e=>e.ts0))},addPlayer:function(e,t,n){Al(e,t)?Dl(e,t,{ts:n}):Pl(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:Ml,getPieceCount:zl,getImageUrl:function(e){var t;const n=(null==(t=Cl[e].puzzle.info.image)?void 0:t.url)||Cl[e].puzzle.info.imageUrl;if(!n)throw new Error("[2021-07-11] no image url set");return n},get:function(e){return Cl[e]||null},getAllGames:function(){return Object.values(Cl).sort(((e,t)=>{const n=El(e.id);return n===El(t.id)?n?t.puzzle.data.finished-e.puzzle.data.finished:t.puzzle.data.started-e.puzzle.data.started:n?1:-1}))},getPlayerBgColor:(e,t)=>{const n=kl(e,t);return n?n.bgcolor:null},getPlayerColor:(e,t)=>{const n=kl(e,t);return n?n.color:null},getPlayerName:(e,t)=>{const n=kl(e,t);return n?n.name:null},getPlayerIndexById:xl,getPlayerIdByIndex:function(e,t){return Cl[e].players.length>t?ae.decodePlayer(Cl[e].players[t]).id:null},changePlayer:Dl,setPlayer:Pl,setPiece:function(e,t,n){Cl[e].puzzle.tiles[t]=ae.encodePiece(n)},setPuzzleData:function(e,t){Cl[e].puzzle.data=t},getTableWidth:lo,getTableHeight:oo,getPuzzle:e=>Cl[e].puzzle,getRng:e=>Cl[e].rng.obj,getPuzzleWidth:e=>Cl[e].puzzle.info.width,getPuzzleHeight:e=>Cl[e].puzzle.info.height,getPiecesSortedByZIndex:function(e){return Cl[e].puzzle.tiles.map(ae.decodePiece).sort(((e,t)=>e.z-t.z))},getFirstOwnedPiece:(e,t)=>{const n=Fl(e,t);return n<0?null:Cl[e].puzzle.tiles[n]},getPieceDrawOffset:e=>Cl[e].puzzle.info.tileDrawOffset,getPieceDrawSize:jl,getFinalPiecePos:Ul,getStartTs:e=>Cl[e].puzzle.data.started,getFinishTs:e=>Cl[e].puzzle.data.finished,handleInput:function(e,t,n,l,o){const a=Cl[e].puzzle,s=function(e,t){return t in Cl[e].evtInfos?Cl[e].evtInfos[t]:{_last_mouse:null,_last_mouse_down:null}}(e,t),i=[],r=()=>{i.push([wn,a.data])},d=t=>{i.push([bn,ae.encodePiece(Vl(e,t))])},c=e=>{for(const t of e)d(t)},u=()=>{const n=kl(e,t);n&&i.push([Cn,ae.encodePlayer(n)])},p=n[0];if(p===sn){const o=n[1];Dl(e,t,{bgcolor:o,ts:l}),u()}else if(p===rn){const o=n[1];Dl(e,t,{color:o,ts:l}),u()}else if(p===dn){const o=`${n[1]}`.substr(0,16);Dl(e,t,{name:o,ts:l}),u()}else if(p===en){const o=n[1],a=n[2],s=kl(e,t);if(s){const n=s.x-o,i=s.y-a;Dl(e,t,{ts:l,x:n,y:i}),u()}}else if(p===tn){const o={x:n[1],y:n[2]};Dl(e,t,{d:1,ts:l}),u(),s._last_mouse_down=o;const a=((e,t)=>{const n=Cl[e].puzzle.info,l=Cl[e].puzzle.tiles;let o=-1,a=-1;for(let s=0;so)&&(o=e.z,a=s)}return a})(e,o);if(a>=0){const n=Kl(e)+1;Nl(e,{maxZ:n}),r();const l=to(e,a);Yl(e,l,Kl(e)),eo(e,l,t),c(l)}s._last_mouse=o}else if(p===ln){const o=n[1],a=n[2],i={x:o,y:a};if(null===s._last_mouse_down)Dl(e,t,{x:o,y:a,ts:l}),u();else{const n=Fl(e,t);if(n>=0){Dl(e,t,{x:o,y:a,ts:l}),u();const r=to(e,n);let d=fl.pointInBounds(i,$l(e))&&fl.pointInBounds(s._last_mouse_down,$l(e));for(const t of r){const n=Gl(e,t);if(fl.pointInBounds(i,n)){d=!0;break}}if(d){const t=o-s._last_mouse_down.x,n=a-s._last_mouse_down.y;Zl(e,r,{x:t,y:n}),c(r)}}else Dl(e,t,{ts:l}),u();s._last_mouse_down=i}s._last_mouse=i}else if(p===nn){const i={x:n[1],y:n[2]},p=0;s._last_mouse_down=null;const g=Fl(e,t);if(g>=0){const n=to(e,g);eo(e,n,0),c(n);const s=Rl(e,g),i=Ul(e,g);let h=!1;if(Il(e)===Ge.REAL){for(const t of n)if(Bl(e,t)){h=!0;break}}else h=!0;if(h&&fl.pointDistance(i,s){const o=Cl[e].puzzle.info;if(n<0)return!1;if(((e,t,n)=>{const l=Ol(e,t),o=Ol(e,n);return!(!l||l!==o)})(e,t,n))return!1;const a=Rl(e,t),s=fl.pointAdd(Rl(e,n),{x:l[0]*o.tileSize,y:l[1]*o.tileSize});if(fl.pointDistance(a,s){const l=Cl[e].puzzle.tiles,o=Ol(e,t),a=Ol(e,n);let s;const i=[];o&&i.push(o),a&&i.push(a),o?s=o:a?s=a:(Nl(e,{maxGroup:Hl(e)+1}),r(),s=Hl(e));if(_l(e,t,{group:s}),d(t),_l(e,n,{group:s}),d(n),i.length>0)for(const r of l){const t=ae.decodePiece(r);i.includes(t.group)&&(_l(e,t.idx,{group:s}),d(t.idx))}})(e,t,n),o=to(e,t),((e,t)=>-1===Xl(e,t))(e,n))Jl(e,o);else{const t=((e,t)=>{let n=0;for(const l of t){const t=Ll(e,l);t>n&&(n=t)}return n})(e,o);Yl(e,o,t)}return c(o),!0}return!1};let a=!1;for(const t of to(e,g)){const l=ql(e,t);if(n(e,t,l[0],[0,1])||n(e,t,l[1],[-1,0])||n(e,t,l[2],[0,-1])||n(e,t,l[3],[1,0])){a=!0;break}}if(a&&Tl(e)===Be.ANY){const n=no(e,t)+1;Dl(e,t,{d:p,ts:l,points:n}),u()}else Dl(e,t,{d:p,ts:l}),u();a&&Il(e)===Ge.REAL&&Ml(e)===zl(e)&&(Nl(e,{finished:l}),r()),a&&o&&o(t)}}else Dl(e,t,{d:p,ts:l}),u();s._last_mouse=i}else if(p===on){const o=n[1],a=n[2];Dl(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else if(p===an){const o=n[1],a=n[2];Dl(e,t,{x:o,y:a,ts:l}),u(),s._last_mouse={x:o,y:a}}else Dl(e,t,{ts:l}),u();return function(e,t,n){Cl[e].evtInfos[t]=n}(e,t,s),i}};let so=-10,io=20,ro=2,co=15;class uo{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=so+Math.random()*io,this.vy=-1*(ro+Math.random()*co),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;ro=t/2,co=t-ro;const n=1/4*this.canvas.width/(t/2);so=-n,io=2*n}resize(){this.setSpeedParams()}init(){this.readyBombs=[],this.explodedBombs=[],this.particles=[];for(let e=0;e<1;e++)this.readyBombs.push(new uo(this.rng))}update(){100*Math.random()<5&&this.readyBombs.push(new uo(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{localStorage.setItem(e,t)},Co=e=>localStorage.getItem(e);var xo=(e,t)=>{bo(e,`${t}`)},ko=(e,t)=>{const n=Co(e);if(null===n)return t;const l=parseInt(n,10);return isNaN(l)?t:l},Po=(e,t)=>{bo(e,t?"1":"0")},Ao=(e,t)=>{const n=Co(e);return null===n?t:"1"===n},So=(e,t)=>{bo(e,t)},zo=(e,t)=>{const n=Co(e);return null===n?t:n};const To={"./grab.png":ol,"./grab_mask.png":al,"./hand.png":sl,"./hand_mask.png":il},Io={"./click.mp3":ll},Eo="replay";let Mo=!0,Do=!0;let No=!0;async function _o(e,t,n,l,o,a){void 0===window.DEBUG&&(window.DEBUG=!1);const s=Io["./click.mp3"].default,i=new Audio(s),r=await dl.loadImageToBitmap(To["./grab.png"].default),d=await dl.loadImageToBitmap(To["./hand.png"].default),c=await dl.loadImageToBitmap(To["./grab_mask.png"].default),u=await dl.loadImageToBitmap(To["./hand_mask.png"].default),p=r.width,g=Math.round(p/2),h=r.height,m=Math.round(h/2),y={},f=async e=>{const t=e.color+" "+e.d;if(!y[t]){const n=e.d?r:d;if(e.color){const l=e.d?c:u;y[t]=await createImageBitmap(dl.colorizedCanvas(n,l,e.color))}else y[t]=n}return y[t]},v=function(e,t){return t.width=window.innerWidth,t.height=window.innerHeight,e.appendChild(t),window.addEventListener("resize",(()=>{t.width=window.innerWidth,t.height=window.innerHeight,No=!0})),t}(o,dl.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};Nn.onConnectionStateChange((e=>{a.setConnectionState(e)}));const b=async e=>{const t=w.dataOffset;w.dataOffset+=1e4;const n=await Nn.requestReplayData(e,t);return w.log=w.log.slice(w.logPointer),w.logPointer=0,w.log.push(...n.log),0===n.log.length&&(w.final=!0),n};let C=()=>0;const x=async()=>{if("play"===l){const l=await Nn.connect(n,e,t),o=ae.decodeGame(l);ao.setGame(o.id,o),C=()=>L()}else{if(l!==Eo)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);ao.setGame(n.id,n),w.lastRealTs=L(),w.gameStartTs=parseInt(t.log[0][4],10),w.lastGameTs=w.gameStartTs,C=()=>w.lastGameTs}}No=!0};await x();const k=ao.getPieceDrawOffset(e),P=ao.getPieceDrawSize(e),A=ao.getPuzzleWidth(e),S=ao.getPuzzleHeight(e),z=ao.getTableWidth(e),T=ao.getTableHeight(e),I={x:(z-A)/2,y:(T-S)/2},E={w:A,h:S},M={w:P,h:P},D=await bl.loadPuzzleBitmaps(ao.getPuzzle(e)),N=new go(v,ao.getRng(e));N.init();const _=v.getContext("2d");v.classList.add("loaded"),a.setPuzzleCut();const V=function(){let e=0,t=0,n=1;const l=(l,o)=>{e+=l/n,t+=o/n},o=e=>{const t=n+.05*n*("in"===e?1:-1);return Math.min(Math.max(t,.1),6)},a=(e,t)=>{if(n==e)return!1;const o=1-n/e;return l(-t.x*o,-t.y*o),n=e,!0},s=l=>({x:l.x/n-e,y:l.y/n-t}),i=l=>({x:(l.x+e)*n,y:(l.y+t)*n}),r=e=>({w:e.w*n,h:e.h*n}),d=e=>({w:e.w/n,h:e.h/n});return{getCurrentZoom:()=>n,reset:()=>{e=0,t=0,n=1},move:l,canZoom:e=>n!=o(e),zoom:(e,t)=>a(o(e),t),setZoom:a,worldToViewport:e=>{const{x:t,y:n}=i(e);return{x:Math.round(t),y:Math.round(n)}},worldToViewportRaw:i,worldDimToViewport:e=>{const{w:t,h:n}=r(e);return{w:Math.round(t),h:Math.round(n)}},worldDimToViewportRaw:r,viewportToWorld:e=>{const{x:t,y:n}=s(e);return{x:Math.round(t),y:Math.round(n)}},viewportToWorldRaw:s,viewportDimToWorld:e=>{const{w:t,h:n}=d(e);return{w:Math.round(t),h:Math.round(n)}},viewportDimToWorldRaw:d}}(),O=()=>{V.reset(),V.move(-(z-v.width)/2,-(T-v.height)/2);const e=V.worldDimToViewport(E),t=v.width-40,n=v.height-40;if(e.w>t||e.h>n||e.w{const l=n.viewportToWorld({x:e,y:t});return[l.x,l.y]},h=e=>g(e.offsetX,e.offsetY),m=()=>g(e.width/2,e.height/2),y=(e,t)=>{a&&("ShiftLeft"===t.code||"ShiftRight"===t.code?p=e:"ArrowUp"===t.code||"KeyW"===t.code?r=e:"ArrowDown"===t.code||"KeyS"===t.code?d=e:"ArrowLeft"===t.code||"KeyA"===t.code?s=e:"ArrowRight"===t.code||"KeyD"===t.code?i=e:"KeyQ"===t.code?u=e:"KeyE"===t.code&&(c=e))};let f=null;e.addEventListener("mousedown",(e=>{f=h(e),0===e.button&&v([tn,...f])})),e.addEventListener("mouseup",(e=>{f=h(e),0===e.button&&v([nn,...f])})),e.addEventListener("mousemove",(e=>{f=h(e),v([ln,...f])})),e.addEventListener("wheel",(e=>{if(f=h(e),n.canZoom(e.deltaY<0?"in":"out")){const t=e.deltaY<0?on:an;v([t,...f])}})),t.addEventListener("keydown",(e=>y(!0,e))),t.addEventListener("keyup",(e=>y(!1,e))),t.addEventListener("keypress",(e=>{a&&("Space"===e.code&&v([cn]),l===Eo&&("KeyI"===e.code&&v([gn]),"KeyO"===e.code&&v([hn]),"KeyP"===e.code&&v([pn])),"KeyF"===e.code&&v([fn]),"KeyG"===e.code&&v([vn]),"KeyM"===e.code&&v([un]),"KeyN"===e.code&&v([mn]),"KeyC"===e.code&&v([yn]))}));const v=e=>{o.push(e)};return{addEvent:v,consumeAll:()=>{if(0===o.length)return[];const e=o.slice();return o=[],e},createKeyEvents:()=>{const e=(s?1:0)-(i?1:0),t=(r?1:0)-(d?1:0);if(0!==e||0!==t){const l=(p?24:12)*Math.sqrt(n.getCurrentZoom()),o=n.viewportDimToWorld({w:e*l,h:t*l});v([en,o.w,o.h]),f&&(f[0]-=o.w,f[1]-=o.h)}if(c&&u);else if(c){if(n.canZoom("in")){const e=f||m();v([on,...e])}}else if(u&&n.canZoom("out")){const e=f||m();v([an,...e])}},setHotkeys:e=>{a=e}}}(v,window,V,l),U=ao.getImageUrl(e),R=()=>{const t=ao.getStartTs(e),n=ao.getFinishTs(e),l=C();a.setFinished(!!n),a.setDuration((n||l)-t)};R(),a.setPiecesDone(ao.getFinishedPiecesCount(e)),a.setPiecesTotal(ao.getPieceCount(e));const G=C();a.setActivePlayers(ao.getActivePlayers(e,G)),a.setIdlePlayers(ao.getIdlePlayers(e,G));const F=!!ao.getFinishTs(e);let j=F;const W=()=>j&&!F,H=()=>ko(ho,100),K=()=>Ao(mo,!1),q=()=>Ao(wo,!0),Y=()=>{const e=H();i.volume=e/100,i.play()},Q=()=>l===Eo?zo(yo,"#222222"):ao.getPlayerBgColor(e,t)||zo(yo,"#222222"),Z=()=>l===Eo?zo(fo,"#ffffff"):ao.getPlayerColor(e,t)||zo(fo,"#ffffff");let X="",J="",ee=!1;const te=e=>{ee=e;const[t,n]=e?[X,"grab"]:[J,"default"];v.style.cursor=`url('${t}') ${g} ${m}, ${n}`},ne=e=>{X=dl.colorizedCanvas(r,c,e).toDataURL(),J=dl.colorizedCanvas(d,u,e).toDataURL(),te(ee)};ne(Z());const le=()=>{a.setReplaySpeed&&a.setReplaySpeed(w.speeds[w.speedIdx]),a.setReplayPaused&&a.setReplayPaused(w.paused)},oe=()=>{w.speedIdx+1{w.speedIdx>=1&&(w.speedIdx--,le())},ie=()=>{w.paused=!w.paused,le()},re=[];let de;let ce;if("play"===l?re.push(setInterval((()=>{R()}),1e3)):l===Eo&&le(),"play"===l)Nn.onServerChange((n=>{n[0],n[1],n[2];const l=n[3];for(const[o,a]of l)switch(o){case Cn:{const n=ae.decodePlayer(a);n.id!==t&&(ao.setPlayer(e,n.id,n),No=!0)}break;case bn:{const t=ae.decodePiece(a);ao.setPiece(e,t.idx,t),No=!0}break;case wn:ao.setPuzzleData(e,a),No=!0}j=!!ao.getFinishTs(e)}));else if(l===Eo){const t=(t,n)=>{const l=t;if(l[0]===Zt){const t=l[1];return ao.addPlayer(e,t,n),!0}if(l[0]===Xt){const t=ao.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (update player) ]";return ao.addPlayer(e,t,n),!0}if(l[0]===Jt){const t=ao.getPlayerIdByIndex(e,l[1]);if(!t)throw"[ 2021-05-17 player not found (handle input) ]";const o=l[2];return ao.handleInput(e,t,o,n),!0}return!1};let n=w.lastGameTs;const l=async()=>{w.logPointer+1>=w.log.length&&await b(e);const o=L();if(w.paused)return w.lastRealTs=o,void(de=setTimeout(l,50));const a=(o-w.lastRealTs)*w.speeds[w.speedIdx];let s=w.lastGameTs+a;for(;;){if(w.paused)break;const e=w.logPointer+1;if(e>=w.log.length)break;const l=w.log[w.logPointer],o=n+l[l.length-1],a=w.log[e],i=a[a.length-1],r=o+i;if(r>s){s+500*${let t=!1;const n=e.fps||60,l=e.slow||1,o=e.update,a=e.render,s=window.requestAnimationFrame,i=1/n,r=l*i;let d,c=0,u=window.performance.now();const p=()=>{for(d=window.performance.now(),c+=Math.min(1,(d-u)/1e3);c>r;)c-=r,o(i);a(c/l),u=d,t||s(p)};return s(p),{stop:()=>{t=!0}}})({update:()=>{B.createKeyEvents();for(const n of B.consumeAll())if("play"===l){const l=n[0];if(l===en){const e=n[1],t=n[2],l=V.worldDimToViewport({w:e,h:t});No=!0,V.move(l.w,l.h)}else if(l===ln){if(ue&&!ao.getFirstOwnedPiece(e,t)){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);No=!0,V.move(l,o),ue=t}}else if(l===rn)ne(n[1]);else if(l===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(l===nn)ue=null,te(!1);else if(l===on){const e={x:n[1],y:n[2]};No=!0,V.zoom("in",V.worldToViewport(e))}else if(l===an){const e={x:n[1],y:n[2]};No=!0,V.zoom("out",V.worldToViewport(e))}else l===cn?a.togglePreview():l===un?a.toggleSoundsEnabled():l===mn?a.togglePlayerNames():l===yn?O():l===fn?(Mo=!Mo,No=!0):l===vn&&(Do=!Do,No=!0);const o=C();ao.handleInput(e,t,n,o,(e=>{K()&&Y()})).length>0&&(No=!0),Nn.sendClientEvent(n)}else if(l===Eo){const e=n[0];if(e===pn)ie();else if(e===hn)se();else if(e===gn)oe();else if(e===en){const e=n[1],t=n[2];No=!0,V.move(e,t)}else if(e===ln){if(ue){const e={x:n[1],y:n[2]},t=V.worldToViewport(e),l=Math.round(t.x-ue.x),o=Math.round(t.y-ue.y);No=!0,V.move(l,o),ue=t}}else if(e===rn)ne(n[1]);else if(e===tn){const e={x:n[1],y:n[2]};ue=V.worldToViewport(e),te(!0)}else if(e===nn)ue=null,te(!1);else if(e===on){const e={x:n[1],y:n[2]};No=!0,V.zoom("in",V.worldToViewport(e))}else if(e===an){const e={x:n[1],y:n[2]};No=!0,V.zoom("out",V.worldToViewport(e))}else e===cn?a.togglePreview():e===un?a.toggleSoundsEnabled():e===mn?a.togglePlayerNames():e===yn?O():e===fn?(Mo=!Mo,No=!0):e===vn&&(Do=!Do,No=!0)}j=!!ao.getFinishTs(e),W()&&(N.update(),No=!0)},render:async()=>{if(!No)return;const n=C();let o,s,i;window.DEBUG&&gl(0),_.fillStyle=Q(),_.fillRect(0,0,v.width,v.height),window.DEBUG&&hl("clear done"),o=V.worldToViewportRaw(I),s=V.worldDimToViewportRaw(E),_.fillStyle="rgba(255, 255, 255, .3)",_.fillRect(o.x,o.y,s.w,s.h),window.DEBUG&&hl("board done");const r=ao.getPiecesSortedByZIndex(e);window.DEBUG&&hl("get tiles done"),s=V.worldDimToViewportRaw(M);for(const e of r)(-1===e.owner?Mo:Do)&&(i=D[e.idx],o=V.worldToViewportRaw({x:k+e.pos.x,y:k+e.pos.y}),_.drawImage(i,0,0,i.width,i.height,o.x,o.y,s.w,s.h));window.DEBUG&&hl("tiles done");const d=[];for(const a of ao.getActivePlayers(e,n))c=a,(l===Eo||c.id!==t)&&(i=await f(a),o=V.worldToViewport(a),_.drawImage(i,o.x-g,o.y-m),q()&&d.push([`${a.name} (${a.points})`,o.x,o.y+h]));var c;_.fillStyle="white",_.textAlign="center";for(const[e,t,l]of d)_.fillText(e,t,l);window.DEBUG&&hl("players done"),a.setActivePlayers(ao.getActivePlayers(e,n)),a.setIdlePlayers(ao.getIdlePlayers(e,n)),a.setPiecesDone(ao.getFinishedPiecesCount(e)),window.DEBUG&&hl("HUD done"),W()&&N.render(),No=!1}}),{setHotkeys:e=>{B.setHotkeys(e)},onBgChange:e=>{So(yo,e),B.addEvent([sn,e])},onColorChange:e=>{So(fo,e),B.addEvent([rn,e])},onNameChange:e=>{So(vo,e),B.addEvent([dn,e])},onSoundsEnabledChange:e=>{Po(mo,e)},onSoundsVolumeChange:e=>{xo(ho,e),Y()},onShowPlayerNamesChange:e=>{Po(wo,e)},replayOnSpeedUp:oe,replayOnSpeedDown:se,replayOnPauseToggle:ie,previewImageUrl:U,player:{background:Q(),color:Z(),name:l===Eo?zo(vo,"anon"):ao.getPlayerName(e,t)||zo(vo,"anon"),soundsEnabled:K(),soundsVolume:H(),showPlayerNames:q()},game:ao.get(e),disconnect:Nn.disconnect,connect:x,unload:()=>{re.forEach((e=>{clearInterval(e)})),de&&clearTimeout(de),ce&&ce.stop()}}}var Vo=e({name:"game",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,ConnectionOverlay:_n,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _o(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,"play",this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{reconnect(){this.g.connect()},toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}}});const Oo={id:"game"},Bo={key:1,class:"overlay"},Uo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Ro={class:"menu"},$o={class:"tabs"},Go=i("🧩 Puzzles");Vo.render=function(e,i,r,d,c,u){const g=a("settings-overlay"),h=a("preview-overlay"),m=a("info-overlay"),y=a("help-overlay"),f=a("connection-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Oo,[p(n(g,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(h,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(m,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(y,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",Bo,[Uo])):o("",!0),n(f,{connectionState:e.connectionState,onReconnect:e.reconnect},null,8,["connectionState","onReconnect"]),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},null,8,["finished","duration","piecesDone","piecesTotal"]),n("div",Ro,[n("div",$o,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[Go])),_:1}),n("div",{class:"opener",onClick:i[6]||(i[6]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[7]||(i[7]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[8]||(i[8]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])};var Lo=e({name:"replay",components:{PuzzleStatus:zt,Scores:xt,SettingsOverlay:It,PreviewOverlay:Rt,InfoOverlay:Gt,HelpOverlay:$n},data:()=>({activePlayers:[],idlePlayers:[],finished:!1,duration:0,piecesDone:0,piecesTotal:0,overlay:"",connectionState:0,cuttingPuzzle:!0,g:{player:{background:"",color:"",name:"",soundsEnabled:!1,soundsVolume:100,showPlayerNames:!0},game:null,previewImageUrl:"",setHotkeys:e=>{},onBgChange:e=>{},onColorChange:e=>{},onNameChange:e=>{},onSoundsEnabledChange:e=>{},onSoundsVolumeChange:e=>{},onShowPlayerNamesChange:e=>{},replayOnSpeedUp:()=>{},replayOnSpeedDown:()=>{},replayOnPauseToggle:()=>{},connect:()=>{},disconnect:()=>{},unload:()=>{}},replay:{speed:1,paused:!1}}),async mounted(){this.$route.params.id&&(this.$watch((()=>this.g.player.background),(e=>{this.g.onBgChange(e)})),this.$watch((()=>this.g.player.color),(e=>{this.g.onColorChange(e)})),this.$watch((()=>this.g.player.name),(e=>{this.g.onNameChange(e)})),this.$watch((()=>this.g.player.soundsEnabled),(e=>{this.g.onSoundsEnabledChange(e)})),this.$watch((()=>this.g.player.soundsVolume),(e=>{this.g.onSoundsVolumeChange(e)})),this.$watch((()=>this.g.player.showPlayerNames),(e=>{this.g.onShowPlayerNamesChange(e)})),this.g=await _o(`${this.$route.params.id}`,this.$clientId,this.$config.WS_ADDRESS,Eo,this.$el,{setPuzzleCut:()=>{this.cuttingPuzzle=!1},setActivePlayers:e=>{this.activePlayers=e},setIdlePlayers:e=>{this.idlePlayers=e},setFinished:e=>{this.finished=e},setDuration:e=>{this.duration=e},setPiecesDone:e=>{this.piecesDone=e},setPiecesTotal:e=>{this.piecesTotal=e},togglePreview:()=>{this.toggle("preview",!1)},setConnectionState:e=>{this.connectionState=e},setReplaySpeed:e=>{this.replay.speed=e},setReplayPaused:e=>{this.replay.paused=e},toggleSoundsEnabled:()=>{this.g.player.soundsEnabled=!this.g.player.soundsEnabled},togglePlayerNames:()=>{this.g.player.showPlayerNames=!this.g.player.showPlayerNames}}))},unmounted(){this.g.unload(),this.g.disconnect()},methods:{toggle(e,t){""===this.overlay?(this.overlay=e,t&&this.g.setHotkeys(!1)):(this.overlay="",t&&this.g.setHotkeys(!0))}},computed:{replayText(){return"Replay-Speed: "+this.replay.speed+"x"+(this.replay.paused?" Paused":"")}}});const Fo={id:"replay"},jo={key:1,class:"overlay"},Wo=n("div",{class:"overlay-content"},[n("div",null,"⏳ Cutting puzzle, please wait... ⏳")],-1),Ho={class:"menu"},Ko={class:"tabs"},qo=i("🧩 Puzzles");Lo.render=function(e,i,d,c,u,g){const h=a("settings-overlay"),m=a("preview-overlay"),y=a("info-overlay"),f=a("help-overlay"),v=a("puzzle-status"),w=a("router-link"),b=a("scores");return s(),t("div",Fo,[p(n(h,{onBgclick:i[1]||(i[1]=t=>e.toggle("settings",!0)),modelValue:e.g.player,"onUpdate:modelValue":i[2]||(i[2]=t=>e.g.player=t)},null,8,["modelValue"]),[[x,"settings"===e.overlay]]),p(n(m,{onBgclick:i[3]||(i[3]=t=>e.toggle("preview",!1)),img:e.g.previewImageUrl},null,8,["img"]),[[x,"preview"===e.overlay]]),e.g.game?p((s(),t(y,{key:0,onBgclick:i[4]||(i[4]=t=>e.toggle("info",!0)),game:e.g.game},null,8,["game"])),[[x,"info"===e.overlay]]):o("",!0),p(n(f,{onBgclick:i[5]||(i[5]=t=>e.toggle("help",!0))},null,512),[[x,"help"===e.overlay]]),e.cuttingPuzzle?(s(),t("div",jo,[Wo])):o("",!0),n(v,{finished:e.finished,duration:e.duration,piecesDone:e.piecesDone,piecesTotal:e.piecesTotal},{default:l((()=>[n("div",null,[n("div",null,r(e.replayText),1),n("button",{class:"btn",onClick:i[6]||(i[6]=t=>e.g.replayOnSpeedUp())},"⏫"),n("button",{class:"btn",onClick:i[7]||(i[7]=t=>e.g.replayOnSpeedDown())},"⏬"),n("button",{class:"btn",onClick:i[8]||(i[8]=t=>e.g.replayOnPauseToggle())},"⏸️")])])),_:1},8,["finished","duration","piecesDone","piecesTotal"]),n("div",Ho,[n("div",Ko,[n(w,{class:"opener",to:{name:"index"},target:"_blank"},{default:l((()=>[qo])),_:1}),n("div",{class:"opener",onClick:i[9]||(i[9]=t=>e.toggle("preview",!1))},"🖼️ Preview"),n("div",{class:"opener",onClick:i[10]||(i[10]=t=>e.toggle("settings",!0))},"🛠️ Settings"),n("div",{class:"opener",onClick:i[11]||(i[11]=t=>e.toggle("info",!0))},"ℹ️ Info"),n("div",{class:"opener",onClick:i[12]||(i[12]=t=>e.toggle("help",!0))},"⌨️ Hotkeys")])]),n(b,{activePlayers:e.activePlayers,idlePlayers:e.idlePlayers},null,8,["activePlayers","idlePlayers"])])},(async()=>{const e=function(){let e=zo("ID","");return e||(e=ae.uniqId(),So("ID",e)),e}(),t=function(){let e=zo("SECRET","");return e||(e=ae.uniqId(),So("SECRET",e)),e}();O(e),B(t);const n=await _("/api/me",{}),l=await n.json(),o=await _("/api/conf",{}),a=await o.json(),s=k({history:P(),routes:[{name:"index",path:"/",component:Z},{name:"new-game",path:"/new-game",component:pt},{name:"game",path:"/g/:id",component:Vo},{name:"replay",path:"/replay/:id",component:Lo}]});s.beforeEach(((e,t)=>{t.name&&document.documentElement.classList.remove(`view-${String(t.name)}`),document.documentElement.classList.add(`view-${String(e.name)}`)}));const i=A(S);i.config.globalProperties.$me=l,i.config.globalProperties.$config=a,i.config.globalProperties.$clientId=e,i.use(s),i.mount("#app")})(); diff --git a/build/public/index.html b/build/public/index.html index 0974d69..773251f 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 5e3f14e..9ef521f 100644 --- a/build/server/main.js +++ b/build/server/main.js @@ -155,6 +155,7 @@ function encodeGame(data) { data.scoreMode, data.shapeMode, data.snapMode, + data.creatorUserId, ]; } function decodeGame(data) { @@ -170,6 +171,7 @@ function decodeGame(data) { scoreMode: data[6], shapeMode: data[7], snapMode: data[8], + creatorUserId: data[9], }; } function coordByPieceIdx(info, pieceIdx) { @@ -1358,6 +1360,7 @@ const get = (gameId, offset = 0) => { log[0][5] = DefaultScoreMode(log[0][5]); log[0][6] = DefaultShapeMode(log[0][6]); log[0][7] = DefaultSnapMode(log[0][7]); + log[0][8] = log[0][8] || null; } return log; }; @@ -1753,7 +1756,63 @@ function setDirty(gameId) { function setClean(gameId) { delete dirtyGames[gameId]; } -function loadGames() { +function loadGamesFromDb(db) { + const gameRows = db.getMany('games'); + for (const gameRow of gameRows) { + loadGameFromDb(db, gameRow.id); + } +} +function loadGameFromDb(db, gameId) { + const gameRow = db.get('games', { id: gameId }); + let game; + try { + game = JSON.parse(gameRow.data); + } + catch { + log$3.log(`[ERR] unable to load game from db ${gameId}`); + } + if (typeof game.puzzle.data.started === 'undefined') { + game.puzzle.data.started = gameRow.created; + } + if (typeof game.puzzle.data.finished === 'undefined') { + game.puzzle.data.finished = gameRow.finished; + } + if (!Array.isArray(game.players)) { + game.players = Object.values(game.players); + } + const gameObject = storeDataToGame(game, game.creator_user_id); + GameCommon.setGame(gameObject.id, gameObject); +} +function persistGamesToDb(db) { + for (const gameId of Object.keys(dirtyGames)) { + persistGameToDb(db, gameId); + } +} +function persistGameToDb(db, gameId) { + const game = GameCommon.get(gameId); + if (!game) { + log$3.error(`[ERROR] unable to persist non existing game ${gameId}`); + return; + } + if (game.id in dirtyGames) { + setClean(game.id); + } + db.upsert('games', { + id: game.id, + creator_user_id: game.creatorUserId, + image_id: game.puzzle.info.image?.id, + created: game.puzzle.data.started, + finished: game.puzzle.data.finished, + data: gameToStoreData(game) + }, { + id: game.id, + }); + log$3.info(`[INFO] persisted game ${game.id}`); +} +/** + * @deprecated + */ +function loadGamesFromDisk() { const files = fs.readdirSync(DATA_DIR); for (const f of files) { const m = f.match(/^([a-z0-9]+)\.json$/); @@ -1761,10 +1820,13 @@ function loadGames() { continue; } const gameId = m[1]; - loadGame(gameId); + loadGameFromDisk(gameId); } } -function loadGame(gameId) { +/** + * @deprecated + */ +function loadGameFromDisk(gameId) { const file = `${DATA_DIR}/${gameId}.json`; const contents = fs.readFileSync(file, 'utf-8'); let game; @@ -1786,27 +1848,21 @@ function loadGame(gameId) { if (!Array.isArray(game.players)) { game.players = Object.values(game.players); } - const gameObject = { - id: game.id, - rng: { - type: game.rng ? game.rng.type : '_fake_', - obj: game.rng ? Rng.unserialize(game.rng.obj) : new Rng(0), - }, - puzzle: game.puzzle, - players: game.players, - evtInfos: {}, - scoreMode: DefaultScoreMode(game.scoreMode), - shapeMode: DefaultShapeMode(game.shapeMode), - snapMode: DefaultSnapMode(game.snapMode), - }; + const gameObject = storeDataToGame(game, null); GameCommon.setGame(gameObject.id, gameObject); } -function persistGames() { +/** + * @deprecated + */ +function persistGamesToDisk() { for (const gameId of Object.keys(dirtyGames)) { - persistGame(gameId); + persistGameToDisk(gameId); } } -function persistGame(gameId) { +/** + * @deprecated + */ +function persistGameToDisk(gameId) { const game = GameCommon.get(gameId); if (!game) { log$3.error(`[ERROR] unable to persist non existing game ${gameId}`); @@ -1815,7 +1871,27 @@ function persistGame(gameId) { if (game.id in dirtyGames) { setClean(game.id); } - fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, JSON.stringify({ + fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, gameToStoreData(game)); + log$3.info(`[INFO] persisted game ${game.id}`); +} +function storeDataToGame(storeData, creatorUserId) { + return { + id: storeData.id, + creatorUserId, + rng: { + type: storeData.rng ? storeData.rng.type : '_fake_', + obj: storeData.rng ? Rng.unserialize(storeData.rng.obj) : new Rng(0), + }, + puzzle: storeData.puzzle, + players: storeData.players, + evtInfos: {}, + scoreMode: DefaultScoreMode(storeData.scoreMode), + shapeMode: DefaultShapeMode(storeData.shapeMode), + snapMode: DefaultSnapMode(storeData.snapMode), + }; +} +function gameToStoreData(game) { + return JSON.stringify({ id: game.id, rng: { type: game.rng.type, @@ -1826,22 +1902,27 @@ function persistGame(gameId) { scoreMode: game.scoreMode, shapeMode: game.shapeMode, snapMode: game.snapMode, - })); - log$3.info(`[INFO] persisted game ${game.id}`); + }); } var GameStorage = { - loadGames, - loadGame, - persistGames, - persistGame, + // disk functions are deprecated + loadGamesFromDisk, + loadGameFromDisk, + persistGamesToDisk, + persistGameToDisk, + loadGamesFromDb, + loadGameFromDb, + persistGamesToDb, + persistGameToDb, setDirty, }; -async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode) { +async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId) { const seed = Util.hash(gameId + ' ' + ts); const rng = new Rng(seed); return { id: gameId, + creatorUserId, rng: { type: 'Rng', obj: rng }, puzzle: await createPuzzle(rng, targetTiles, image, ts, shapeMode), players: [], @@ -1851,10 +1932,10 @@ async function createGameObject(gameId, targetTiles, image, ts, scoreMode, shape snapMode, }; } -async function createGame(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode) { - const gameObject = await createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode); +async function createGame(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId) { + const gameObject = await createGameObject(gameId, targetTiles, image, ts, scoreMode, shapeMode, snapMode, creatorUserId); GameLog.create(gameId, ts); - GameLog.log(gameId, Protocol.LOG_HEADER, 1, targetTiles, image, ts, scoreMode, shapeMode, snapMode); + GameLog.log(gameId, Protocol.LOG_HEADER, 1, targetTiles, image, ts, scoreMode, shapeMode, snapMode, gameObject.creatorUserId); GameCommon.setGame(gameObject.id, gameObject); GameStorage.setDirty(gameId); } @@ -2101,10 +2182,7 @@ const storage = multer.diskStorage({ }); const upload = multer({ storage }).single('file'); app.get('/api/me', (req, res) => { - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }); + let user = getUser(db, req); res.send({ id: user ? user.id : null, created: user ? user.created : null, @@ -2137,7 +2215,7 @@ app.get('/api/replay-data', async (req, res) => { if (offset === 0) { // also need the game game = await Game.createGameObject(gameId, log[0][2], log[0][3], // must be ImageInfo - log[0][4], log[0][5], log[0][6], log[0][7]); + log[0][4], log[0][5], log[0][6], log[0][7], log[0][8]); } res.send({ log, game: game ? Util.encodeGame(game) : null }); }); @@ -2168,6 +2246,28 @@ app.get('/api/index-data', (req, res) => { gamesFinished: games.filter(g => !!g.finished), }); }); +const getOrCreateUser = (db, req) => { + let user = getUser(db, req); + if (!user) { + db.insert('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + 'created': Time.timestamp(), + }); + user = getUser(db, req); + } + return user; +}; +const getUser = (db, req) => { + let user = db.get('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + }); + if (user) { + user.id = parseInt(user.id, 10); + } + return user; +}; const setImageTags = (db, imageId, tags) => { tags.forEach((tag) => { const slug = Util.slug(tag); @@ -2181,21 +2281,14 @@ const setImageTags = (db, imageId, tags) => { }); }; app.post('/api/save-image', express.json(), (req, res) => { - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }); - let userId = null; - if (user) { - userId = parseInt(user.id, 10); - } - else { + let user = getUser(db, req); + if (!user || !user.id) { res.status(403).send({ ok: false, error: 'forbidden' }); return; } const data = req.body; let image = db.get('images', { id: data.id }); - if (parseInt(image.uploader_user_id, 10) !== userId) { + if (parseInt(image.uploader_user_id, 10) !== user.id) { res.status(403).send({ ok: false, error: 'forbidden' }); return; } @@ -2223,24 +2316,10 @@ app.post('/api/upload', (req, res) => { log.log(err); res.status(400).send("Something went wrong!"); } - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }); - let userId = null; - if (user) { - userId = user.id; - } - else { - userId = db.insert('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - 'created': Time.timestamp(), - }); - } + const user = getOrCreateUser(db, req); const dim = await Images.getDimensions(`${UPLOAD_DIR}/${req.file.filename}`); const imageId = db.insert('images', { - uploader_user_id: userId, + uploader_user_id: user.id, filename: req.file.filename, filename_original: req.file.originalname, title: req.body.title || '', @@ -2256,12 +2335,17 @@ app.post('/api/upload', (req, res) => { }); }); app.post('/api/newgame', express.json(), async (req, res) => { + let user = getOrCreateUser(db, req); + if (!user || !user.id) { + res.status(403).send({ ok: false, error: 'forbidden' }); + return; + } const gameSettings = req.body; log.log(gameSettings); const gameId = Util.uniqId(); if (!GameCommon.exists(gameId)) { const ts = Time.timestamp(); - await Game.createGame(gameId, gameSettings.tiles, gameSettings.image, ts, gameSettings.scoreMode, gameSettings.shapeMode, gameSettings.snapMode); + await Game.createGame(gameId, gameSettings.tiles, gameSettings.image, ts, gameSettings.scoreMode, gameSettings.shapeMode, gameSettings.snapMode, user.id); } res.send({ id: gameId }); }); @@ -2343,7 +2427,7 @@ wss.on('message', async ({ socket, data }) => { log.error(e); } }); -GameStorage.loadGames(); +GameStorage.loadGamesFromDb(db); const server = app.listen(port, hostname, () => log.log(`server running on http://${hostname}:${port}`)); wss.listen(); const memoryUsageHuman = () => { @@ -2357,7 +2441,7 @@ memoryUsageHuman(); // persist games in fixed interval const persistInterval = setInterval(() => { log.log('Persisting games...'); - GameStorage.persistGames(); + GameStorage.persistGamesToDb(db); memoryUsageHuman(); }, config.persistence.interval); const gracefulShutdown = (signal) => { @@ -2365,7 +2449,7 @@ const gracefulShutdown = (signal) => { log.log('clearing persist interval...'); clearInterval(persistInterval); log.log('persisting games...'); - GameStorage.persistGames(); + GameStorage.persistGamesToDb(db); log.log('shutting down webserver...'); server.close(); log.log('shutting down websocketserver...'); diff --git a/scripts/fix_games_image_info.ts b/scripts/fix_games_image_info.ts index 559b512..49ac4ed 100644 --- a/scripts/fix_games_image_info.ts +++ b/scripts/fix_games_image_info.ts @@ -47,7 +47,7 @@ function fixOne(gameId: string) { log.log(g.puzzle.info.image.title, imageRow.id) - GameStorage.persistGame(gameId) + GameStorage.persistGameToDb(db, gameId) } else if (g.puzzle.info.image?.id) { const imageId = g.puzzle.info.image.id @@ -55,7 +55,7 @@ function fixOne(gameId: string) { log.log(g.puzzle.info.image.title, imageId) - GameStorage.persistGame(gameId) + GameStorage.persistGameToDb(db, gameId) } // fix log @@ -81,7 +81,7 @@ function fixOne(gameId: string) { } function fix() { - GameStorage.loadGames() + GameStorage.loadGamesFromDisk() GameCommon.getAllGames().forEach((game: Game) => { fixOne(game.id) }) diff --git a/scripts/fix_tiles.ts b/scripts/fix_tiles.ts index 5eb7ee9..a45b19b 100644 --- a/scripts/fix_tiles.ts +++ b/scripts/fix_tiles.ts @@ -1,11 +1,16 @@ import GameCommon from '../src/common/GameCommon' import { logger } from '../src/common/Util' +import Db from '../src/server/Db' +import { DB_FILE, DB_PATCHES_DIR } from '../src/server/Dirs' import GameStorage from '../src/server/GameStorage' const log = logger('fix_tiles.js') +const db = new Db(DB_FILE, DB_PATCHES_DIR) +db.patch(true) + function fix_tiles(gameId) { - GameStorage.loadGame(gameId) + GameStorage.loadGameFromDb(db, gameId) let changed = false const tiles = GameCommon.getPiecesSortedByZIndex(gameId) for (let tile of tiles) { @@ -27,7 +32,7 @@ function fix_tiles(gameId) { } } if (changed) { - GameStorage.persistGame(gameId) + GameStorage.persistGameToDb(db, gameId) } } diff --git a/scripts/import_games.ts b/scripts/import_games.ts new file mode 100644 index 0000000..f2e5cfa --- /dev/null +++ b/scripts/import_games.ts @@ -0,0 +1,27 @@ +import GameCommon from '../src/common/GameCommon' +import { Game } from '../src/common/Types' +import { logger } from '../src/common/Util' +import { DB_FILE, DB_PATCHES_DIR } from '../src/server/Dirs' +import Db from '../src/server/Db' +import GameStorage from '../src/server/GameStorage' + +const log = logger('import_games.ts') + +console.log(DB_FILE) + +const db = new Db(DB_FILE, DB_PATCHES_DIR) +db.patch(true) + +function run() { + GameStorage.loadGamesFromDisk() + GameCommon.getAllGames().forEach((game: Game) => { + if (!game.puzzle.info.image?.id) { + log.error(game.id + " has no image") + log.error(game.puzzle.info.image) + return + } + GameStorage.persistGameToDb(db, game.id) + }) +} + +run() diff --git a/src/common/Types.ts b/src/common/Types.ts index acf0d7b..ccbb318 100644 --- a/src/common/Types.ts +++ b/src/common/Types.ts @@ -51,6 +51,7 @@ export type EncodedGame = FixedLengthArray<[ ScoreMode, ShapeMode, SnapMode, + number|null, ]> export interface ReplayData { @@ -72,6 +73,7 @@ interface GameRng { export interface Game { id: string + creatorUserId: number|null players: Array puzzle: Puzzle evtInfos: Record diff --git a/src/common/Util.ts b/src/common/Util.ts index dbf94b6..4de6495 100644 --- a/src/common/Util.ts +++ b/src/common/Util.ts @@ -133,6 +133,7 @@ function encodeGame(data: Game): EncodedGame { data.scoreMode, data.shapeMode, data.snapMode, + data.creatorUserId, ] } @@ -149,6 +150,7 @@ function decodeGame(data: EncodedGame): Game { scoreMode: data[6], shapeMode: data[7], snapMode: data[8], + creatorUserId: data[9], } } diff --git a/src/dbpatches/04_games.sqlite b/src/dbpatches/04_games.sqlite new file mode 100644 index 0000000..edde806 --- /dev/null +++ b/src/dbpatches/04_games.sqlite @@ -0,0 +1,11 @@ +CREATE TABLE games ( + id TEXT PRIMARY KEY, + + creator_user_id INTEGER, + image_id INTEGER NOT NULL, + + created TIMESTAMP NOT NULL, + finished TIMESTAMP NOT NULL, + + data TEXT NOT NULL +); diff --git a/src/server/Game.ts b/src/server/Game.ts index 0aef26f..4b1aba2 100644 --- a/src/server/Game.ts +++ b/src/server/Game.ts @@ -16,12 +16,14 @@ async function createGameObject( ts: Timestamp, scoreMode: ScoreMode, shapeMode: ShapeMode, - snapMode: SnapMode + snapMode: SnapMode, + creatorUserId: number|null ): Promise { const seed = Util.hash(gameId + ' ' + ts) const rng = new Rng(seed) return { id: gameId, + creatorUserId, rng: { type: 'Rng', obj: rng }, puzzle: await createPuzzle(rng, targetTiles, image, ts, shapeMode), players: [], @@ -39,7 +41,8 @@ async function createGame( ts: Timestamp, scoreMode: ScoreMode, shapeMode: ShapeMode, - snapMode: SnapMode + snapMode: SnapMode, + creatorUserId: number ): Promise { const gameObject = await createGameObject( gameId, @@ -48,7 +51,8 @@ async function createGame( ts, scoreMode, shapeMode, - snapMode + snapMode, + creatorUserId ) GameLog.create(gameId, ts) @@ -61,7 +65,8 @@ async function createGame( ts, scoreMode, shapeMode, - snapMode + snapMode, + gameObject.creatorUserId ) GameCommon.setGame(gameObject.id, gameObject) diff --git a/src/server/GameLog.ts b/src/server/GameLog.ts index a8b2050..05ef870 100644 --- a/src/server/GameLog.ts +++ b/src/server/GameLog.ts @@ -90,6 +90,7 @@ const get = ( log[0][5] = DefaultScoreMode(log[0][5]) log[0][6] = DefaultShapeMode(log[0][6]) log[0][7] = DefaultSnapMode(log[0][7]) + log[0][8] = log[0][8] || null } return log } diff --git a/src/server/GameStorage.ts b/src/server/GameStorage.ts index 35d0023..b5df21a 100644 --- a/src/server/GameStorage.ts +++ b/src/server/GameStorage.ts @@ -5,6 +5,7 @@ import Util, { logger } from './../common/Util' import { Rng } from './../common/Rng' import { DATA_DIR } from './Dirs' import Time from './../common/Time' +import Db from './Db' const log = logger('GameStorage.js') @@ -15,8 +16,73 @@ function setDirty(gameId: string): void { function setClean(gameId: string): void { delete dirtyGames[gameId] } +function loadGamesFromDb(db: Db): void { + const gameRows = db.getMany('games') + for (const gameRow of gameRows) { + loadGameFromDb(db, gameRow.id) + } +} -function loadGames(): void { +function loadGameFromDb(db: Db, gameId: string): void { + const gameRow = db.get('games', {id: gameId}) + + let game + try { + game = JSON.parse(gameRow.data) + } catch { + log.log(`[ERR] unable to load game from db ${gameId}`); + } + if (typeof game.puzzle.data.started === 'undefined') { + game.puzzle.data.started = gameRow.created + } + if (typeof game.puzzle.data.finished === 'undefined') { + game.puzzle.data.finished = gameRow.finished + } + if (!Array.isArray(game.players)) { + game.players = Object.values(game.players) + } + + const gameObject: Game = storeDataToGame(game, game.creator_user_id) + GameCommon.setGame(gameObject.id, gameObject) +} + +function persistGamesToDb(db: Db): void { + for (const gameId of Object.keys(dirtyGames)) { + persistGameToDb(db, gameId) + } +} + +function persistGameToDb(db: Db, gameId: string): void { + const game: Game|null = GameCommon.get(gameId) + if (!game) { + log.error(`[ERROR] unable to persist non existing game ${gameId}`) + return + } + + if (game.id in dirtyGames) { + setClean(game.id) + } + + db.upsert('games', { + id: game.id, + + creator_user_id: game.creatorUserId, + image_id: game.puzzle.info.image?.id, + + created: game.puzzle.data.started, + finished: game.puzzle.data.finished, + + data: gameToStoreData(game) + }, { + id: game.id, + }) + log.info(`[INFO] persisted game ${game.id}`) +} + +/** + * @deprecated + */ +function loadGamesFromDisk(): void { const files = fs.readdirSync(DATA_DIR) for (const f of files) { const m = f.match(/^([a-z0-9]+)\.json$/) @@ -24,11 +90,14 @@ function loadGames(): void { continue } const gameId = m[1] - loadGame(gameId) + loadGameFromDisk(gameId) } } -function loadGame(gameId: string): void { +/** + * @deprecated + */ +function loadGameFromDisk(gameId: string): void { const file = `${DATA_DIR}/${gameId}.json` const contents = fs.readFileSync(file, 'utf-8') let game @@ -49,29 +118,23 @@ function loadGame(gameId: string): void { if (!Array.isArray(game.players)) { game.players = Object.values(game.players) } - const gameObject: Game = { - id: game.id, - rng: { - type: game.rng ? game.rng.type : '_fake_', - obj: game.rng ? Rng.unserialize(game.rng.obj) : new Rng(0), - }, - puzzle: game.puzzle, - players: game.players, - evtInfos: {}, - scoreMode: DefaultScoreMode(game.scoreMode), - shapeMode: DefaultShapeMode(game.shapeMode), - snapMode: DefaultSnapMode(game.snapMode), - } + const gameObject: Game = storeDataToGame(game, null) GameCommon.setGame(gameObject.id, gameObject) } -function persistGames(): void { +/** + * @deprecated + */ +function persistGamesToDisk(): void { for (const gameId of Object.keys(dirtyGames)) { - persistGame(gameId) + persistGameToDisk(gameId) } } -function persistGame(gameId: string): void { +/** + * @deprecated + */ +function persistGameToDisk(gameId: string): void { const game = GameCommon.get(gameId) if (!game) { log.error(`[ERROR] unable to persist non existing game ${gameId}`) @@ -81,7 +144,29 @@ function persistGame(gameId: string): void { if (game.id in dirtyGames) { setClean(game.id) } - fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, JSON.stringify({ + fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, gameToStoreData(game)) + log.info(`[INFO] persisted game ${game.id}`) +} + +function storeDataToGame(storeData: any, creatorUserId: number|null): Game { + return { + id: storeData.id, + creatorUserId, + rng: { + type: storeData.rng ? storeData.rng.type : '_fake_', + obj: storeData.rng ? Rng.unserialize(storeData.rng.obj) : new Rng(0), + }, + puzzle: storeData.puzzle, + players: storeData.players, + evtInfos: {}, + scoreMode: DefaultScoreMode(storeData.scoreMode), + shapeMode: DefaultShapeMode(storeData.shapeMode), + snapMode: DefaultSnapMode(storeData.snapMode), + } +} + +function gameToStoreData(game: Game): string { + return JSON.stringify({ id: game.id, rng: { type: game.rng.type, @@ -92,14 +177,20 @@ function persistGame(gameId: string): void { scoreMode: game.scoreMode, shapeMode: game.shapeMode, snapMode: game.snapMode, - })) - log.info(`[INFO] persisted game ${game.id}`) + }); } export default { - loadGames, - loadGame, - persistGames, - persistGame, + // disk functions are deprecated + loadGamesFromDisk, + loadGameFromDisk, + persistGamesToDisk, + persistGameToDisk, + + loadGamesFromDb, + loadGameFromDb, + persistGamesToDb, + persistGameToDb, + setDirty, } diff --git a/src/server/main.ts b/src/server/main.ts index ad29d1d..47cdaba 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -58,10 +58,7 @@ const storage = multer.diskStorage({ const upload = multer({storage}).single('file'); app.get('/api/me', (req, res): void => { - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }) + let user = getUser(db, req) res.send({ id: user ? user.id : null, created: user ? user.created : null, @@ -103,6 +100,7 @@ app.get('/api/replay-data', async (req, res): Promise => { log[0][5], log[0][6], log[0][7], + log[0][8], // creatorUserId ) } res.send({ log, game: game ? Util.encodeGame(game) : null }) @@ -144,6 +142,30 @@ interface SaveImageRequestData { tags: string[] } +const getOrCreateUser = (db: Db, req: any): any => { + let user = getUser(db, req) + if (!user) { + db.insert('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + 'created': Time.timestamp(), + }) + user = getUser(db, req) + } + return user +} + +const getUser = (db: Db, req: any): any => { + let user = db.get('users', { + 'client_id': req.headers['client-id'], + 'client_secret': req.headers['client-secret'], + }) + if (user) { + user.id = parseInt(user.id, 10) + } + return user +} + const setImageTags = (db: Db, imageId: number, tags: string[]): void => { tags.forEach((tag: string) => { const slug = Util.slug(tag) @@ -158,21 +180,15 @@ const setImageTags = (db: Db, imageId: number, tags: string[]): void => { } app.post('/api/save-image', express.json(), (req, res): void => { - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }) - let userId: number|null = null - if (user) { - userId = parseInt(user.id, 10) - } else { + let user = getUser(db, req) + if (!user || !user.id) { res.status(403).send({ ok: false, error: 'forbidden' }) return } const data = req.body as SaveImageRequestData let image = db.get('images', {id: data.id}) - if (parseInt(image.uploader_user_id, 10) !== userId) { + if (parseInt(image.uploader_user_id, 10) !== user.id) { res.status(403).send({ ok: false, error: 'forbidden' }) return } @@ -205,26 +221,13 @@ app.post('/api/upload', (req, res): void => { res.status(400).send("Something went wrong!"); } - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }) - let userId: number|null = null - if (user) { - userId = user.id - } else { - userId = db.insert('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - 'created': Time.timestamp(), - }) as number - } + const user = getOrCreateUser(db, req) const dim = await Images.getDimensions( `${UPLOAD_DIR}/${req.file.filename}` ) const imageId = db.insert('images', { - uploader_user_id: userId, + uploader_user_id: user.id, filename: req.file.filename, filename_original: req.file.originalname, title: req.body.title || '', @@ -243,6 +246,12 @@ app.post('/api/upload', (req, res): void => { }) app.post('/api/newgame', express.json(), async (req, res): Promise => { + let user = getOrCreateUser(db, req) + if (!user || !user.id) { + res.status(403).send({ ok: false, error: 'forbidden' }) + return + } + const gameSettings = req.body as GameSettings log.log(gameSettings) const gameId = Util.uniqId() @@ -256,6 +265,7 @@ app.post('/api/newgame', express.json(), async (req, res): Promise => { gameSettings.scoreMode, gameSettings.shapeMode, gameSettings.snapMode, + user.id, ) } res.send({ id: gameId }) @@ -355,7 +365,7 @@ wss.on('message', async ( } }) -GameStorage.loadGames() +GameStorage.loadGamesFromDb(db) const server = app.listen( port, hostname, @@ -378,7 +388,7 @@ memoryUsageHuman() // persist games in fixed interval const persistInterval = setInterval(() => { log.log('Persisting games...') - GameStorage.persistGames() + GameStorage.persistGamesToDb(db) memoryUsageHuman() }, config.persistence.interval) @@ -390,7 +400,7 @@ const gracefulShutdown = (signal: string): void => { clearInterval(persistInterval) log.log('persisting games...') - GameStorage.persistGames() + GameStorage.persistGamesToDb(db) log.log('shutting down webserver...') server.close() From e7f86b5ef8879355915355362d2842f7f8f647be Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Thu, 15 Jul 2021 23:10:27 +0200 Subject: [PATCH 14/17] cleanup --- src/server/Game.ts | 42 ++++++++++--------- src/server/GameLog.ts | 2 +- src/server/GameStorage.ts | 34 ++------------- src/server/Images.ts | 17 +++++++- src/server/Users.ts | 36 ++++++++++++++++ src/server/main.ts | 88 ++++++++------------------------------- 6 files changed, 95 insertions(+), 124 deletions(-) create mode 100644 src/server/Users.ts diff --git a/src/server/Game.ts b/src/server/Game.ts index 4b1aba2..2eb5ae0 100644 --- a/src/server/Game.ts +++ b/src/server/Game.ts @@ -1,5 +1,5 @@ import GameCommon from './../common/GameCommon' -import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode,ImageInfo, Timestamp } from './../common/Types' +import { Change, Game, Input, ScoreMode, ShapeMode, SnapMode,ImageInfo, Timestamp, GameSettings } from './../common/Types' import Util, { logger } from './../common/Util' import { Rng } from './../common/Rng' import GameLog from './GameLog' @@ -34,24 +34,24 @@ async function createGameObject( } } -async function createGame( - gameId: string, - targetTiles: number, - image: ImageInfo, +async function createNewGame( + gameSettings: GameSettings, ts: Timestamp, - scoreMode: ScoreMode, - shapeMode: ShapeMode, - snapMode: SnapMode, creatorUserId: number -): Promise { +): Promise { + let gameId; + do { + gameId = Util.uniqId() + } while (GameCommon.exists(gameId)) + const gameObject = await createGameObject( gameId, - targetTiles, - image, + gameSettings.tiles, + gameSettings.image, ts, - scoreMode, - shapeMode, - snapMode, + gameSettings.scoreMode, + gameSettings.shapeMode, + gameSettings.snapMode, creatorUserId ) @@ -60,17 +60,19 @@ async function createGame( gameId, Protocol.LOG_HEADER, 1, - targetTiles, - image, + gameSettings.tiles, + gameSettings.image, ts, - scoreMode, - shapeMode, - snapMode, + gameSettings.scoreMode, + gameSettings.shapeMode, + gameSettings.snapMode, gameObject.creatorUserId ) GameCommon.setGame(gameObject.id, gameObject) GameStorage.setDirty(gameId) + + return gameId } function addPlayer(gameId: string, playerId: string, ts: Timestamp): void { @@ -105,7 +107,7 @@ function handleInput( export default { createGameObject, - createGame, + createNewGame, addPlayer, handleInput, } diff --git a/src/server/GameLog.ts b/src/server/GameLog.ts index 05ef870..ec7a898 100644 --- a/src/server/GameLog.ts +++ b/src/server/GameLog.ts @@ -90,7 +90,7 @@ const get = ( log[0][5] = DefaultScoreMode(log[0][5]) log[0][6] = DefaultShapeMode(log[0][6]) log[0][7] = DefaultSnapMode(log[0][7]) - log[0][8] = log[0][8] || null + log[0][8] = log[0][8] || null // creatorUserId } return log } diff --git a/src/server/GameStorage.ts b/src/server/GameStorage.ts index b5df21a..4b2de65 100644 --- a/src/server/GameStorage.ts +++ b/src/server/GameStorage.ts @@ -41,7 +41,7 @@ function loadGameFromDb(db: Db, gameId: string): void { if (!Array.isArray(game.players)) { game.players = Object.values(game.players) } - + const gameObject: Game = storeDataToGame(game, game.creator_user_id) GameCommon.setGame(gameObject.id, gameObject) } @@ -122,32 +122,6 @@ function loadGameFromDisk(gameId: string): void { GameCommon.setGame(gameObject.id, gameObject) } -/** - * @deprecated - */ -function persistGamesToDisk(): void { - for (const gameId of Object.keys(dirtyGames)) { - persistGameToDisk(gameId) - } -} - -/** - * @deprecated - */ -function persistGameToDisk(gameId: string): void { - const game = GameCommon.get(gameId) - if (!game) { - log.error(`[ERROR] unable to persist non existing game ${gameId}`) - return - } - - if (game.id in dirtyGames) { - setClean(game.id) - } - fs.writeFileSync(`${DATA_DIR}/${game.id}.json`, gameToStoreData(game)) - log.info(`[INFO] persisted game ${game.id}`) -} - function storeDataToGame(storeData: any, creatorUserId: number|null): Game { return { id: storeData.id, @@ -181,16 +155,14 @@ function gameToStoreData(game: Game): string { } export default { - // disk functions are deprecated + // disk functions are deprecated loadGamesFromDisk, loadGameFromDisk, - persistGamesToDisk, - persistGameToDisk, loadGamesFromDb, loadGameFromDb, persistGamesToDb, persistGameToDb, - + setDirty, } diff --git a/src/server/Images.ts b/src/server/Images.ts index dd46e07..7632b2a 100644 --- a/src/server/Images.ts +++ b/src/server/Images.ts @@ -6,7 +6,7 @@ import sharp from 'sharp' import {UPLOAD_DIR, UPLOAD_URL} from './Dirs' import Db, { OrderBy, WhereRaw } from './Db' import { Dim } from '../common/Geometry' -import { logger } from '../common/Util' +import Util, { logger } from '../common/Util' import { Tag, ImageInfo } from '../common/Types' const log = logger('Images.ts') @@ -209,6 +209,20 @@ async function getDimensions(imagePath: string): Promise { } } +const setTags = (db: Db, imageId: number, tags: string[]): void => { + db.delete('image_x_category', { image_id: imageId }) + tags.forEach((tag: string) => { + const slug = Util.slug(tag) + const id = db.upsert('categories', { slug, title: tag }, { slug }, 'id') + if (id) { + db.insert('image_x_category', { + image_id: imageId, + category_id: id, + }) + } + }) +} + export default { allImagesFromDisk, imageFromDb, @@ -216,4 +230,5 @@ export default { getAllTags, resizeImage, getDimensions, + setTags, } diff --git a/src/server/Users.ts b/src/server/Users.ts new file mode 100644 index 0000000..4c5fb00 --- /dev/null +++ b/src/server/Users.ts @@ -0,0 +1,36 @@ +import Time from '../common/Time' +import Db from './Db' + +const TABLE = 'users' + +const HEADER_CLIENT_ID = 'client-id' +const HEADER_CLIENT_SECRET = 'client-secret' + +const getOrCreateUser = (db: Db, req: any): any => { + let user = getUser(db, req) + if (!user) { + db.insert(TABLE, { + 'client_id': req.headers[HEADER_CLIENT_ID], + 'client_secret': req.headers[HEADER_CLIENT_SECRET], + 'created': Time.timestamp(), + }) + user = getUser(db, req) + } + return user +} + +const getUser = (db: Db, req: any): any => { + const user = db.get(TABLE, { + 'client_id': req.headers[HEADER_CLIENT_ID], + 'client_secret': req.headers[HEADER_CLIENT_SECRET], + }) + if (user) { + user.id = parseInt(user.id, 10) + } + return user +} + +export default { + getOrCreateUser, + getUser, +} diff --git a/src/server/main.ts b/src/server/main.ts index 47cdaba..8242b21 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -22,6 +22,7 @@ import GameCommon from '../common/GameCommon' import { ServerEvent, Game as GameType, GameSettings } from '../common/Types' import GameStorage from './GameStorage' import Db from './Db' +import Users from './Users' const db = new Db(DB_FILE, DB_PATCHES_DIR) db.patch() @@ -58,7 +59,7 @@ const storage = multer.diskStorage({ const upload = multer({storage}).single('file'); app.get('/api/me', (req, res): void => { - let user = getUser(db, req) + let user = Users.getUser(db, req) res.send({ id: user ? user.id : null, created: user ? user.created : null, @@ -142,52 +143,15 @@ interface SaveImageRequestData { tags: string[] } -const getOrCreateUser = (db: Db, req: any): any => { - let user = getUser(db, req) - if (!user) { - db.insert('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - 'created': Time.timestamp(), - }) - user = getUser(db, req) - } - return user -} - -const getUser = (db: Db, req: any): any => { - let user = db.get('users', { - 'client_id': req.headers['client-id'], - 'client_secret': req.headers['client-secret'], - }) - if (user) { - user.id = parseInt(user.id, 10) - } - return user -} - -const setImageTags = (db: Db, imageId: number, tags: string[]): void => { - tags.forEach((tag: string) => { - const slug = Util.slug(tag) - const id = db.upsert('categories', { slug, title: tag }, { slug }, 'id') - if (id) { - db.insert('image_x_category', { - image_id: imageId, - category_id: id, - }) - } - }) -} - app.post('/api/save-image', express.json(), (req, res): void => { - let user = getUser(db, req) + const user = Users.getUser(db, req) if (!user || !user.id) { res.status(403).send({ ok: false, error: 'forbidden' }) return } const data = req.body as SaveImageRequestData - let image = db.get('images', {id: data.id}) + const image = db.get('images', {id: data.id}) if (parseInt(image.uploader_user_id, 10) !== user.id) { res.status(403).send({ ok: false, error: 'forbidden' }) return @@ -199,11 +163,7 @@ app.post('/api/save-image', express.json(), (req, res): void => { id: data.id, }) - db.delete('image_x_category', { image_id: data.id }) - - if (data.tags) { - setImageTags(db, data.id, data.tags) - } + Images.setTags(db, data.id, data.tags || []) res.send({ ok: true }) }) @@ -211,17 +171,19 @@ app.post('/api/upload', (req, res): void => { upload(req, res, async (err: any): Promise => { if (err) { log.log(err) - res.status(400).send("Something went wrong!"); + res.status(400).send("Something went wrong!") + return } try { await Images.resizeImage(req.file.filename) } catch (err) { log.log(err) - res.status(400).send("Something went wrong!"); + res.status(400).send("Something went wrong!") + return } - const user = getOrCreateUser(db, req) + const user = Users.getOrCreateUser(db, req) const dim = await Images.getDimensions( `${UPLOAD_DIR}/${req.file.filename}` @@ -238,7 +200,7 @@ app.post('/api/upload', (req, res): void => { if (req.body.tags) { const tags = req.body.tags.split(',').filter((tag: string) => !!tag) - setImageTags(db, imageId as number, tags) + Images.setTags(db, imageId as number, tags) } res.send(Images.imageFromDb(db, imageId as number)) @@ -246,28 +208,12 @@ app.post('/api/upload', (req, res): void => { }) app.post('/api/newgame', express.json(), async (req, res): Promise => { - let user = getOrCreateUser(db, req) - if (!user || !user.id) { - res.status(403).send({ ok: false, error: 'forbidden' }) - return - } - - const gameSettings = req.body as GameSettings - log.log(gameSettings) - const gameId = Util.uniqId() - if (!GameCommon.exists(gameId)) { - const ts = Time.timestamp() - await Game.createGame( - gameId, - gameSettings.tiles, - gameSettings.image, - ts, - gameSettings.scoreMode, - gameSettings.shapeMode, - gameSettings.snapMode, - user.id, - ) - } + const user = Users.getOrCreateUser(db, req) + const gameId = await Game.createNewGame( + req.body as GameSettings, + Time.timestamp(), + user.id + ) res.send({ id: gameId }) }) From b4980e367cc8ecae10fb6e6b5ae18ff5b51139f6 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Thu, 15 Jul 2021 23:59:25 +0200 Subject: [PATCH 15/17] fix wording --- src/frontend/components/NewGameDialog.vue | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/frontend/components/NewGameDialog.vue b/src/frontend/components/NewGameDialog.vue index 731c71f..eff46a7 100644 --- a/src/frontend/components/NewGameDialog.vue +++ b/src/frontend/components/NewGameDialog.vue @@ -35,20 +35,20 @@ Normal
+ Any (Flat pieces can occur anywhere)
+ Flat (All pieces flat on all sides) + Normal (Pieces snap to final destination and to each other)
+ Real (Pieces snap only to corners, already snapped pieces and to each other) From bf4897bf83f0a777180c9ca7cee2fb04007332c4 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Fri, 16 Jul 2021 00:05:50 +0200 Subject: [PATCH 16/17] fix type hint --- src/frontend/views/Replay.vue | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/frontend/views/Replay.vue b/src/frontend/views/Replay.vue index 1bf775a..97ec422 100644 --- a/src/frontend/views/Replay.vue +++ b/src/frontend/views/Replay.vue @@ -49,7 +49,7 @@ import InfoOverlay from './../components/InfoOverlay.vue' import HelpOverlay from './../components/HelpOverlay.vue' import { main, MODE_REPLAY } from './../game' -import { Player } from '../../common/Types' +import { Game, Player } from '../../common/Types' export default defineComponent({ name: 'replay', From 68a267bd70666e784129e25275ed7d1d2720abd9 Mon Sep 17 00:00:00 2001 From: Zutatensuppe Date: Sun, 10 Oct 2021 12:09:50 +0200 Subject: [PATCH 17/17] only watch build dir --- scripts/server | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/server b/scripts/server index 182e3a4..4d1a1c9 100755 --- a/scripts/server +++ b/scripts/server @@ -1,4 +1,4 @@ #!/bin/sh # server for built files -nodemon --max-old-space-size=64 -e js build/server/main.js -c config.json +nodemon --watch build --max-old-space-size=64 -e js build/server/main.js -c config.json