diff --git a/assets/index-c2262c42.js b/assets/index-c2262c42.js deleted file mode 100644 index beae6a2..0000000 --- a/assets/index-c2262c42.js +++ /dev/null @@ -1,25 +0,0 @@ -var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value);(function(){const relList=document.createElement("link").relList;if(relList&&relList.supports&&relList.supports("modulepreload"))return;for(const link of document.querySelectorAll('link[rel="modulepreload"]'))processPreload(link);new MutationObserver(mutations=>{for(const mutation of mutations)if(mutation.type==="childList")for(const node of mutation.addedNodes)node.tagName==="LINK"&&node.rel==="modulepreload"&&processPreload(node)}).observe(document,{childList:!0,subtree:!0});function getFetchOpts(link){const fetchOpts={};return link.integrity&&(fetchOpts.integrity=link.integrity),link.referrerPolicy&&(fetchOpts.referrerPolicy=link.referrerPolicy),link.crossOrigin==="use-credentials"?fetchOpts.credentials="include":link.crossOrigin==="anonymous"?fetchOpts.credentials="omit":fetchOpts.credentials="same-origin",fetchOpts}function processPreload(link){if(link.ep)return;link.ep=!0;const fetchOpts=getFetchOpts(link);fetch(link.href,fetchOpts)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};/*! ***************************************************************************** -Copyright (C) Microsoft. All rights reserved. -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 - -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. - -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */var Reflect2;(function(Reflect3){(function(factory){var root=typeof commonjsGlobal=="object"?commonjsGlobal:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),exporter=makeExporter(Reflect3);typeof root.Reflect>"u"?root.Reflect=Reflect3:exporter=makeExporter(root.Reflect,exporter),factory(exporter);function makeExporter(target,previous){return function(key,value){typeof target[key]!="function"&&Object.defineProperty(target,key,{configurable:!0,writable:!0,value}),previous&&previous(key,value)}}})(function(exporter){var hasOwn=Object.prototype.hasOwnProperty,supportsSymbol=typeof Symbol=="function",toPrimitiveSymbol=supportsSymbol&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",iteratorSymbol=supportsSymbol&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",supportsCreate=typeof Object.create=="function",supportsProto={__proto__:[]}instanceof Array,downLevel=!supportsCreate&&!supportsProto,HashMap={create:supportsCreate?function(){return MakeDictionary(Object.create(null))}:supportsProto?function(){return MakeDictionary({__proto__:null})}:function(){return MakeDictionary({})},has:downLevel?function(map,key){return hasOwn.call(map,key)}:function(map,key){return key in map},get:downLevel?function(map,key){return hasOwn.call(map,key)?map[key]:void 0}:function(map,key){return map[key]}},functionPrototype=Object.getPrototypeOf(Function),usePolyfill=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",_Map=!usePolyfill&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:CreateMapPolyfill(),_Set=!usePolyfill&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:CreateSetPolyfill(),_WeakMap=!usePolyfill&&typeof WeakMap=="function"?WeakMap:CreateWeakMapPolyfill(),Metadata=new _WeakMap;function decorate(decorators,target,propertyKey,attributes){if(IsUndefined(propertyKey)){if(!IsArray(decorators))throw new TypeError;if(!IsConstructor(target))throw new TypeError;return DecorateConstructor(decorators,target)}else{if(!IsArray(decorators))throw new TypeError;if(!IsObject(target))throw new TypeError;if(!IsObject(attributes)&&!IsUndefined(attributes)&&!IsNull(attributes))throw new TypeError;return IsNull(attributes)&&(attributes=void 0),propertyKey=ToPropertyKey(propertyKey),DecorateProperty(decorators,target,propertyKey,attributes)}}exporter("decorate",decorate);function metadata(metadataKey,metadataValue){function decorator(target,propertyKey){if(!IsObject(target))throw new TypeError;if(!IsUndefined(propertyKey)&&!IsPropertyKey(propertyKey))throw new TypeError;OrdinaryDefineOwnMetadata(metadataKey,metadataValue,target,propertyKey)}return decorator}exporter("metadata",metadata);function defineMetadata(metadataKey,metadataValue,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryDefineOwnMetadata(metadataKey,metadataValue,target,propertyKey)}exporter("defineMetadata",defineMetadata);function hasMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryHasMetadata(metadataKey,target,propertyKey)}exporter("hasMetadata",hasMetadata);function hasOwnMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryHasOwnMetadata(metadataKey,target,propertyKey)}exporter("hasOwnMetadata",hasOwnMetadata);function getMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryGetMetadata(metadataKey,target,propertyKey)}exporter("getMetadata",getMetadata);function getOwnMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryGetOwnMetadata(metadataKey,target,propertyKey)}exporter("getOwnMetadata",getOwnMetadata);function getMetadataKeys(target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryMetadataKeys(target,propertyKey)}exporter("getMetadataKeys",getMetadataKeys);function getOwnMetadataKeys(target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryOwnMetadataKeys(target,propertyKey)}exporter("getOwnMetadataKeys",getOwnMetadataKeys);function deleteMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey));var metadataMap=GetOrCreateMetadataMap(target,propertyKey,!1);if(IsUndefined(metadataMap)||!metadataMap.delete(metadataKey))return!1;if(metadataMap.size>0)return!0;var targetMetadata=Metadata.get(target);return targetMetadata.delete(propertyKey),targetMetadata.size>0||Metadata.delete(target),!0}exporter("deleteMetadata",deleteMetadata);function DecorateConstructor(decorators,target){for(var i=decorators.length-1;i>=0;--i){var decorator=decorators[i],decorated=decorator(target);if(!IsUndefined(decorated)&&!IsNull(decorated)){if(!IsConstructor(decorated))throw new TypeError;target=decorated}}return target}function DecorateProperty(decorators,target,propertyKey,descriptor){for(var i=decorators.length-1;i>=0;--i){var decorator=decorators[i],decorated=decorator(target,propertyKey,descriptor);if(!IsUndefined(decorated)&&!IsNull(decorated)){if(!IsObject(decorated))throw new TypeError;descriptor=decorated}}return descriptor}function GetOrCreateMetadataMap(O,P,Create){var targetMetadata=Metadata.get(O);if(IsUndefined(targetMetadata)){if(!Create)return;targetMetadata=new _Map,Metadata.set(O,targetMetadata)}var metadataMap=targetMetadata.get(P);if(IsUndefined(metadataMap)){if(!Create)return;metadataMap=new _Map,targetMetadata.set(P,metadataMap)}return metadataMap}function OrdinaryHasMetadata(MetadataKey,O,P){var hasOwn2=OrdinaryHasOwnMetadata(MetadataKey,O,P);if(hasOwn2)return!0;var parent=OrdinaryGetPrototypeOf(O);return IsNull(parent)?!1:OrdinaryHasMetadata(MetadataKey,parent,P)}function OrdinaryHasOwnMetadata(MetadataKey,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!1);return IsUndefined(metadataMap)?!1:ToBoolean(metadataMap.has(MetadataKey))}function OrdinaryGetMetadata(MetadataKey,O,P){var hasOwn2=OrdinaryHasOwnMetadata(MetadataKey,O,P);if(hasOwn2)return OrdinaryGetOwnMetadata(MetadataKey,O,P);var parent=OrdinaryGetPrototypeOf(O);if(!IsNull(parent))return OrdinaryGetMetadata(MetadataKey,parent,P)}function OrdinaryGetOwnMetadata(MetadataKey,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!1);if(!IsUndefined(metadataMap))return metadataMap.get(MetadataKey)}function OrdinaryDefineOwnMetadata(MetadataKey,MetadataValue,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!0);metadataMap.set(MetadataKey,MetadataValue)}function OrdinaryMetadataKeys(O,P){var ownKeys=OrdinaryOwnMetadataKeys(O,P),parent=OrdinaryGetPrototypeOf(O);if(parent===null)return ownKeys;var parentKeys=OrdinaryMetadataKeys(parent,P);if(parentKeys.length<=0)return ownKeys;if(ownKeys.length<=0)return parentKeys;for(var set=new _Set,keys=[],_i=0,ownKeys_1=ownKeys;_i=0&&index=this._keys.length?(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel):this._index++,{value:result,done:!1}}return{value:void 0,done:!0}},MapIterator2.prototype.throw=function(error){throw this._index>=0&&(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel),error},MapIterator2.prototype.return=function(value){return this._index>=0&&(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel),{value,done:!0}},MapIterator2}();return function(){function Map2(){this._keys=[],this._values=[],this._cacheKey=cacheSentinel,this._cacheIndex=-2}return Object.defineProperty(Map2.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Map2.prototype.has=function(key){return this._find(key,!1)>=0},Map2.prototype.get=function(key){var index=this._find(key,!1);return index>=0?this._values[index]:void 0},Map2.prototype.set=function(key,value){var index=this._find(key,!0);return this._values[index]=value,this},Map2.prototype.delete=function(key){var index=this._find(key,!1);if(index>=0){for(var size=this._keys.length,i=index+1;i{const canvas=document.createElement("canvas"),ctx=canvas.getContext("2d",{desynchronized:!1,alpha:!0,willReadFrequently:!1});return id&&(canvas.id=id),[canvas,ctx]},catImg=document.createElement("img");catImg.src=cat;const dogImg=document.createElement("img");dogImg.src=dog;const lionImg=document.createElement("img");lionImg.src=lion;const duckImg=document.createElement("img");duckImg.src=duck;const mouseImg=document.createElement("img");mouseImg.src=mouse;const rabbitImg=document.createElement("img");rabbitImg.src=rabbit;const images={cat:catImg,dog:dogImg,lion:lionImg,duck:duckImg,mouse:mouseImg,rabbit:rabbitImg},ROOT=document.querySelector("#root"),[bgCanvas,bgCtx]=createCanvas("bg"),[gameCanvas,gameCtx]=createCanvas("game"),[effectCanvas,effectCtx]=createCanvas("effect"),[scoreCanvas,scoreCtx]=createCanvas("score"),[selectCanvas,selectCtx]=createCanvas("select");bgCtx.translate(.5,.5);gameCtx.translate(.5,.5);effectCtx.translate(.5,.5);scoreCtx.translate(.5,.5);selectCtx.translate(.5,.5);const isMobile=window.navigator.userAgent.match(/android|mobile/gi),SUB_OPTIONS={SIZE:{RATIO:1}},OPTIONS={SIZE:{UNIT:50},WIDTH:{GAME:{X:9,Y:9}},ANIMATION:{SPEED:isMobile?.5:.1,FRAME:16},GAME:{TURN:50}},RESPONSIVE_UNIT_SIZE=()=>OPTIONS.SIZE.UNIT+SUB_OPTIONS.SIZE.RATIO,BG_COLOR="#dddddd",wait=[],RUN_MODE={}.VITE_RUN_MODE||"none",STORE_NAME="pang_store",BASE_TYPE_SCORE=[["dog",1],["cat",2],["duck",3],["mouse",4],["lion",5]],TestCase2=[["dog","dog","dog","lion","lion","mouse","dog","mouse","cat"],["dog","dog","dog","mouse","dog","lion","lion","lion","mouse"],["dog","lion","lion","lion","dog","dog","mouse","dog","mouse"],["dog","dog","dog","lion","lion","mouse","dog","mouse","cat"],["dog","dog","lion","dog","mouse","dog","mouse","cat","lion"],["dog","mouse","mouse","mouse","dog","dog","lion","mouse","cat"],["mouse","lion","dog","dog","lion","dog","dog","mouse","mouse"],["mouse","lion","dog","dog","lion","dog","mouse","mouse","mouse"],["dog","lion","lion","mouse","dog","mouse","cat","cat","cat"]];class Logger{constructor(name){__publicField(this,"name","SYS");__publicField(this,"_logger",console);__publicField(this,"directories",[]);__publicField(this,"only",()=>new Logger(this.name+":only"));this.name=name}convert(color,...data){}reform(str){return`[${str}] >`}dir(dir){return this.directories.push(dir),this}log(...data){this.convert("yellowBright",...data),this.clearDir()}debug(...data){this.convert("blueBright",...data),this.clearDir()}error(...data){this.convert("redBright",...data),this.clearDir()}clearDir(){this.directories=[]}}class BaseModule{constructor(mode){__publicField(this,"mode","none");this.mode=mode}}class Animator extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode)}}const capitalize=str=>str.charAt(0).toLowerCase()+str.slice(1),responseBlockAxis=(x,y)=>{const centerX=innerWidth/2,centerY=innerHeight/2,horizonValue=OPTIONS.WIDTH.GAME.X*RESPONSIVE_UNIT_SIZE(),verticalValue=OPTIONS.WIDTH.GAME.Y*RESPONSIVE_UNIT_SIZE(),halfHorizon=horizonValue/2,halfVertical=verticalValue/2,resX=centerX+x-halfHorizon,resY=centerY+y-halfVertical;return[resX,resY]},responsePointerAxis=(x,y)=>{const centerX=innerWidth/2,centerY=innerHeight/2,horizonValue=OPTIONS.WIDTH.GAME.X*RESPONSIVE_UNIT_SIZE(),verticalValue=OPTIONS.WIDTH.GAME.Y*RESPONSIVE_UNIT_SIZE(),halfHorizon=horizonValue/2,halfVertical=verticalValue/2,unitCenterX=Math.floor((x-centerX+halfHorizon)/RESPONSIVE_UNIT_SIZE()),unitCenterY=Math.floor((y-centerY+halfVertical)/RESPONSIVE_UNIT_SIZE());return[unitCenterX,unitCenterY]},_Cell=class _Cell{constructor(type,x,y,score){__publicField(this,"id");__publicField(this,"type");__publicField(this,"x");__publicField(this,"y");__publicField(this,"matched");__publicField(this,"isPang");__publicField(this,"score");__publicField(this,"isSelected");__publicField(this,"isHover");__publicField(this,"logger");this.id=_Cell.autoIncrement,this.type=type,this.x=x,this.y=y,this.matched=!1,this.isPang=!1,this.score=score,this.isSelected=!1,this.isHover=!1,_Cell.autoIncrement++,this.logger=new Logger("Cell")}getDirectionWith(dstCell){const srcX=this.x,srcY=this.y,dstX=dstCell.x,dstY=dstCell.y;return this.logger.dir("getDirectionWith").log(srcX,srcY,dstX,dstY),dstX>srcX?(this.logger.dir("getDirectionWith").log("오른쪽으로 스왑"),"right"):dstXsrcY?(this.logger.dir("getDirectionWith").log("아래쪽으로 스왑"),"down"):dstYresolver=resolve),fromX=this.x,toX=to,direction=fromX!==to&&fromX>to,move=setInterval(()=>{this.x+=fromX>to?-OPTIONS.ANIMATION.SPEED/2:OPTIONS.ANIMATION.SPEED/2,direction?toX>=this.x&&(clearInterval(move),resolver(!0),this.x=fromX):toX<=this.x&&(clearInterval(move),resolver(!0),this.x=fromX)},OPTIONS.ANIMATION.FRAME);return promise}moveY(to){let resolver;const promise=new Promise(resolve=>resolver=resolve),fromY=this.y,toY=to,direction=fromY!==to&&fromY>to,move=setInterval(()=>{this.y+=fromY>to?-OPTIONS.ANIMATION.SPEED/2:OPTIONS.ANIMATION.SPEED/2,direction?toY>=this.y&&(clearInterval(move),this.y=fromY,resolver(this)):toY<=this.y&&(clearInterval(move),this.y=fromY,resolver(this))},OPTIONS.ANIMATION.FRAME);return promise}swapEffect(target,direction){let resolver;const promise=new Promise(resolve=>resolver=resolve);switch(this.x,this.y,target.x,target.y,direction){case"left":case"right":Promise.all([this.moveX(target.x),target.moveX(this.x)]).then(()=>{resolver(!0)});break;case"up":case"down":Promise.all([this.moveY(target.y),target.moveY(this.y)]).then(()=>{resolver(!0)});break;default:setTimeout(()=>{resolver(!1)},0);break}return this.logger.dir("swapEffect").debug(`from ${this.type} to ${target.type} swapping...`),promise}pang(){this.type="",this.isPang=!0}highlight(type){const[x,y]=responseBlockAxis(this.x*RESPONSIVE_UNIT_SIZE(),this.y*RESPONSIVE_UNIT_SIZE());switch(type){case"hover":selectCtx.fillStyle="#56565656";break;case"select":selectCtx.fillStyle="#48c46e56";break}selectCtx.fillRect(x,y,RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())}render(){const[x,y]=responseBlockAxis(this.x,this.y),image=images[this.type];image?(gameCtx.imageSmoothingQuality="low",gameCtx.imageSmoothingEnabled=!0,gameCtx.drawImage(image,Math.floor(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x)),Math.floor(this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y)),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())):(gameCtx.fillStyle="#00000000",gameCtx.fillRect(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())),this.isSelected&&this.highlight("select")}renderOtherCanvas(ctx){const[x,y]=responseBlockAxis(this.x,this.y),image=images[this.type];image?ctx.drawImage(image,this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE()):(ctx.fillStyle="#00000000",ctx.fillRect(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE()))}static copy(cell,toCell){return new _Cell(cell.type,toCell.x,toCell.y,cell.score)}deepCopySelf(){return new _Cell(this.type,this.x,this.y,this.score)}deepCopy(cell){return new _Cell(cell.type,cell.x,cell.y,cell.score)}deepCopyWithAxis(cell,x,y){return new _Cell(cell.type,x,y,cell.score)}};__publicField(_Cell,"autoIncrement",0);let Cell=_Cell;class BlockManager extends BaseModule{constructor(mode,scoreCalculator){super(mode);__publicField(this,"types",BASE_TYPE_SCORE);__publicField(this,"logger");__publicField(this,"blockSize",{x:50,y:50});__publicField(this,"map",[]);__publicField(this,"scoreCalculator");this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),this.scoreCalculator=scoreCalculator}scoreUp(score){this.scoreCalculator.scoreUp(score)}initialize(){if(this.mode!=="test"){const map=this.createMap([OPTIONS.WIDTH.GAME.X,OPTIONS.WIDTH.GAME.Y]);return this.logger.dir("initialize").log("created map",map),this.map=map,map}else{if(TestCase2.length!==OPTIONS.WIDTH.GAME.Y||TestCase2[0].length!==OPTIONS.WIDTH.GAME.X)throw new Error("Invalid map size");const map=this.createCustomMap(TestCase2);return this.logger.dir("initialize").log("created custom map",map),this.map=map,map}}getCellScoreByType(type){const index=this.types.findIndex(typeScore=>typeScore[0]===type);return this.types[index][1]}getRandomCellType(){const randomTypeIndex=Math.floor(Math.random()*this.types.length);return this.types[randomTypeIndex]}createMap([xSize,ySize]){const maps=[];for(let y=0;yrow.map((cell,x)=>new Cell(cell,x,y,this.getCellScoreByType(cell))))}isInBoundary(srcCell,dstCell){var _a,_b,_c,_d;this.logger.dir("isInBoundary").debug("srcCell","dstCell",srcCell,dstCell);const srcX=srcCell==null?void 0:srcCell.x,srcY=srcCell==null?void 0:srcCell.y;if(srcX===void 0||srcY===void 0)return!1;const topCell=(_a=this.map[srcY-1])==null?void 0:_a[srcX],bottomCell=(_b=this.map[srcY+1])==null?void 0:_b[srcX],leftCell=(_c=this.map[srcY])==null?void 0:_c[srcX-1],rightCell=(_d=this.map[srcY])==null?void 0:_d[srcX+1],isIn=topCell===dstCell||bottomCell===dstCell||leftCell===dstCell||rightCell===dstCell;return this.logger.dir("swapBothCell").dir("isInBoundary").debug(isIn),isIn}inLinePang(srcCell,dstCell,direction){this.logger.dir("inLinePang").debug("validating pangable line by dst cell.");const horizonPangList=[],verticalPangList=[];if(direction==="left"){const upSrcLinePang=this.upLinePang(srcCell),downSrcLinePang=this.downLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),upDstLinePang=this.upLinePang(dstCell),downDstLinePang=this.downLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),concatSrcUpDown=[...new Set([...upSrcLinePang,...downSrcLinePang])],concatDstUpDown=[...new Set([...upDstLinePang,...downDstLinePang])],concatSrcLeft=[...new Set(leftSrcLinePang)],concatDstRight=[...new Set(rightDstLinePang)];concatSrcUpDown.length>2&&verticalPangList.push(...concatSrcUpDown),concatDstUpDown.length>2&&verticalPangList.push(...concatDstUpDown),concatSrcLeft.length>2&&horizonPangList.push(...concatSrcLeft),concatDstRight.length>2&&horizonPangList.push(...concatDstRight)}else if(direction==="right"){const upDstLinePang=this.upLinePang(dstCell),downDstLinePang=this.downLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),upSrcLinePang=this.upLinePang(srcCell),downSrcLinePang=this.downLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),concatSrcUpDown=[...new Set([...upSrcLinePang,...downSrcLinePang])],concatDstUpDown=[...new Set([...upDstLinePang,...downDstLinePang])],concatDstLeft=[...new Set(leftDstLinePang)],concatSrcRight=[...new Set(rightSrcLinePang)];concatSrcUpDown.length>2&&verticalPangList.push(...concatSrcUpDown),concatDstUpDown.length>2&&verticalPangList.push(...concatDstUpDown),concatDstLeft.length>2&&horizonPangList.push(...concatDstLeft),concatSrcRight.length>2&&horizonPangList.push(...concatSrcRight)}else if(direction==="up"){const upSrcLinePang=this.upLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),downDstLinePang=this.downLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),concatSrcLeftRight=[...new Set([...leftSrcLinePang,...rightSrcLinePang])],concatDstLeftRight=[...new Set([...leftDstLinePang,...rightDstLinePang])],concatSrcUp=[...new Set(upSrcLinePang)],concatDstDown=[...new Set(downDstLinePang)];concatSrcLeftRight.length>2&&verticalPangList.push(...concatSrcLeftRight),concatDstLeftRight.length>2&&verticalPangList.push(...concatDstLeftRight),concatSrcUp.length>2&&horizonPangList.push(...concatSrcUp),concatDstDown.length>2&&horizonPangList.push(...concatDstDown)}else if(direction==="down"){const upDstLinePang=this.upLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),downSrcLinePang=this.downLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),concatDstLeftRight=[...new Set([...leftDstLinePang,...rightDstLinePang])],concatSrcLeftRight=[...new Set([...leftSrcLinePang,...rightSrcLinePang])],concatDstUp=[...new Set(upDstLinePang)],concatSrcDown=[...new Set(downSrcLinePang)];concatSrcLeftRight.length>2&&verticalPangList.push(...concatSrcLeftRight),concatDstLeftRight.length>2&&verticalPangList.push(...concatDstLeftRight),concatDstUp.length>2&&horizonPangList.push(...concatDstUp),concatSrcDown.length>2&&horizonPangList.push(...concatSrcDown)}return this.logger.dir("inLinePang").dir("collected pang list").debug(horizonPangList,verticalPangList),[horizonPangList,verticalPangList]}upLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let y=targetY-1;y>=0;y--){const cell=this.map[y][targetX];if(cell.type===targetCell.type){temp.push(this.map[y][targetX]),this.logger.dir("upLinePang").debug("cell count",y);continue}this.logger.dir("upLinePang").error("cell is not matched type",cell);break}return this.logger.dir("upLinePang").log("pang list",temp),temp}downLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let y=targetY+1;y=0;x--){const cell=this.map[targetY][x];if(cell.type===targetCell.type){temp.push(this.map[targetY][x]);continue}this.logger.dir("leftLinePang").error("cell is not matched type",cell);break}return this.logger.dir("leftLinePang").log("pang list",temp),temp}rightLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let x=targetX+1;xresolver=resolve);return setTimeout(()=>{this.swapBothCell(srcCell,dstCell).then(()=>{resolver(!0)})},150),promise}async swapBothCell(srcCell,dstCell){var _a,_b,_c,_d;if(this.logger.dir("swapBothCell").debug("before swap both cell:",this.map),this.logger.dir("swapBothCell").dir("src").debug("get both cell in this.map",(_a=this.map[srcCell==null?void 0:srcCell.y])==null?void 0:_a[srcCell==null?void 0:srcCell.x]),this.logger.dir("swapBothCell").dir("dest").debug("get both cell in this.map",(_b=this.map[dstCell==null?void 0:dstCell.y])==null?void 0:_b[dstCell==null?void 0:dstCell.x]),!((_c=this.map[srcCell==null?void 0:srcCell.y])!=null&&_c[srcCell==null?void 0:srcCell.x])||!((_d=this.map[dstCell==null?void 0:dstCell.y])!=null&&_d[dstCell==null?void 0:dstCell.x]))return!1;try{if(!this.isInBoundary(srcCell,dstCell))return!1}catch(error){return console.error(error),!1}const swapDirection=srcCell.getDirectionWith(dstCell);if(swapDirection===null)return!1;this.logger.dir("swapBothCell").log(swapDirection),await srcCell.swapEffect(dstCell,swapDirection)||this.logger.dir("swapBothCell").error("swap error"),this.logger.dir("swapBothCell").debug("success swapEffect.");const destCopyCell=Cell.copy(dstCell,srcCell),srcCopyCell=Cell.copy(srcCell,dstCell);this.map[srcCell.y][srcCell.x]=destCopyCell,this.map[dstCell.y][dstCell.x]=srcCopyCell;const swapedSrcCell=this.map[srcCell.y][srcCell.x],swapedDstCell=this.map[dstCell.y][dstCell.x];this.logger.dir("swapBothCell").dir("check src").debug(swapedSrcCell),this.logger.dir("swapBothCell").dir("check dst").debug(swapedDstCell);const pangResult=this.inLinePang(swapedDstCell,swapedSrcCell,swapDirection);return pangResult.every(cell=>cell.length===0)?(this.logger.dir("swapBothCell").debug("no matched cell line"),!1):(pangResult.flat(1).forEach(cell=>{cell.pang(),this.scoreCalculator.scoreUp(cell.score)}),!0)}async swapBothCellAndFill(srcCell,dstCell){return await this.swapBothCell(srcCell,dstCell)?(await this.searchColumnsAndFillEmptyCell(),!0):(this.logger.dir("swapBothCellAndFill").error("not swapped"),!1)}getColumnLineFromStartPoint(x,startPoint){const yValue=startPoint,temp=[];for(let level=0;level<=yValue;level++){const cell=this.map[level][x];cell&&temp.push(cell)}return temp}getColumnLine(x){const yValue=OPTIONS.WIDTH.GAME.Y,temp=[];for(let level=0;level(row.length>3&&(acc+=row[0].score*row.slice(3).length),acc),0),columnScores=columns.reduce((acc,column)=>(column.length>3&&(acc+=column[0].score*column.slice(3).length),acc),0);return this.logger.dir("getPangableList").debug("추가 점수:",rowScores+columnScores),[...new Set([...rows,...columns].flat(1))]}async autoPangAndFill(loop=!0){this.getPangableList().forEach(cell=>{cell.pang(),this.scoreCalculator.scoreUp(cell.score)}),await this.searchEmptyColumnsAndFill();const isDone=this.getPangableList().length===0;return this.logger.dir("autoPangAndFill").log("isDone",isDone),loop&&!isDone?await this.autoPangAndFill():isDone}async searchEmptyColumnsAndFill(){new Promise(resolve=>resolve);const promises=[];for(let index=0;index{cell.moveY(idxx).then(()=>{cell.y=idxx,resolve(cell)})}))}return Promise.all(promises)}searchRowsAndFilterPangable(){var _a,_b,_c;const rowTemp=[];for(const row of this.map){for(const cell of row){const isEmpty=rowTemp.length===0,isEmptyLastArray=((_a=rowTemp[rowTemp.length-1])==null?void 0:_a.length)===0,isDifferenceType=((_c=(_b=rowTemp[rowTemp.length-1])==null?void 0:_b[0])==null?void 0:_c.type)!==cell.type;(isEmpty||isEmptyLastArray||isDifferenceType)&&rowTemp.push([]),rowTemp[rowTemp.length-1].push(cell)}rowTemp.push([])}return rowTemp.filter(row=>row.length>2)}searchColumnsAndFilterPangable(){var _a,_b,_c;const columnTemp=[];for(let index=0;indexcolumn.length>2)}async searchColumnsAndFillEmptyCell(){this.logger.dir("searchColumnsAndFillEmptyCell").log("start search empty column and fill cells...");const promises=[];for(let index=0;indexcell.type!=="")}async columnFillNewAnimals(x){const[startPoint,emptyAmount]=this.getEmptyStartPointAndAmount(x),columnLine=this.getColumnLine(x),filterCells=this.filterEmptyCell(columnLine),concatOriginAndNewCells=this.fillNewCells(filterCells,emptyAmount,x),animationTemp=[];concatOriginAndNewCells.forEach(cell=>{var _a,_b;const copyCell=cell.deepCopySelf();animationTemp.push(copyCell),(_b=(_a=this.map)==null?void 0:_a[cell.y])!=null&&_b[cell.x]&&(this.map[cell.y][cell.x]=copyCell)});const promiseTemp=[];for(const tempCell of animationTemp){let resolver;const aniPromise=new Promise(resolve=>resolver=resolve);promiseTemp.push(aniPromise);const tempCellY=tempCell.y;tempCell.y-=emptyAmount;const aniLoop=setInterval(()=>{tempCell.y+=OPTIONS.ANIMATION.SPEED/2,tempCell.y>=tempCellY&&(tempCell.y=tempCellY,clearInterval(aniLoop),resolver(!0))},OPTIONS.ANIMATION.FRAME)}return Promise.all(promiseTemp)}findEmptyCell(cells){return cells.find(cell=>cell.type==="")}filterEmptyCell(cells){return cells.filter(cell=>cell.type!=="")}fillNewCells(origin,emptyAmount,x){origin[0].y;const tempEmptyAmount=emptyAmount,temp=origin.map(cell=>cell.deepCopySelf());for(let index=1;index<=tempEmptyAmount;index++){const[type,score]=this.getRandomCellType(),copyCell=new Cell(type,x,1-index-1,score);temp.unshift(copyCell)}return temp}getEmptyStartPointAndAmount(x){const yValue=OPTIONS.WIDTH.GAME.Y-1;let startPoint=-1,emptyAmount=0;for(let level=yValue;level>=0;level--){const cell=this.map[level][x];cell.type===""&&(emptyAmount+=1,startPointcell.isSelected=!1)}}class Pointer extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");__publicField(this,"dependency",{});__publicField(this,"grab",null);__publicField(this,"swapTemp",[]);this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),window.addEventListener("mousemove",this.moveMouse.bind(this)),window.addEventListener("mousedown",this.clickCell.bind(this))}inject(module){this.logger.dir("inject").debug(`${capitalize(module.constructor.name)} is injected`),this.dependency[capitalize(module.constructor.name)]=module}async clickCell(){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m;if(this.mode==="test"){wait.length===0?(this.logger.only().dir("test").dir("clickCell").log("auto pang"),wait.push(0),await((_a=this.dependency.blockManager)==null?void 0:_a.autoPangAndFill(!1)),this.logger.debug(this.grab),wait.pop()):this.logger.only().dir("test").dir("clickCell").error("blocked click event");return}if(wait.length>0){this.logger.dir("clickCell").error("current working click event",wait),this.swapTemp=[];return}if(this.grab){if(this.logger.dir("clickCell").debug(this.grab),this.swapTemp.length<2&&(this.grab.isSelected=!0,this.swapTemp.push(this.grab),this.logger.dir("clickCell").log(this.swapTemp),this.logger.dir("clickCell").dir("select first cell").debug(this.swapTemp[0])),this.swapTemp.length===2){if(this.logger.dir("clickCell").log(this.swapTemp),this.logger.dir("clickCell").log("this.swapTemp length",2),this.dependency.blockManager&&this.swapTemp[0]!==this.swapTemp[1]&&wait.length===0){this.logger.dir("clickCell").dir("select second cell").debug(this.grab),wait.push(0),this.logger.dir("clickCell").log("swap both run");const isBoundary=this.dependency.blockManager.isInBoundary(this.swapTemp[0],this.swapTemp[1]);this.logger.dir("clickCell").debug("isBoundary",isBoundary),isBoundary&&((_b=this.dependency.scoreCalculator)==null||_b.turnCount());try{if(!await this.dependency.blockManager.swapBothCell(this.swapTemp[0],this.swapTemp[1])){this.logger.dir("swapBothCellAndFill").error("not swapped");const first=(_g=(_d=this.dependency.blockManager.map)==null?void 0:_d[(_c=this.swapTemp[0])==null?void 0:_c.y])==null?void 0:_g[(_f=(_e=this.swapTemp)==null?void 0:_e[0])==null?void 0:_f.x],second=(_l=(_i=this.dependency.blockManager.map)==null?void 0:_i[(_h=this.swapTemp[1])==null?void 0:_h.y])==null?void 0:_l[(_k=(_j=this.swapTemp)==null?void 0:_j[1])==null?void 0:_k.x];await this.dependency.blockManager.revertSwap(first,second),wait.pop(),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.swapTemp=[];return}}catch{return}await this.dependency.blockManager.autoPangAndFill(),this.logger.dir("clickCell").debug("release??"),wait.pop(),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.logger.dir("clickCell").log("swap both end")}this.logger.dir("clickCell").log(this.swapTemp),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.swapTemp=[],this.logger.dir("clickCell").log(this.swapTemp)}this.logger.dir("clickCell2").debug(this.swapTemp)}else this.logger.dir("clickCell").debug("no grab");this.logger.dir("clickCell").debug("map",(_m=this.dependency.blockManager)==null?void 0:_m.map)}moveMouse(e){const x=e.clientX,y=e.clientY,[resX,resY]=responsePointerAxis(x,y);try{const cell=this.getCellInfo(resX,resY);this.grab=cell,this.grab.isHover||(this.grab.isHover=!0)}catch{this.grab=null}}getCellInfo(x,y){var _a,_b;if(this.dependency.mapGenerator){const cell=(_b=(_a=this.dependency.mapGenerator.map)==null?void 0:_a[y])==null?void 0:_b[x];if(cell)return cell;throw new Error("not found cell")}throw new Error("no injected module")}}class ScoreCalculator extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");__publicField(this,"scores",0);__publicField(this,"turn",0);mode==="none"?this.turn=OPTIONS.GAME.TURN:mode==="test"&&(this.turn=1/0),this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode)}scoreUp(score){this.scores+=score,this.logger.dir("scoreUp").debug("get score",score)}turnCount(){this.logger.dir("turnCount").debug("count minus",this.turn),this.turn-=1}popupEndModal(){const wrap=document.createElement("div");wrap.id="modal",wrap.innerHTML=` - - - `,document.body.append(wrap)}render(){scoreCtx.font="bold 16px Arial",scoreCtx.textAlign="left",scoreCtx.fillStyle="#000000",scoreCtx.fillText(`score: ${this.scores} point${this.scores>1?"s":""}`,50,50),this.turn>5&&this.turn<10?scoreCtx.fillStyle="#ffff00":this.turn<=5&&(scoreCtx.fillStyle="#ff0000"),scoreCtx.fillText(`turn: ${this.turn} turn${this.scores>1?"s":""}`,50,70)}}class StoreManager extends BaseModule{constructor(mode,storeName){super(mode);__publicField(this,"storeName");__publicField(this,"logger");__publicField(this,"store",[]);this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),this.storeName=storeName||"pang_store",this.getData()}getLocalStorage(){return JSON.parse(localStorage.getItem(this.storeName)||"[]")}saveLocalStorage(){localStorage.setItem(this.storeName,JSON.stringify(this.store))}saveStore(data){this.store=data}getStore(){return this.store}getData(){const data=this.getLocalStorage();this.saveStore(data)}saveData(data){this.saveStore(data),this.saveLocalStorage()}addData(data){this.store.push(data),this.saveLocalStorage()}}class GameCore extends BaseModule{constructor(){super(RUN_MODE);__publicField(this,"seek",0);__publicField(this,"blockManager");__publicField(this,"animator");__publicField(this,"mapGenerator");__publicField(this,"scoreCalculator");__publicField(this,"storeManager");__publicField(this,"pointer");__publicField(this,"logger");__publicField(this,"canvases",[]);__publicField(this,"gameEnd",!1);__publicField(this,"_dev");__publicField(this,"_runMode");__publicField(this,"_baseWidth",innerWidth);__publicField(this,"_baseHeight",innerHeight);__publicField(this,"_storeName");__publicField(this,"_animation");__publicField(this,"handleResizeCanvasSize",()=>{this.logger.dir("setupCanvas").dir("handleResizeCanvasSize").log("resize all canvas");for(const canvas of this.canvases)canvas.width=innerWidth,canvas.height=innerHeight,this.logger.dir("handleResizeCanvasSize").dir("if").debug(this._baseWidth,innerWidth,RESPONSIVE_UNIT_SIZE()),innerWidth<=280?SUB_OPTIONS.SIZE.RATIO=-25:innerWidth<=375?SUB_OPTIONS.SIZE.RATIO=-15:innerWidth<=390?SUB_OPTIONS.SIZE.RATIO=-14:innerWidth<=393?SUB_OPTIONS.SIZE.RATIO=-15:innerWidth<=414?SUB_OPTIONS.SIZE.RATIO=-12:innerWidth<=540?SUB_OPTIONS.SIZE.RATIO=-3:innerWidth<=820?SUB_OPTIONS.SIZE.RATIO=15:innerWidth<=1024?SUB_OPTIONS.SIZE.RATIO=5:innerWidth<=1280?SUB_OPTIONS.SIZE.RATIO=6:SUB_OPTIONS.SIZE.RATIO=5});this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").debug("dev",this._dev),this.logger.dir("constructor").debug("run mode",this._runMode),this.logger.dir("constructor").log("setup game core..."),window.addEventListener("click",this.handleNewGame.bind(this))}newGame(){this.gameEnd=!1;const map=this.blockManager.initialize();this.mapGenerator.initialize(map),this.scoreCalculator.turn=OPTIONS.GAME.TURN,this.scoreCalculator.scores=0,setTimeout(()=>{this.execInitialPang()},16)}stopRender(){cancelAnimationFrame(this._animation)}handleNewGame(e){const target=e.target;wait.length>0&&target&&target.id==="newGame"?(this.newGame(),window.removeEventListener("click",this.handleNewGame.bind(this)),wait.splice(0),setTimeout(()=>{document.querySelectorAll("#modal").forEach(modal=>modal.remove())},10)):target&&target.id==="modal-close"&&document.querySelectorAll("#modal").forEach(modal=>modal.remove()),document.querySelectorAll("#modal").forEach(modal=>modal.remove())}setOption(property,value){if(`_${property}`in this)this.logger.dir("setOption").log(`success set option, property: ${property}, value: ${value}`),this[`_${property}`]=value;else throw new Error(`${property} is not a valid property`)}initialize(){this.logger.dir("initialize").log("initialize"),this.loadModules(),this.setupCanvas(bgCanvas,gameCanvas,effectCanvas,scoreCanvas,selectCanvas),this.injection();const map=this.blockManager.initialize();this.mapGenerator.initialize(map)}loadModules(){this.logger.dir("loadModules").log("start..."),this.scoreCalculator=new ScoreCalculator(this.mode),this.blockManager=new BlockManager(this.mode,this.scoreCalculator),this.blockManager,this.animator=new Animator(this.mode),this.mapGenerator=new MapGenerator(this.mode),this.pointer=new Pointer(this.mode),this.storeManager=new StoreManager(this.mode,this._storeName),this.logger.dir("loadModules").log("success!")}setupCanvas(...canvases){this.canvases=canvases,this.logger.dir("setupCanvas").log("setup canvas elements");for(const canvas of canvases)this.logger.dir("setupCanvas").log(`add ${canvas.id} canvas`),ROOT.append(canvas);this.handleResizeCanvasSize(),this.logger.dir("setupCanvas").log("add event window resize detect"),window.addEventListener("resize",this.handleResizeCanvasSize.bind(this))}injection(){this.pointer.inject(this.blockManager),this.pointer.inject(this.mapGenerator),this.pointer.inject(this.scoreCalculator)}animation(time){this.clearRect(),time*=.001,wait.length===0&&!this.gameEnd&&this.scoreCalculator.turn===0&&(wait.push(0),this.gameEnd=!0,this.scoreCalculator.popupEndModal()),this.scoreCalculator.render(),this.mapGenerator.render(),this.blockManager.render(),bgCtx.restore(),scoreCtx.restore(),gameCtx.restore(),selectCtx.restore(),effectCtx.restore(),this._animation=requestAnimationFrame(this.animation.bind(this)),this.seek=Math.floor(time)}clearRect(){bgCtx.clearRect(0,0,innerWidth,innerHeight),scoreCtx.clearRect(0,0,innerWidth,innerHeight),gameCtx.clearRect(0,0,innerWidth,innerHeight),effectCtx.clearRect(0,0,innerWidth,innerHeight),selectCtx.clearRect(0,0,innerWidth,innerHeight),bgCtx.save(),scoreCtx.save(),gameCtx.save(),effectCtx.save(),selectCtx.save()}render(){this.logger.dir("render").log("start game core rendering..."),this.logger.dir("render").log("start calulator rendering..."),this.logger.dir("render").log("start game map rendering..."),this.logger.dir("render").log("start block rendering..."),this.execInitialPang(),this._animation=requestAnimationFrame(this.animation.bind(this))}execInitialPang(){this.mode!=="test"&&wait.length===0&&(wait.push(0),this.blockManager.autoPangAndFill().then(()=>{wait.pop()}))}renderPerSecond(){}}const gameCore=new GameCore;gameCore.setOption("dev",MODE);gameCore.setOption("runMode",RUN_MODE);gameCore.setOption("storeName",STORE_NAME);gameCore.initialize();gameCore.render(); diff --git a/assets/index-e4f3e0d0.js b/assets/index-e4f3e0d0.js new file mode 100644 index 0000000..ed36d94 --- /dev/null +++ b/assets/index-e4f3e0d0.js @@ -0,0 +1,25 @@ +var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key]=value;var __publicField=(obj,key,value)=>(__defNormalProp(obj,typeof key!="symbol"?key+"":key,value),value);(function(){const relList=document.createElement("link").relList;if(relList&&relList.supports&&relList.supports("modulepreload"))return;for(const link of document.querySelectorAll('link[rel="modulepreload"]'))processPreload(link);new MutationObserver(mutations=>{for(const mutation of mutations)if(mutation.type==="childList")for(const node of mutation.addedNodes)node.tagName==="LINK"&&node.rel==="modulepreload"&&processPreload(node)}).observe(document,{childList:!0,subtree:!0});function getFetchOpts(link){const fetchOpts={};return link.integrity&&(fetchOpts.integrity=link.integrity),link.referrerPolicy&&(fetchOpts.referrerPolicy=link.referrerPolicy),link.crossOrigin==="use-credentials"?fetchOpts.credentials="include":link.crossOrigin==="anonymous"?fetchOpts.credentials="omit":fetchOpts.credentials="same-origin",fetchOpts}function processPreload(link){if(link.ep)return;link.ep=!0;const fetchOpts=getFetchOpts(link);fetch(link.href,fetchOpts)}})();var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};/*! ***************************************************************************** +Copyright (C) Microsoft. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */var Reflect2;(function(Reflect3){(function(factory){var root=typeof commonjsGlobal=="object"?commonjsGlobal:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),exporter=makeExporter(Reflect3);typeof root.Reflect>"u"?root.Reflect=Reflect3:exporter=makeExporter(root.Reflect,exporter),factory(exporter);function makeExporter(target,previous){return function(key,value){typeof target[key]!="function"&&Object.defineProperty(target,key,{configurable:!0,writable:!0,value}),previous&&previous(key,value)}}})(function(exporter){var hasOwn=Object.prototype.hasOwnProperty,supportsSymbol=typeof Symbol=="function",toPrimitiveSymbol=supportsSymbol&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",iteratorSymbol=supportsSymbol&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",supportsCreate=typeof Object.create=="function",supportsProto={__proto__:[]}instanceof Array,downLevel=!supportsCreate&&!supportsProto,HashMap={create:supportsCreate?function(){return MakeDictionary(Object.create(null))}:supportsProto?function(){return MakeDictionary({__proto__:null})}:function(){return MakeDictionary({})},has:downLevel?function(map,key){return hasOwn.call(map,key)}:function(map,key){return key in map},get:downLevel?function(map,key){return hasOwn.call(map,key)?map[key]:void 0}:function(map,key){return map[key]}},functionPrototype=Object.getPrototypeOf(Function),usePolyfill=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",_Map=!usePolyfill&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:CreateMapPolyfill(),_Set=!usePolyfill&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:CreateSetPolyfill(),_WeakMap=!usePolyfill&&typeof WeakMap=="function"?WeakMap:CreateWeakMapPolyfill(),Metadata=new _WeakMap;function decorate(decorators,target,propertyKey,attributes){if(IsUndefined(propertyKey)){if(!IsArray(decorators))throw new TypeError;if(!IsConstructor(target))throw new TypeError;return DecorateConstructor(decorators,target)}else{if(!IsArray(decorators))throw new TypeError;if(!IsObject(target))throw new TypeError;if(!IsObject(attributes)&&!IsUndefined(attributes)&&!IsNull(attributes))throw new TypeError;return IsNull(attributes)&&(attributes=void 0),propertyKey=ToPropertyKey(propertyKey),DecorateProperty(decorators,target,propertyKey,attributes)}}exporter("decorate",decorate);function metadata(metadataKey,metadataValue){function decorator(target,propertyKey){if(!IsObject(target))throw new TypeError;if(!IsUndefined(propertyKey)&&!IsPropertyKey(propertyKey))throw new TypeError;OrdinaryDefineOwnMetadata(metadataKey,metadataValue,target,propertyKey)}return decorator}exporter("metadata",metadata);function defineMetadata(metadataKey,metadataValue,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryDefineOwnMetadata(metadataKey,metadataValue,target,propertyKey)}exporter("defineMetadata",defineMetadata);function hasMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryHasMetadata(metadataKey,target,propertyKey)}exporter("hasMetadata",hasMetadata);function hasOwnMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryHasOwnMetadata(metadataKey,target,propertyKey)}exporter("hasOwnMetadata",hasOwnMetadata);function getMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryGetMetadata(metadataKey,target,propertyKey)}exporter("getMetadata",getMetadata);function getOwnMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryGetOwnMetadata(metadataKey,target,propertyKey)}exporter("getOwnMetadata",getOwnMetadata);function getMetadataKeys(target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryMetadataKeys(target,propertyKey)}exporter("getMetadataKeys",getMetadataKeys);function getOwnMetadataKeys(target,propertyKey){if(!IsObject(target))throw new TypeError;return IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey)),OrdinaryOwnMetadataKeys(target,propertyKey)}exporter("getOwnMetadataKeys",getOwnMetadataKeys);function deleteMetadata(metadataKey,target,propertyKey){if(!IsObject(target))throw new TypeError;IsUndefined(propertyKey)||(propertyKey=ToPropertyKey(propertyKey));var metadataMap=GetOrCreateMetadataMap(target,propertyKey,!1);if(IsUndefined(metadataMap)||!metadataMap.delete(metadataKey))return!1;if(metadataMap.size>0)return!0;var targetMetadata=Metadata.get(target);return targetMetadata.delete(propertyKey),targetMetadata.size>0||Metadata.delete(target),!0}exporter("deleteMetadata",deleteMetadata);function DecorateConstructor(decorators,target){for(var i=decorators.length-1;i>=0;--i){var decorator=decorators[i],decorated=decorator(target);if(!IsUndefined(decorated)&&!IsNull(decorated)){if(!IsConstructor(decorated))throw new TypeError;target=decorated}}return target}function DecorateProperty(decorators,target,propertyKey,descriptor){for(var i=decorators.length-1;i>=0;--i){var decorator=decorators[i],decorated=decorator(target,propertyKey,descriptor);if(!IsUndefined(decorated)&&!IsNull(decorated)){if(!IsObject(decorated))throw new TypeError;descriptor=decorated}}return descriptor}function GetOrCreateMetadataMap(O,P,Create){var targetMetadata=Metadata.get(O);if(IsUndefined(targetMetadata)){if(!Create)return;targetMetadata=new _Map,Metadata.set(O,targetMetadata)}var metadataMap=targetMetadata.get(P);if(IsUndefined(metadataMap)){if(!Create)return;metadataMap=new _Map,targetMetadata.set(P,metadataMap)}return metadataMap}function OrdinaryHasMetadata(MetadataKey,O,P){var hasOwn2=OrdinaryHasOwnMetadata(MetadataKey,O,P);if(hasOwn2)return!0;var parent=OrdinaryGetPrototypeOf(O);return IsNull(parent)?!1:OrdinaryHasMetadata(MetadataKey,parent,P)}function OrdinaryHasOwnMetadata(MetadataKey,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!1);return IsUndefined(metadataMap)?!1:ToBoolean(metadataMap.has(MetadataKey))}function OrdinaryGetMetadata(MetadataKey,O,P){var hasOwn2=OrdinaryHasOwnMetadata(MetadataKey,O,P);if(hasOwn2)return OrdinaryGetOwnMetadata(MetadataKey,O,P);var parent=OrdinaryGetPrototypeOf(O);if(!IsNull(parent))return OrdinaryGetMetadata(MetadataKey,parent,P)}function OrdinaryGetOwnMetadata(MetadataKey,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!1);if(!IsUndefined(metadataMap))return metadataMap.get(MetadataKey)}function OrdinaryDefineOwnMetadata(MetadataKey,MetadataValue,O,P){var metadataMap=GetOrCreateMetadataMap(O,P,!0);metadataMap.set(MetadataKey,MetadataValue)}function OrdinaryMetadataKeys(O,P){var ownKeys=OrdinaryOwnMetadataKeys(O,P),parent=OrdinaryGetPrototypeOf(O);if(parent===null)return ownKeys;var parentKeys=OrdinaryMetadataKeys(parent,P);if(parentKeys.length<=0)return ownKeys;if(ownKeys.length<=0)return parentKeys;for(var set=new _Set,keys=[],_i=0,ownKeys_1=ownKeys;_i=0&&index=this._keys.length?(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel):this._index++,{value:result,done:!1}}return{value:void 0,done:!0}},MapIterator2.prototype.throw=function(error){throw this._index>=0&&(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel),error},MapIterator2.prototype.return=function(value){return this._index>=0&&(this._index=-1,this._keys=arraySentinel,this._values=arraySentinel),{value,done:!0}},MapIterator2}();return function(){function Map2(){this._keys=[],this._values=[],this._cacheKey=cacheSentinel,this._cacheIndex=-2}return Object.defineProperty(Map2.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),Map2.prototype.has=function(key){return this._find(key,!1)>=0},Map2.prototype.get=function(key){var index=this._find(key,!1);return index>=0?this._values[index]:void 0},Map2.prototype.set=function(key,value){var index=this._find(key,!0);return this._values[index]=value,this},Map2.prototype.delete=function(key){var index=this._find(key,!1);if(index>=0){for(var size=this._keys.length,i=index+1;i{const canvas=document.createElement("canvas"),ctx=canvas.getContext("2d",{desynchronized:!1,alpha:!0,willReadFrequently:!1});return id&&(canvas.id=id),[canvas,ctx]},catImg=document.createElement("img");catImg.src=cat;const dogImg=document.createElement("img");dogImg.src=dog;const lionImg=document.createElement("img");lionImg.src=lion;const duckImg=document.createElement("img");duckImg.src=duck;const mouseImg=document.createElement("img");mouseImg.src=mouse;const rabbitImg=document.createElement("img");rabbitImg.src=rabbit;const pandaImg=document.createElement("img");pandaImg.src=panda;const pigImg=document.createElement("img");pigImg.src=pig;const racoonImg=document.createElement("img");racoonImg.src=racoon;const images={cat:catImg,dog:dogImg,lion:lionImg,duck:duckImg,mouse:mouseImg,rabbit:rabbitImg,panda:pandaImg,pig:pigImg,racoon:racoonImg},ROOT=document.querySelector("#root"),[bgCanvas,bgCtx]=createCanvas("bg"),[gameCanvas,gameCtx]=createCanvas("game"),[effectCanvas,effectCtx]=createCanvas("effect"),[scoreCanvas,scoreCtx]=createCanvas("score"),[selectCanvas,selectCtx]=createCanvas("select"),[questCanvas,questCtx]=createCanvas("quest");bgCtx.translate(.5,.5);gameCtx.translate(.5,.5);effectCtx.translate(.5,.5);scoreCtx.translate(.5,.5);selectCtx.translate(.5,.5);const isMobile=window.navigator.userAgent.match(/android|mobile/gi),SUB_OPTIONS={SIZE:{RATIO:1}},OPTIONS={SIZE:{UNIT:50},WIDTH:{GAME:{X:9,Y:9}},ANIMATION:{SPEED:isMobile?.5:.1,FRAME:16},GAME:{TURN:75}},RESPONSIVE_UNIT_SIZE=()=>OPTIONS.SIZE.UNIT+SUB_OPTIONS.SIZE.RATIO,BG_COLOR="#dddddd",wait=[],RUN_MODE={}.VITE_RUN_MODE||"none",STORE_NAME="pang_store",BASE_TYPE_SCORE=[["dog",1],["duck",3],["mouse",4],["lion",6],["pig",7],["panda",8],["racoon",9]],TestCase2=[["dog","dog","dog","lion","lion","mouse","dog","mouse","cat"],["dog","dog","dog","mouse","dog","lion","lion","lion","mouse"],["dog","lion","lion","lion","dog","dog","mouse","dog","mouse"],["dog","dog","dog","lion","lion","mouse","dog","mouse","cat"],["dog","dog","lion","dog","mouse","dog","mouse","cat","lion"],["dog","mouse","mouse","mouse","dog","dog","lion","mouse","cat"],["mouse","lion","dog","dog","lion","dog","dog","mouse","mouse"],["mouse","lion","dog","dog","lion","dog","mouse","mouse","mouse"],["dog","lion","lion","mouse","dog","mouse","cat","cat","cat"]],QUEST_LIST=[new Quest("돼지가 너무 많아!","돼지를 15마리 잡으세요.",150,{type:"pig",amount:15}),new Quest("찍찍찌익!","쥐를 30마리 잡으세요.",300,{type:"mouse",amount:30}),new Quest("팬더 수집가 - 1","팬더를 10마리 잡으세요.",100,{type:"panda",amount:10}),new Quest("팬더 수집가 - 2","팬더를 15마리 잡으세요.",300,{type:"panda",amount:15}),new Quest("팬더 수집가 - 3","팬더를 20마리 잡으세요.",600,{type:"panda",amount:20}),new Quest("강아지 수집가 - 1","강아지를 15마리 잡으세요.",200,{type:"dog",amount:15}),new Quest("강아지 수집가 - 2","강아지를 20마리 잡으세요.",400,{type:"dog",amount:20}),new Quest("강아지 수집가 - 3","강아지를 30마리 잡으세요.",800,{type:"dog",amount:30}),new Quest("사자 수집가 - 1","사자를 15마리 잡으세요.",200,{type:"lion",amount:15}),new Quest("사자 수집가 - 2","사자를 20마리 잡으세요.",400,{type:"lion",amount:20}),new Quest("사자 수집가 - 3","사자를 30마리 잡으세요.",800,{type:"lion",amount:30}),new Quest("토끼 수집가 - 1","토끼를 15마리 잡으세요.",200,{type:"rabbit",amount:15}),new Quest("토끼 수집가 - 2","토끼를 20마리 잡으세요.",400,{type:"rabbit",amount:20}),new Quest("토끼 수집가 - 3","토끼를 30마리 잡으세요.",800,{type:"rabbit",amount:30}),new Quest("오리 수집가 - 1","오리를 15마리 잡으세요.",200,{type:"duck",amount:15}),new Quest("오리 수집가 - 2","오리를 20마리 잡으세요.",400,{type:"duck",amount:20}),new Quest("오리 수집가 - 3","오리를 30마리 잡으세요.",800,{type:"duck",amount:30}),new Quest("돼지 수집가 - 1","돼지를 15마리 잡으세요.",200,{type:"pig",amount:15}),new Quest("돼지 수집가 - 2","돼지를 20마리 잡으세요.",400,{type:"pig",amount:20}),new Quest("돼지 수집가 - 3","돼지를 30마리 잡으세요.",800,{type:"pig",amount:30})];class Logger{constructor(name){__publicField(this,"name","SYS");__publicField(this,"_logger",console);__publicField(this,"directories",[]);__publicField(this,"only",()=>new Logger(this.name+":only"));this.name=name}convert(color,...data){}reform(str){return`[${str}] >`}dir(dir){return this.directories.push(dir),this}log(...data){this.convert("yellowBright",...data),this.clearDir()}debug(...data){this.convert("blueBright",...data),this.clearDir()}error(...data){this.convert("redBright",...data),this.clearDir()}clearDir(){this.directories=[]}}class BaseModule{constructor(mode){__publicField(this,"mode","none");this.mode=mode}}class Animator extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode)}}const capitalize=str=>str.charAt(0).toLowerCase()+str.slice(1),responseBlockAxis=(x,y)=>{const centerX=innerWidth/2,centerY=innerHeight/2,horizonValue=OPTIONS.WIDTH.GAME.X*RESPONSIVE_UNIT_SIZE(),verticalValue=OPTIONS.WIDTH.GAME.Y*RESPONSIVE_UNIT_SIZE(),halfHorizon=horizonValue/2,halfVertical=verticalValue/2,resX=centerX+x-halfHorizon,resY=centerY+y-halfVertical;return[resX,resY]},responsePointerAxis=(x,y)=>{const centerX=innerWidth/2,centerY=innerHeight/2,horizonValue=OPTIONS.WIDTH.GAME.X*RESPONSIVE_UNIT_SIZE(),verticalValue=OPTIONS.WIDTH.GAME.Y*RESPONSIVE_UNIT_SIZE(),halfHorizon=horizonValue/2,halfVertical=verticalValue/2,unitCenterX=Math.floor((x-centerX+halfHorizon)/RESPONSIVE_UNIT_SIZE()),unitCenterY=Math.floor((y-centerY+halfVertical)/RESPONSIVE_UNIT_SIZE());return[unitCenterX,unitCenterY]},_Cell=class _Cell{constructor(type,x,y,score){__publicField(this,"id");__publicField(this,"type");__publicField(this,"x");__publicField(this,"y");__publicField(this,"matched");__publicField(this,"isPang");__publicField(this,"score");__publicField(this,"isSelected");__publicField(this,"isHover");__publicField(this,"logger");this.id=_Cell.autoIncrement,this.type=type,this.x=x,this.y=y,this.matched=!1,this.isPang=!1,this.score=score,this.isSelected=!1,this.isHover=!1,_Cell.autoIncrement++,this.logger=new Logger("Cell")}getDirectionWith(dstCell){const srcX=this.x,srcY=this.y,dstX=dstCell.x,dstY=dstCell.y;return this.logger.dir("getDirectionWith").log(srcX,srcY,dstX,dstY),dstX>srcX?(this.logger.dir("getDirectionWith").log("오른쪽으로 스왑"),"right"):dstXsrcY?(this.logger.dir("getDirectionWith").log("아래쪽으로 스왑"),"down"):dstYresolver=resolve),fromX=this.x,toX=to,direction=fromX!==to&&fromX>to,move=setInterval(()=>{this.x+=fromX>to?-OPTIONS.ANIMATION.SPEED/2:OPTIONS.ANIMATION.SPEED/2,direction?toX>=this.x&&(clearInterval(move),resolver(!0),this.x=fromX):toX<=this.x&&(clearInterval(move),resolver(!0),this.x=fromX)},OPTIONS.ANIMATION.FRAME);return promise}moveY(to){let resolver;const promise=new Promise(resolve=>resolver=resolve),fromY=this.y,toY=to,direction=fromY!==to&&fromY>to,move=setInterval(()=>{this.y+=fromY>to?-OPTIONS.ANIMATION.SPEED/2:OPTIONS.ANIMATION.SPEED/2,direction?toY>=this.y&&(clearInterval(move),this.y=fromY,resolver(this)):toY<=this.y&&(clearInterval(move),this.y=fromY,resolver(this))},OPTIONS.ANIMATION.FRAME);return promise}swapEffect(target,direction){let resolver;const promise=new Promise(resolve=>resolver=resolve);switch(this.x,this.y,target.x,target.y,direction){case"left":case"right":Promise.all([this.moveX(target.x),target.moveX(this.x)]).then(()=>{resolver(!0)});break;case"up":case"down":Promise.all([this.moveY(target.y),target.moveY(this.y)]).then(()=>{resolver(!0)});break;default:setTimeout(()=>{resolver(!1)},0);break}return this.logger.dir("swapEffect").debug(`from ${this.type} to ${target.type} swapping...`),promise}pang(){this.type="",this.isPang=!0}highlight(type){const[x,y]=responseBlockAxis(this.x*RESPONSIVE_UNIT_SIZE(),this.y*RESPONSIVE_UNIT_SIZE());switch(type){case"hover":selectCtx.fillStyle="#56565656";break;case"select":selectCtx.fillStyle="#48c46e56";break}selectCtx.fillRect(x,y,RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())}render(){const[x,y]=responseBlockAxis(this.x,this.y),image=images[this.type];image?(gameCtx.imageSmoothingQuality="low",gameCtx.imageSmoothingEnabled=!0,gameCtx.drawImage(image,Math.floor(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x)),Math.floor(this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y)),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())):(gameCtx.fillStyle="#00000000",gameCtx.fillRect(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE())),this.isSelected&&this.highlight("select")}renderOtherCanvas(ctx){const[x,y]=responseBlockAxis(this.x,this.y),image=images[this.type];image?ctx.drawImage(image,this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE()):(ctx.fillStyle="#00000000",ctx.fillRect(this.x*RESPONSIVE_UNIT_SIZE()+Math.floor(x-this.x),this.y*RESPONSIVE_UNIT_SIZE()+Math.floor(y-this.y),RESPONSIVE_UNIT_SIZE(),RESPONSIVE_UNIT_SIZE()))}static copy(cell,toCell){return new _Cell(cell.type,toCell.x,toCell.y,cell.score)}deepCopySelf(){return new _Cell(this.type,this.x,this.y,this.score)}deepCopy(cell){return new _Cell(cell.type,cell.x,cell.y,cell.score)}deepCopyWithAxis(cell,x,y){return new _Cell(cell.type,x,y,cell.score)}};__publicField(_Cell,"autoIncrement",0);let Cell=_Cell;class BlockManager extends BaseModule{constructor(mode,scoreCalculator,questManager){super(mode);__publicField(this,"types",BASE_TYPE_SCORE);__publicField(this,"logger");__publicField(this,"blockSize",{x:50,y:50});__publicField(this,"map",[]);__publicField(this,"scoreCalculator");__publicField(this,"questManager");__publicField(this,"animalsPang",{cat:0,dog:0,lion:0,duck:0,mouse:0,rabbit:0,panda:0,pig:0,racoon:0});this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),this.scoreCalculator=scoreCalculator,this.questManager=questManager}containsType(type){return this.types.some(types=>types[0]===type)}scoreUp(score){this.scoreCalculator.scoreUp(score)}initialize(){if(this.mode!=="test"){const map=this.createMap([OPTIONS.WIDTH.GAME.X,OPTIONS.WIDTH.GAME.Y]);return this.logger.dir("initialize").log("created map",map),this.map=map,map}else{if(TestCase2.length!==OPTIONS.WIDTH.GAME.Y||TestCase2[0].length!==OPTIONS.WIDTH.GAME.X)throw new Error("Invalid map size");const map=this.createCustomMap(TestCase2);return this.logger.dir("initialize").log("created custom map",map),this.map=map,map}}getCellScoreByType(type){const index=this.types.findIndex(typeScore=>typeScore[0]===type);return this.types[index][1]}getRandomCellType(){const randomTypeIndex=Math.floor(Math.random()*this.types.length);return this.types[randomTypeIndex]}createMap([xSize,ySize]){const maps=[];for(let y=0;yrow.map((cell,x)=>new Cell(cell,x,y,this.getCellScoreByType(cell))))}isInBoundary(srcCell,dstCell){var _a,_b,_c,_d;this.logger.dir("isInBoundary").debug("srcCell","dstCell",srcCell,dstCell);const srcX=srcCell==null?void 0:srcCell.x,srcY=srcCell==null?void 0:srcCell.y;if(srcX===void 0||srcY===void 0)return!1;const topCell=(_a=this.map[srcY-1])==null?void 0:_a[srcX],bottomCell=(_b=this.map[srcY+1])==null?void 0:_b[srcX],leftCell=(_c=this.map[srcY])==null?void 0:_c[srcX-1],rightCell=(_d=this.map[srcY])==null?void 0:_d[srcX+1],isIn=topCell===dstCell||bottomCell===dstCell||leftCell===dstCell||rightCell===dstCell;return this.logger.dir("swapBothCell").dir("isInBoundary").debug(isIn),isIn}inLinePang(srcCell,dstCell,direction){this.logger.dir("inLinePang").debug("validating pangable line by dst cell.");const horizonPangList=[],verticalPangList=[];if(direction==="left"){const upSrcLinePang=this.upLinePang(srcCell),downSrcLinePang=this.downLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),upDstLinePang=this.upLinePang(dstCell),downDstLinePang=this.downLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),concatSrcUpDown=[...new Set([...upSrcLinePang,...downSrcLinePang])],concatDstUpDown=[...new Set([...upDstLinePang,...downDstLinePang])],concatSrcLeft=[...new Set(leftSrcLinePang)],concatDstRight=[...new Set(rightDstLinePang)];concatSrcUpDown.length>2&&verticalPangList.push(...concatSrcUpDown),concatDstUpDown.length>2&&verticalPangList.push(...concatDstUpDown),concatSrcLeft.length>2&&horizonPangList.push(...concatSrcLeft),concatDstRight.length>2&&horizonPangList.push(...concatDstRight)}else if(direction==="right"){const upDstLinePang=this.upLinePang(dstCell),downDstLinePang=this.downLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),upSrcLinePang=this.upLinePang(srcCell),downSrcLinePang=this.downLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),concatSrcUpDown=[...new Set([...upSrcLinePang,...downSrcLinePang])],concatDstUpDown=[...new Set([...upDstLinePang,...downDstLinePang])],concatDstLeft=[...new Set(leftDstLinePang)],concatSrcRight=[...new Set(rightSrcLinePang)];concatSrcUpDown.length>2&&verticalPangList.push(...concatSrcUpDown),concatDstUpDown.length>2&&verticalPangList.push(...concatDstUpDown),concatDstLeft.length>2&&horizonPangList.push(...concatDstLeft),concatSrcRight.length>2&&horizonPangList.push(...concatSrcRight)}else if(direction==="up"){const upSrcLinePang=this.upLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),downDstLinePang=this.downLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),concatSrcLeftRight=[...new Set([...leftSrcLinePang,...rightSrcLinePang])],concatDstLeftRight=[...new Set([...leftDstLinePang,...rightDstLinePang])],concatSrcUp=[...new Set(upSrcLinePang)],concatDstDown=[...new Set(downDstLinePang)];concatSrcLeftRight.length>2&&verticalPangList.push(...concatSrcLeftRight),concatDstLeftRight.length>2&&verticalPangList.push(...concatDstLeftRight),concatSrcUp.length>2&&horizonPangList.push(...concatSrcUp),concatDstDown.length>2&&horizonPangList.push(...concatDstDown)}else if(direction==="down"){const upDstLinePang=this.upLinePang(dstCell),leftDstLinePang=this.leftLinePang(dstCell),rightDstLinePang=this.rightLinePang(dstCell),downSrcLinePang=this.downLinePang(srcCell),leftSrcLinePang=this.leftLinePang(srcCell),rightSrcLinePang=this.rightLinePang(srcCell),concatDstLeftRight=[...new Set([...leftDstLinePang,...rightDstLinePang])],concatSrcLeftRight=[...new Set([...leftSrcLinePang,...rightSrcLinePang])],concatDstUp=[...new Set(upDstLinePang)],concatSrcDown=[...new Set(downSrcLinePang)];concatSrcLeftRight.length>2&&verticalPangList.push(...concatSrcLeftRight),concatDstLeftRight.length>2&&verticalPangList.push(...concatDstLeftRight),concatDstUp.length>2&&horizonPangList.push(...concatDstUp),concatSrcDown.length>2&&horizonPangList.push(...concatSrcDown)}return this.logger.dir("inLinePang").dir("collected pang list").debug(horizonPangList,verticalPangList),[horizonPangList,verticalPangList]}upLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let y=targetY-1;y>=0;y--){const cell=this.map[y][targetX];if(cell.type===targetCell.type){temp.push(this.map[y][targetX]),this.logger.dir("upLinePang").debug("cell count",y);continue}this.logger.dir("upLinePang").error("cell is not matched type",cell);break}return this.logger.dir("upLinePang").log("pang list",temp),temp}downLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let y=targetY+1;y=0;x--){const cell=this.map[targetY][x];if(cell.type===targetCell.type){temp.push(this.map[targetY][x]);continue}this.logger.dir("leftLinePang").error("cell is not matched type",cell);break}return this.logger.dir("leftLinePang").log("pang list",temp),temp}rightLinePang(targetCell){const targetX=targetCell.x,targetY=targetCell.y,temp=[targetCell];for(let x=targetX+1;xresolver=resolve);return setTimeout(()=>{this.swapBothCell(srcCell,dstCell).then(()=>{resolver(!0)})},150),promise}async swapBothCell(srcCell,dstCell){var _a,_b,_c,_d;if(this.logger.dir("swapBothCell").debug("before swap both cell:",this.map),this.logger.dir("swapBothCell").dir("src").debug("get both cell in this.map",(_a=this.map[srcCell==null?void 0:srcCell.y])==null?void 0:_a[srcCell==null?void 0:srcCell.x]),this.logger.dir("swapBothCell").dir("dest").debug("get both cell in this.map",(_b=this.map[dstCell==null?void 0:dstCell.y])==null?void 0:_b[dstCell==null?void 0:dstCell.x]),!((_c=this.map[srcCell==null?void 0:srcCell.y])!=null&&_c[srcCell==null?void 0:srcCell.x])||!((_d=this.map[dstCell==null?void 0:dstCell.y])!=null&&_d[dstCell==null?void 0:dstCell.x]))return!1;try{if(!this.isInBoundary(srcCell,dstCell))return!1}catch(error){return console.error(error),!1}const swapDirection=srcCell.getDirectionWith(dstCell);if(swapDirection===null)return!1;this.logger.dir("swapBothCell").log(swapDirection),await srcCell.swapEffect(dstCell,swapDirection)||this.logger.dir("swapBothCell").error("swap error"),this.logger.dir("swapBothCell").debug("success swapEffect.");const destCopyCell=Cell.copy(dstCell,srcCell),srcCopyCell=Cell.copy(srcCell,dstCell);this.map[srcCell.y][srcCell.x]=destCopyCell,this.map[dstCell.y][dstCell.x]=srcCopyCell;const swapedSrcCell=this.map[srcCell.y][srcCell.x],swapedDstCell=this.map[dstCell.y][dstCell.x];this.logger.dir("swapBothCell").dir("check src").debug(swapedSrcCell),this.logger.dir("swapBothCell").dir("check dst").debug(swapedDstCell);const pangResult=this.inLinePang(swapedDstCell,swapedSrcCell,swapDirection);return pangResult.every(cell=>cell.length===0)?(this.logger.dir("swapBothCell").debug("no matched cell line"),!1):(pangResult.flat(1).forEach(cell=>{this.animalsPang[cell.type]+=1,this.questManager.questAmountUp(cell.type),cell.pang(),this.scoreCalculator.scoreUp(cell.score)}),!0)}async swapBothCellAndFill(srcCell,dstCell){return await this.swapBothCell(srcCell,dstCell)?(await this.searchColumnsAndFillEmptyCell(),!0):(this.logger.dir("swapBothCellAndFill").error("not swapped"),!1)}getColumnLineFromStartPoint(x,startPoint){const yValue=startPoint,temp=[];for(let level=0;level<=yValue;level++){const cell=this.map[level][x];cell&&temp.push(cell)}return temp}getColumnLine(x){const yValue=OPTIONS.WIDTH.GAME.Y,temp=[];for(let level=0;level(row.length>3&&(acc+=row[0].score*row.slice(3).length),acc),0),columnScores=columns.reduce((acc,column)=>(column.length>3&&(acc+=column[0].score*column.slice(3).length),acc),0);return this.logger.dir("getPangableList").debug("추가 점수:",rowScores+columnScores),[...new Set([...rows,...columns].flat(1))]}async autoPangAndFill(loop=!0){this.getPangableList().forEach(cell=>{this.animalsPang[cell.type]+=1,this.questManager.questAmountUp(cell.type),cell.pang(),this.scoreCalculator.scoreUp(cell.score)}),await this.searchEmptyColumnsAndFill();const isDone=this.getPangableList().length===0;return this.logger.dir("autoPangAndFill").log("isDone",isDone),loop&&!isDone?await this.autoPangAndFill():isDone}async searchEmptyColumnsAndFill(){new Promise(resolve=>resolve);const promises=[];for(let index=0;index{cell.moveY(idxx).then(()=>{cell.y=idxx,resolve(cell)})}))}return Promise.all(promises)}searchRowsAndFilterPangable(){var _a,_b,_c;const rowTemp=[];for(const row of this.map){for(const cell of row){const isEmpty=rowTemp.length===0,isEmptyLastArray=((_a=rowTemp[rowTemp.length-1])==null?void 0:_a.length)===0,isDifferenceType=((_c=(_b=rowTemp[rowTemp.length-1])==null?void 0:_b[0])==null?void 0:_c.type)!==cell.type;(isEmpty||isEmptyLastArray||isDifferenceType)&&rowTemp.push([]),rowTemp[rowTemp.length-1].push(cell)}rowTemp.push([])}return rowTemp.filter(row=>row.length>2)}searchColumnsAndFilterPangable(){var _a,_b,_c;const columnTemp=[];for(let index=0;indexcolumn.length>2)}async searchColumnsAndFillEmptyCell(){this.logger.dir("searchColumnsAndFillEmptyCell").log("start search empty column and fill cells...");const promises=[];for(let index=0;indexcell.type!=="")}async columnFillNewAnimals(x){const[startPoint,emptyAmount]=this.getEmptyStartPointAndAmount(x),columnLine=this.getColumnLine(x),filterCells=this.filterEmptyCell(columnLine),concatOriginAndNewCells=this.fillNewCells(filterCells,emptyAmount,x),animationTemp=[];concatOriginAndNewCells.forEach(cell=>{var _a,_b;const copyCell=cell.deepCopySelf();animationTemp.push(copyCell),(_b=(_a=this.map)==null?void 0:_a[cell.y])!=null&&_b[cell.x]&&(this.map[cell.y][cell.x]=copyCell)});const promiseTemp=[];for(const tempCell of animationTemp){let resolver;const aniPromise=new Promise(resolve=>resolver=resolve);promiseTemp.push(aniPromise);const tempCellY=tempCell.y;tempCell.y-=emptyAmount;const aniLoop=setInterval(()=>{tempCell.y+=OPTIONS.ANIMATION.SPEED/2,tempCell.y>=tempCellY&&(tempCell.y=tempCellY,clearInterval(aniLoop),resolver(!0))},OPTIONS.ANIMATION.FRAME)}return Promise.all(promiseTemp)}findEmptyCell(cells){return cells.find(cell=>cell.type==="")}filterEmptyCell(cells){return cells.filter(cell=>cell.type!=="")}fillNewCells(origin,emptyAmount,x){origin[0].y;const tempEmptyAmount=emptyAmount,temp=origin.map(cell=>cell.deepCopySelf());for(let index=1;index<=tempEmptyAmount;index++){const[type,score]=this.getRandomCellType(),copyCell=new Cell(type,x,1-index-1,score);temp.unshift(copyCell)}return temp}getEmptyStartPointAndAmount(x){const yValue=OPTIONS.WIDTH.GAME.Y-1;let startPoint=-1,emptyAmount=0;for(let level=yValue;level>=0;level--){const cell=this.map[level][x];cell.type===""&&(emptyAmount+=1,startPointcell.isSelected=!1)}}class Pointer extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");__publicField(this,"dependency",{});__publicField(this,"grab",null);__publicField(this,"swapTemp",[]);this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),window.addEventListener("mousemove",this.moveMouse.bind(this)),window.addEventListener("mousedown",this.clickCell.bind(this))}inject(module){this.logger.dir("inject").debug(`${capitalize(module.constructor.name)} is injected`),this.dependency[capitalize(module.constructor.name)]=module}async clickCell(){var _a,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m;if(this.mode==="test"){wait.length===0?(this.logger.only().dir("test").dir("clickCell").log("auto pang"),wait.push(0),await((_a=this.dependency.blockManager)==null?void 0:_a.autoPangAndFill(!1)),this.logger.debug(this.grab),wait.pop()):this.logger.only().dir("test").dir("clickCell").error("blocked click event");return}if(wait.length>0){this.logger.dir("clickCell").error("current working click event",wait),this.swapTemp=[];return}if(this.grab){if(this.logger.dir("clickCell").debug(this.grab),this.swapTemp.length<2&&(this.grab.isSelected=!0,this.swapTemp.push(this.grab),this.logger.dir("clickCell").log(this.swapTemp),this.logger.dir("clickCell").dir("select first cell").debug(this.swapTemp[0])),this.swapTemp.length===2){if(this.logger.dir("clickCell").log(this.swapTemp),this.logger.dir("clickCell").log("this.swapTemp length",2),this.dependency.blockManager&&this.swapTemp[0]!==this.swapTemp[1]&&wait.length===0){this.logger.dir("clickCell").dir("select second cell").debug(this.grab),wait.push(0),this.logger.dir("clickCell").log("swap both run");const isBoundary=this.dependency.blockManager.isInBoundary(this.swapTemp[0],this.swapTemp[1]);this.logger.dir("clickCell").debug("isBoundary",isBoundary),isBoundary&&((_b=this.dependency.scoreCalculator)==null||_b.turnCount());try{if(!await this.dependency.blockManager.swapBothCell(this.swapTemp[0],this.swapTemp[1])){this.logger.dir("swapBothCellAndFill").error("not swapped");const first=(_g=(_d=this.dependency.blockManager.map)==null?void 0:_d[(_c=this.swapTemp[0])==null?void 0:_c.y])==null?void 0:_g[(_f=(_e=this.swapTemp)==null?void 0:_e[0])==null?void 0:_f.x],second=(_l=(_i=this.dependency.blockManager.map)==null?void 0:_i[(_h=this.swapTemp[1])==null?void 0:_h.y])==null?void 0:_l[(_k=(_j=this.swapTemp)==null?void 0:_j[1])==null?void 0:_k.x];await this.dependency.blockManager.revertSwap(first,second),wait.pop(),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.swapTemp=[];return}}catch{return}await this.dependency.blockManager.autoPangAndFill(),this.logger.dir("clickCell").debug("release??"),wait.pop(),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.logger.dir("clickCell").log("swap both end")}this.logger.dir("clickCell").log(this.swapTemp),this.swapTemp[0]&&(this.swapTemp[0].isSelected=!1),this.swapTemp[1]&&(this.swapTemp[1].isSelected=!1),this.swapTemp=[],this.logger.dir("clickCell").log(this.swapTemp)}this.logger.dir("clickCell2").debug(this.swapTemp)}else this.logger.dir("clickCell").debug("no grab");this.logger.dir("clickCell").debug("map",(_m=this.dependency.blockManager)==null?void 0:_m.map)}moveMouse(e){const x=e.clientX,y=e.clientY,[resX,resY]=responsePointerAxis(x,y);try{const cell=this.getCellInfo(resX,resY);this.grab=cell,this.grab.isHover||(this.grab.isHover=!0)}catch{this.grab=null}}getCellInfo(x,y){var _a,_b;if(this.dependency.mapGenerator){const cell=(_b=(_a=this.dependency.mapGenerator.map)==null?void 0:_a[y])==null?void 0:_b[x];if(cell)return cell;throw new Error("not found cell")}throw new Error("no injected module")}}class QuestManager{constructor(mode){__publicField(this,"id");__publicField(this,"mode");__publicField(this,"quests",[]);__publicField(this,"logger");__publicField(this,"lineGap",16*1.8);__publicField(this,"animalsPang",{cat:0,dog:0,lion:0,duck:0,mouse:0,rabbit:0,panda:0,pig:0,racoon:0});__publicField(this,"dependency",{});this.mode=mode,this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode)}inject(module){this.logger.dir("inject").debug(`${capitalize(module.constructor.name)} is injected`),this.dependency[capitalize(module.constructor.name)]=module}addQuest(a,b,c,d){if(!(a instanceof Quest)&&b&&c!==void 0&&d){this.logger.dir("addQuest").log("add new quest");const newQeust=new Quest(a,b,c,d);this.quests.push(newQeust)}else if(a instanceof Quest)this.logger.dir("addQuest").log("add new quest"),this.quests.push(a);else throw new Error("Invalid quest arguments")}removeQuest(quest){quest.deletion=!0,setTimeout(()=>{this.quests=this.quests.filter(q=>!q.deletion),this.autoQuests()},3e3)}autoQuests(){if(this.dependency.blockManager)for(;this.quests.length<2;){const randomQuest=QUEST_LIST[Math.floor(QUEST_LIST.length*Math.random())];!this.quests.includes(randomQuest)&&this.dependency.blockManager.containsType(randomQuest.condition.type)&&this.quests.push(randomQuest)}}questAmountUp(type){const quests=this.quests.filter(quest=>quest.condition.type===type);this.logger.dir("questAmountUp").debug(type),quests.forEach(quest=>{console.log(quest),quest.currentAmount+=1})}render(){var _a;questCtx.font="normal 16px Arial";for(const quest of this.quests){const base=(this.quests.indexOf(quest)+1)*90+20;questCtx.font="bold 16px Arial",questCtx.fillText(quest.title+` (추가 점수 ${quest.score})`,50,base),quest.isDone&&questCtx.fillRect(50,base-6,questCtx.measureText(quest.title+` (추가 점수 ${quest.score})`).width,1),questCtx.font="normal 16px Arial",questCtx.fillText(quest.content,50,base+this.lineGap*1),quest.isDone&&questCtx.fillRect(50,base+this.lineGap*1-6,questCtx.measureText(quest.content).width,1),questCtx.fillText(`${quest.currentAmount}/${quest.condition.amount}`,50,base+this.lineGap*2),quest.isDone&&questCtx.fillRect(50,base+this.lineGap*2-6,questCtx.measureText(`${quest.currentAmount}/${quest.condition.amount}`).width,1),quest.currentAmount>=quest.condition.amount&&(quest.isDone||(quest.success(),(_a=this.dependency.scoreCalculator)==null||_a.scoreUp(quest.score),this.logger.dir("success").log(`clear quest, get score +${quest.score}`),this.removeQuest(quest)))}questCtx.font="normal 16px Arial"}}class ScoreCalculator extends BaseModule{constructor(mode){super(mode);__publicField(this,"logger");__publicField(this,"scores",0);__publicField(this,"turn",0);mode==="none"?this.turn=OPTIONS.GAME.TURN:mode==="test"&&(this.turn=1/0),this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode)}scoreUp(score){this.scores+=score,this.logger.dir("scoreUp").debug("get score",score)}turnCount(){this.logger.dir("turnCount").debug("count minus",this.turn),this.turn-=1}popupEndModal(){const wrap=document.createElement("div");wrap.id="modal",wrap.innerHTML=` + + + `,document.body.append(wrap)}render(){scoreCtx.font="bold 16px Arial",scoreCtx.textAlign="left",scoreCtx.fillStyle="#000000",scoreCtx.fillText(`score: ${this.scores} point${this.scores>1?"s":""}`,50,50),this.turn>5&&this.turn<10?scoreCtx.fillStyle="#ffff00":this.turn<=5&&(scoreCtx.fillStyle="#ff0000"),scoreCtx.fillText(`turn: ${this.turn} turn${this.scores>1?"s":""}`,50,70)}}class StoreManager extends BaseModule{constructor(mode,storeName){super(mode);__publicField(this,"storeName");__publicField(this,"logger");__publicField(this,"store",[]);this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").log("initialize mode:",mode),this.storeName=storeName||"pang_store",this.getData()}getLocalStorage(){return JSON.parse(localStorage.getItem(this.storeName)||"[]")}saveLocalStorage(){localStorage.setItem(this.storeName,JSON.stringify(this.store))}saveStore(data){this.store=data}getStore(){return this.store}getData(){const data=this.getLocalStorage();this.saveStore(data)}saveData(data){this.saveStore(data),this.saveLocalStorage()}addData(data){this.store.push(data),this.saveLocalStorage()}}class GameCore extends BaseModule{constructor(){super(RUN_MODE);__publicField(this,"seek",0);__publicField(this,"blockManager");__publicField(this,"animator");__publicField(this,"mapGenerator");__publicField(this,"scoreCalculator");__publicField(this,"storeManager");__publicField(this,"pointer");__publicField(this,"questManager");__publicField(this,"logger");__publicField(this,"canvases",[]);__publicField(this,"gameEnd",!1);__publicField(this,"_dev");__publicField(this,"_runMode");__publicField(this,"_baseWidth",innerWidth);__publicField(this,"_baseHeight",innerHeight);__publicField(this,"_storeName");__publicField(this,"_animation");__publicField(this,"questQueue",[]);__publicField(this,"handleResizeCanvasSize",()=>{this.logger.dir("setupCanvas").dir("handleResizeCanvasSize").log("resize all canvas");for(const canvas of this.canvases)canvas.width=innerWidth,canvas.height=innerHeight,this.logger.dir("handleResizeCanvasSize").dir("if").debug(this._baseWidth,innerWidth,RESPONSIVE_UNIT_SIZE()),innerWidth<=280?SUB_OPTIONS.SIZE.RATIO=-25:innerWidth<=375?SUB_OPTIONS.SIZE.RATIO=-15:innerWidth<=390?SUB_OPTIONS.SIZE.RATIO=-14:innerWidth<=393?SUB_OPTIONS.SIZE.RATIO=-15:innerWidth<=414?SUB_OPTIONS.SIZE.RATIO=-12:innerWidth<=540?SUB_OPTIONS.SIZE.RATIO=-3:innerWidth<=820?SUB_OPTIONS.SIZE.RATIO=15:innerWidth<=1024?SUB_OPTIONS.SIZE.RATIO=5:innerWidth<=1280?SUB_OPTIONS.SIZE.RATIO=6:SUB_OPTIONS.SIZE.RATIO=5});this.logger=new Logger(this.constructor.name),this.logger.dir("constructor").debug("dev",this._dev),this.logger.dir("constructor").debug("run mode",this._runMode),this.logger.dir("constructor").log("setup game core..."),window.addEventListener("click",this.handleNewGame.bind(this))}initialCommitQuestInQueue(){for(;this.questQueue.length>0;){const quest=this.questQueue.pop();quest&&this.questManager.addQuest(quest)}}newGame(){this.gameEnd=!1;const map=this.blockManager.initialize();this.mapGenerator.initialize(map),this.scoreCalculator.turn=OPTIONS.GAME.TURN,this.scoreCalculator.scores=0,this.blockManager.animalsPang={cat:0,dog:0,lion:0,duck:0,mouse:0,rabbit:0,panda:0,pig:0,racoon:0},setTimeout(()=>{this.execInitialPang()},16)}stopRender(){cancelAnimationFrame(this._animation)}handleNewGame(e){const target=e.target;wait.length>0&&target&&target.id==="newGame"?(this.newGame(),window.removeEventListener("click",this.handleNewGame.bind(this)),wait.splice(0),setTimeout(()=>{document.querySelectorAll("#modal").forEach(modal=>modal.remove())},10)):target&&target.id==="modal-close"&&document.querySelectorAll("#modal").forEach(modal=>modal.remove()),document.querySelectorAll("#modal").forEach(modal=>modal.remove())}setOption(property,value){if(`_${property}`in this)this.logger.dir("setOption").log(`success set option, property: ${property}, value: ${value}`),this[`_${property}`]=value;else throw new Error(`${property} is not a valid property`)}initialize(){this.logger.dir("initialize").log("initialize"),this.loadModules(),this.initialCommitQuestInQueue(),this.setupCanvas(bgCanvas,gameCanvas,effectCanvas,scoreCanvas,selectCanvas,questCanvas),this.injection();const map=this.blockManager.initialize();this.mapGenerator.initialize(map)}autoQuests(){this.questManager.autoQuests()}loadModules(){this.logger.dir("loadModules").log("start..."),this.scoreCalculator=new ScoreCalculator(this.mode),this.questManager=new QuestManager(this.mode),this.blockManager=new BlockManager(this.mode,this.scoreCalculator,this.questManager),this.questManager.animalsPang=this.blockManager.animalsPang,this.animator=new Animator(this.mode),this.mapGenerator=new MapGenerator(this.mode),this.pointer=new Pointer(this.mode),this.storeManager=new StoreManager(this.mode,this._storeName),this.logger.dir("loadModules").log("success!")}setupCanvas(...canvases){this.canvases=canvases,this.logger.dir("setupCanvas").log("setup canvas elements");for(const canvas of canvases)this.logger.dir("setupCanvas").log(`add ${canvas.id} canvas`),ROOT.append(canvas);this.handleResizeCanvasSize(),this.logger.dir("setupCanvas").log("add event window resize detect"),window.addEventListener("resize",this.handleResizeCanvasSize.bind(this))}injection(){this.pointer.inject(this.blockManager),this.pointer.inject(this.mapGenerator),this.pointer.inject(this.scoreCalculator),this.questManager.inject(this.blockManager),this.questManager.inject(this.scoreCalculator)}animation(time){this.clearRect(),time*=.001,wait.length===0&&!this.gameEnd&&this.scoreCalculator.turn===0&&(wait.push(0),this.gameEnd=!0,this.scoreCalculator.popupEndModal()),Math.floor(time),this.seek,this.scoreCalculator.render(),this.mapGenerator.render(),this.blockManager.render(),this.questManager.render(),bgCtx.restore(),scoreCtx.restore(),gameCtx.restore(),selectCtx.restore(),effectCtx.restore(),questCtx.restore(),this._animation=requestAnimationFrame(this.animation.bind(this)),this.seek=Math.floor(time)}clearRect(){bgCtx.clearRect(0,0,innerWidth,innerHeight),scoreCtx.clearRect(0,0,innerWidth,innerHeight),gameCtx.clearRect(0,0,innerWidth,innerHeight),effectCtx.clearRect(0,0,innerWidth,innerHeight),selectCtx.clearRect(0,0,innerWidth,innerHeight),questCtx.clearRect(0,0,innerWidth,innerHeight),bgCtx.save(),scoreCtx.save(),gameCtx.save(),effectCtx.save(),selectCtx.save(),questCtx.save()}render(){this.logger.dir("render").log("start game core rendering..."),this.logger.dir("render").log("start calulator rendering..."),this.logger.dir("render").log("start game map rendering..."),this.logger.dir("render").log("start block rendering..."),setTimeout(()=>{this.execInitialPang()},1e3),this._animation=requestAnimationFrame(this.animation.bind(this))}execInitialPang(){this.mode!=="test"&&wait.length===0&&(wait.push(0),this.blockManager.autoPangAndFill().then(()=>{wait.pop()}))}renderPerSecond(){}}const gameCore=new GameCore;gameCore.setOption("dev",MODE);gameCore.setOption("runMode",RUN_MODE);gameCore.setOption("storeName",STORE_NAME);gameCore.initialize();gameCore.autoQuests();gameCore.render(); diff --git a/index.html b/index.html index e4bc8a3..97c4f4e 100644 --- a/index.html +++ b/index.html @@ -6,7 +6,7 @@ Pang - +