kontra
Version:
Kontra HTML5 game development library
5 lines • 33.1 kB
JavaScript
/**
* @preserve
* Kontra.js v10.0.2
*/
var kontra=function(){function t(t,e){let i=Math.sin(e),s=Math.cos(e);return{x:t.x*s-t.y*i,y:t.x*i+t.y*s}}function e(t,e,i){return Math.min(Math.max(t,i),e)}function i(t,e){let i=s(t),n=s(e);return i.x<n.x+n.width&&i.x+i.width>n.x&&i.y<n.y+n.height&&i.y+i.height>n.y}function s(t){let{x:e=0,y:i=0,width:s,height:n,radius:h}=t.world||t;return t.mapwidth&&(s=t.mapwidth,n=t.mapheight),t.anchor&&(e-=s*t.anchor.x,i-=n*t.anchor.y),s<0&&(e+=s,s*=-1),n<0&&(i+=n,n*=-1),{x:e,y:i,width:s,height:n}}let n=()=>{},h="position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0,0,0,0);",r={preventScroll:!0};function a(t,e){let i=e.parentNode;if(t.setAttribute("data-kontra",""),i){([...i.querySelectorAll(":scope > [data-kontra]")].pop()||e).after(t)}else"CANVAS"==e.nodeName?document.body.append(t):e.append(t)}function o(t,e){let i=t.indexOf(e);if(-1!=i)return t.splice(i,1),!0}function d(t,e){let{x:i,y:n,width:h,height:r}=s(e);do{i-=e.sx||0,n-=e.sy||0}while(e=e.parent);let a=t.x-Math.max(i,Math.min(t.x,i+h)),o=t.y-Math.max(n,Math.min(t.y,n+r));return a*a+o*o<t.radius*t.radius}let c,l,u={};function p(t,e){u[t]=u[t]||[],u[t].push(e)}function _(t,e){u[t]=(u[t]||[]).filter((t=>t!=e))}function f(t,...e){(u[t]||[]).map((t=>t(...e)))}let g={get:(t,e)=>"_proxy"==e||n};function m(){return c}function w(){return l}class x{constructor({spriteSheet:t,frames:e,frameRate:i,loop:s=!0,name:n}){let{width:h,height:r,spacing:a=0,margin:o=0}=t.frame;Object.assign(this,{spriteSheet:t,frames:e,frameRate:i,loop:s,name:n,width:h,height:r,spacing:a,margin:o,isStopped:!1,_f:0,_a:0})}clone(){return new x(this)}start(){this.isStopped=!1,this.loop||this.reset()}stop(){this.isStopped=!0}reset(){this._f=0,this._a=0}update(t=1/60){if(!this.isStopped)if(this.loop||this._f!=this.frames.length-1)for(this._a+=t;this._a*this.frameRate>=1;)this._f=++this._f%this.frames.length,this._a-=1/this.frameRate;else this.stop()}render({x:t,y:e,width:i=this.width,height:s=this.height,context:n=w()}){let h=this.frames[this._f]/this.spriteSheet._f|0,r=this.frames[this._f]%this.spriteSheet._f|0;n.drawImage(this.spriteSheet.image,this.margin+r*this.width+(2*r+1)*this.spacing,this.margin+h*this.height+(2*h+1)*this.spacing,this.width,this.height,t,e,i,s)}}function y(){return new x(...arguments)}let b=/(jpeg|jpg|gif|png|webp)$/,v=/(wav|mp3|ogg|aac)$/,S=/^\//,C=/\/$/,A=new WeakMap,k="",j="",M="";function E(t,e){return new URL(t,e).href}function P(t,e){return[t.replace(C,""),t?e.replace(S,""):e].filter((t=>t)).join("/")}function O(t){return t.split(".").pop()}function L(t){let e=t.replace("."+O(t),"");return 2==e.split("/").length?e.replace(S,""):e}let I={},D={},G={};function N(){window.__k||(window.__k={dm:A,u:E,d:G,i:I})}function X(t){return N(),new Promise(((e,i)=>{let s,n,h;if(s=P(k,t),I[s])return e(I[s]);n=new Image,n.onload=function(){h=E(s,window.location.href),I[L(t)]=I[s]=I[h]=this,f("assetLoaded",this,t),e(this)},n.onerror=function(){i(s)},n.src=s}))}function Y(t){return new Promise(((e,i)=>{let s,n,h,r,a=t;var o;return s=new Audio,n={wav:(o=s).canPlayType('audio/wav; codecs="1"'),mp3:o.canPlayType("audio/mpeg;"),ogg:o.canPlayType('audio/ogg; codecs="vorbis"'),aac:o.canPlayType("audio/aac;")},(t=[].concat(t).reduce(((t,e)=>t||(n[O(e)]?e:null)),0))?(h=P(j,t),D[h]?e(D[h]):(s.addEventListener("canplay",(function(){r=E(h,window.location.href),D[L(t)]=D[h]=D[r]=this,f("assetLoaded",this,t),e(this)})),s.onerror=function(){i(h)},s.src=h,void s.load())):i(a)}))}function T(t){let e,i;return N(),e=P(M,t),G[e]?Promise.resolve(G[e]):fetch(e).then((t=>{if(!t.ok)throw t;return t.clone().json().catch((()=>t.text()))})).then((s=>(i=E(e,window.location.href),"object"==typeof s&&A.set(s,i),G[L(t)]=G[e]=G[i]=s,f("assetLoaded",s,t),s)))}class z{constructor(t=0,e=0,i={}){null!=t.x?(this.x=t.x,this.y=t.y):(this.x=t,this.y=e),i._c&&(this.clamp(i._a,i._b,i._d,i._e),this.x=t,this.y=e)}set(t){this.x=t.x,this.y=t.y}add(t){return new z(this.x+t.x,this.y+t.y,this)}subtract(t){return new z(this.x-t.x,this.y-t.y,this)}scale(t){return new z(this.x*t,this.y*t)}normalize(t=this.length()||1){return new z(this.x/t,this.y/t)}dot(t){return this.x*t.x+this.y*t.y}length(){return Math.hypot(this.x,this.y)}distance(t){return Math.hypot(this.x-t.x,this.y-t.y)}angle(t){return Math.acos(this.dot(t)/(this.length()*t.length()))}direction(){return Math.atan2(this.y,this.x)}clamp(t,e,i,s){this._c=!0,this._a=t,this._b=e,this._d=i,this._e=s}get x(){return this._x}get y(){return this._y}set x(t){this._x=this._c?e(this._a,this._d,t):t}set y(t){this._y=this._c?e(this._b,this._e,t):t}}function R(){return new z(...arguments)}class W extends class{constructor(t){return this.init(t)}init(t={}){this.position=R(),this.velocity=R(),this.acceleration=R(),this.ttl=1/0,Object.assign(this,t)}update(t){this.advance(t)}advance(t){let e=this.acceleration;t&&(e=e.scale(t)),this.velocity=this.velocity.add(e);let i=this.velocity;t&&(i=i.scale(t)),this.position=this.position.add(i),this._pc(),this.ttl--}get dx(){return this.velocity.x}get dy(){return this.velocity.y}set dx(t){this.velocity.x=t}set dy(t){this.velocity.y=t}get ddx(){return this.acceleration.x}get ddy(){return this.acceleration.y}set ddx(t){this.acceleration.x=t}set ddy(t){this.acceleration.y=t}isAlive(){return this.ttl>0}_pc(){}}{init({width:t=0,height:e=0,context:i=w(),render:s=this.draw,update:n=this.advance,children:h=[],anchor:r={x:0,y:0},opacity:a=1,rotation:o=0,drotation:d=0,ddrotation:c=0,scaleX:l=1,scaleY:u=1,..._}={}){this._c=[],super.init({width:t,height:e,context:i,anchor:r,opacity:a,rotation:o,drotation:d,ddrotation:c,scaleX:l,scaleY:u,..._}),this._di=!0,this._uw(),this.addChild(h),this._rf=s,this._uf=n,p("init",(()=>{this.context??=w()}))}update(t){this._uf(t),this.children.map((e=>e.update&&e.update(t)))}render(){let t=this.context;t.save(),(this.x||this.y)&&t.translate(this.x,this.y),this.rotation&&t.rotate(this.rotation),1==this.scaleX&&1==this.scaleY||t.scale(this.scaleX,this.scaleY);let e=this.width,i=this.height,s=-e*this.anchor.x,n=-i*this.anchor.y;(s||n)&&t.translate(s,n),this.context.globalAlpha=this.opacity,this._rf(),(s||n)&&t.translate(-s,-n),this.children.map((t=>t.render&&t.render())),t.restore()}draw(){}_pc(){this._uw(),this.children.map((t=>t._pc()))}get x(){return this.position.x}get y(){return this.position.y}set x(t){this.position.x=t,this._pc()}set y(t){this.position.y=t,this._pc()}get width(){return this._w}set width(t){this._w=t,this._pc()}get height(){return this._h}set height(t){this._h=t,this._pc()}_uw(){if(!this._di)return;let{_wx:e=0,_wy:i=0,_wo:s=1,_wrot:n=0,_wsx:h=1,_wsy:r=1}=this.parent||{};this._wx=this.x,this._wy=this.y,this._ww=this.width,this._wh=this.height,this._wo=s*this.opacity,this._wsx=h*this.scaleX,this._wsy=r*this.scaleY,this._wx=this._wx*h,this._wy=this._wy*r,this._ww=this.width*this._wsx,this._wh=this.height*this._wsy,this._wrot=n+this.rotation;let{x:a,y:o}=t({x:this._wx,y:this._wy},n);this._wx=a,this._wy=o,this._wx+=e,this._wy+=i}get world(){return{x:this._wx,y:this._wy,width:this._ww,height:this._wh,opacity:this._wo,rotation:this._wrot,scaleX:this._wsx,scaleY:this._wsy}}set children(t){this.removeChild(this._c),this.addChild(t)}get children(){return this._c}addChild(...t){t.flat().map((t=>{this.children.push(t),t.parent=this,t._pc=t._pc||n,t._pc()}))}removeChild(...t){t.flat().map((t=>{o(this.children,t)&&(t.parent=null,t._pc())}))}get opacity(){return this._opa}set opacity(t){this._opa=e(0,1,t),this._pc()}get rotation(){return this._rot}set rotation(t){this._rot=t,this._pc()}advance(t){super.advance(t),this.drotation+=this.ddrotation,this.rotation+=this.drotation}setScale(t,e=t){this.scaleX=t,this.scaleY=e}get scaleX(){return this._scx}set scaleX(t){this._scx=t,this._pc()}get scaleY(){return this._scy}set scaleY(t){this._scy=t,this._pc()}}class F extends W{init({image:t,width:e=(t?t.width:void 0),height:i=(t?t.height:void 0),...s}={}){super.init({image:t,width:e,height:i,...s})}get animations(){return this._a}set animations(t){let e,i;for(e in this._a={},t)this._a[e]=t[e].clone(),i=i||this._a[e];this.currentAnimation=i,this.width=this.width||i.width,this.height=this.height||i.height}playAnimation(t){this.currentAnimation?.stop(),this.currentAnimation=this.animations[t],this.currentAnimation.start()}advance(t){super.advance(t),this.currentAnimation?.update(t)}draw(){this.image&&this.context.drawImage(this.image,0,0,this.image.width,this.image.height),this.currentAnimation&&this.currentAnimation.render({x:0,y:0,width:this.width,height:this.height,context:this.context}),this.color&&(this.context.fillStyle=this.color,this.context.fillRect(0,0,this.width,this.height))}}let B=/(\d+)(\w+)/;class H extends W{init({text:t="",textAlign:e="",lineHeight:i=1,font:s=w()?.font,...n}={}){t=""+t,super.init({text:t,textAlign:e,lineHeight:i,font:s,...n}),this.context&&this._p(),p("init",(()=>{this.font??=w().font,this._p()}))}get width(){return this._w}set width(t){this._d=!0,this._w=t,this._fw=t}get text(){return this._t}set text(t){this._d=!0,this._t=""+t}get font(){return this._f}set font(t){this._d=!0,this._f=t,this._fs=function(t){if(!t)return{computed:0};let e=t.match(B),i=+e[1];return{size:i,unit:e[2],computed:i}}(t).computed}get lineHeight(){return this._lh}set lineHeight(t){this._d=!0,this._lh=t}render(){this._d&&this._p(),super.render()}_p(){this._s=[],this._d=!1;let t=this.context,e=[this.text];if(t.font=this.font,e=this.text.split("\n"),this._fw&&e.map((e=>{let i=e.split(" "),s=i.shift(),n=s;i.map((e=>{n+=" "+e,t.measureText(n).width>this._fw&&(this._s.push(s),n=e),s=n})),this._s.push(n)})),!this._s.length&&this.text.includes("\n")){let i=0;e.map((e=>{this._s.push(e),i=Math.max(i,t.measureText(e).width)})),this._w=this._fw||i}this._s.length||(this._s.push(this.text),this._w=this._fw||t.measureText(this.text).width),this.height=this._fs+(this._s.length-1)*this._fs*this.lineHeight,this._uw()}draw(){let t=0,e=this.textAlign,i=this.context;e=this.textAlign||("rtl"==i.canvas.dir?"right":"left"),t="right"==e?this.width:"center"==e?this.width/2|0:0,this._s.map(((s,n)=>{i.textBaseline="top",i.textAlign=e,i.fillStyle=this.color,i.font=this.font,this.strokeColor&&(i.strokeStyle=this.strokeColor,i.lineWidth=this.lineWidth??1,i.strokeText(s,t,this._fs*this.lineHeight*n)),i.fillText(s,t,this._fs*this.lineHeight*n)}))}}function U(){return new H(...arguments)}let q=new WeakMap,K={},V={},$={0:"left",1:"middle",2:"right"};function J(t){let e=t._lf.length?t._lf:t._cf;for(let i=e.length-1;i>=0;i--){let s=e[i];if(s.collidesWithPointer?s.collidesWithPointer(t):d(t,s))return s}}function Q(t,e){return parseFloat(t.getPropertyValue(e))||0}function Z(t){let e=null!=t.button?$[t.button]:"left";V[e]=!0,nt(t,"onDown")}function tt(t){let e=null!=t.button?$[t.button]:"left";V[e]=!1,nt(t,"onUp")}function et(t){nt(t,"onOver")}function it(t){q.get(t.target)._oo=null,V={}}function st(t,e,i){let s=J(t);s&&s[e]&&s[e](i),K[e]&&K[e](i,s),"onOver"==e&&(s!=t._oo&&t._oo&&t._oo.onOut&&t._oo.onOut(i),t._oo=s)}function nt(t,e){t.preventDefault();let i=t.target,s=q.get(i),{scaleX:n,scaleY:h,offsetX:r,offsetY:a}=function(t){let{canvas:e,_s:i}=t,s=e.getBoundingClientRect(),n="none"!=i.transform?i.transform.replace("matrix(","").split(","):[1,1,1,1],h=parseFloat(n[0]),r=parseFloat(n[3]),a=(Q(i,"border-left-width")+Q(i,"border-right-width"))*h,o=(Q(i,"border-top-width")+Q(i,"border-bottom-width"))*r,d=(Q(i,"padding-left")+Q(i,"padding-right"))*h,c=(Q(i,"padding-top")+Q(i,"padding-bottom"))*r;return{scaleX:(s.width-a-d)/e.width,scaleY:(s.height-o-c)/e.height,offsetX:s.left+(Q(i,"border-left-width")+Q(i,"padding-left"))*h,offsetY:s.top+(Q(i,"border-top-width")+Q(i,"padding-top"))*r}}(s);t.type.includes("touch")?(Array.from(t.touches).map((({clientX:t,clientY:e,identifier:i})=>{let o=s.touches[i];o||(o=s.touches[i]={start:{x:(t-r)/n,y:(e-a)/h}},s.touches.length++),o.changed=!1})),Array.from(t.changedTouches).map((({clientX:i,clientY:o,identifier:d})=>{let c=s.touches[d];c.changed=!0,c.x=s.x=(i-r)/n,c.y=s.y=(o-a)/h,st(s,e,t),f("touchChanged",t,s.touches),"onUp"==e&&(delete s.touches[d],s.touches.length--,s.touches.length||f("touchEnd"))}))):(s.x=(t.clientX-r)/n,s.y=(t.clientY-a)/h,st(s,e,t))}function ht({radius:t=5,canvas:e=m()}={}){let i=q.get(e);if(!i){let s=window.getComputedStyle(e);i={x:0,y:0,radius:t,touches:{length:0},canvas:e,_cf:[],_lf:[],_o:[],_oo:null,_s:s},q.set(e,i)}return e.addEventListener("mousedown",Z),e.addEventListener("touchstart",Z),e.addEventListener("mouseup",tt),e.addEventListener("touchend",tt),e.addEventListener("touchcancel",tt),e.addEventListener("blur",it),e.addEventListener("mousemove",et),e.addEventListener("touchmove",et),i._t||(i._t=!0,p("tick",(()=>{i._lf.length=0,i._cf.map((t=>{i._lf.push(t)})),i._cf.length=0}))),i}function rt(...t){t.flat().map((t=>{let e=t.context?t.context.canvas:m(),i=q.get(e);t.__r||(t.__r=t.render,t.render=function(){i._cf.push(this),this.__r()},i._o.push(t))}))}function at(t,e){let i=t[0].toUpperCase()+t.substr(1);K["on"+i]=e}function ot(t){let e=t[0].toUpperCase()+t.substr(1);K["on"+e]=0}class dt extends F{init({padX:t=0,padY:e=0,text:i,disabled:s=!1,container:r,onDown:o,onUp:d,...c}={}){super.init({padX:t,padY:e,...c}),this.textNode=U({...i,context:this.context}),this.width||(this.width=this.textNode.width,this.height=this.textNode.height),rt(this),this.addChild(this.textNode),this._od=o||n,this._ou=d||n;let l=this._dn=document.createElement("button");l.style=h,l.textContent=this.text,s&&this.disable(),l.addEventListener("focus",(()=>this.focus())),l.addEventListener("blur",(()=>this.blur())),l.addEventListener("keydown",(t=>this._kd(t))),l.addEventListener("keyup",(t=>this._ku(t))),a(l,r??this.context.canvas),this._uw(),this._p()}get text(){return this.textNode.text}set text(t){this._d=!0,this.textNode.text=t}get node(){return this._dn}destroy(){this._dn.remove()}_p(){this.text!=this._dn.textContent&&(this._dn.textContent=this.text),this.textNode._p();let t=this.textNode.width+2*this.padX,e=this.textNode.height+2*this.padY;this.width=Math.max(t,this.width),this.height=Math.max(e,this.height),this._uw()}render(){this._d&&this._p(),super.render()}enable(){this.disabled=this._dn.disabled=!1,this.onEnable()}disable(){this.disabled=this._dn.disabled=!0,this.onDisable()}focus(){this.disabled||(this.focused=!0,document.activeElement!=this._dn&&this._dn.focus(r),this.onFocus())}blur(){this.focused=!1,document.activeElement==this._dn&&this._dn.blur(),this.onBlur()}onOver(){this.disabled||(this.hovered=!0)}onOut(){this.hovered=!1}onEnable(){}onDisable(){}onFocus(){}onBlur(){}onDown(){this.disabled||(this.pressed=!0,this._od())}onUp(){this.disabled||(this.pressed=!1,this._ou())}_kd(t){"Enter"!=t.code&&"Space"!=t.code||this.onDown()}_ku(t){"Enter"!=t.code&&"Space"!=t.code||this.onUp()}}function ct(t){let e=t.canvas;t.clearRect(0,0,e.width,e.height)}let lt=[],ut={},pt={},_t={0:"south",1:"east",2:"west",3:"north",4:"leftshoulder",5:"rightshoulder",6:"lefttrigger",7:"righttrigger",8:"select",9:"start",10:"leftstick",11:"rightstick",12:"dpadup",13:"dpaddown",14:"dpadleft",15:"dpadright"};function ft(t){lt[t.gamepad.index]={pressedButtons:{},axes:{}}}function gt(t){delete lt[t.gamepad.index]}function mt(){lt.map((t=>{t.pressedButtons={},t.axes={}}))}function wt(){let t=navigator.getGamepads?navigator.getGamepads():navigator.webkitGetGamepads?navigator.webkitGetGamepads:[];for(let e=0;e<t.length;e++){let i=t[e];if(!i)continue;i.buttons.map(((t,e)=>{let s=_t[e],{pressed:n}=t,{pressedButtons:h}=lt[i.index],r=h[s];!r&&n?[ut[i.index],ut].map((e=>{e?.[s]?.(i,t,s)})):r&&!n&&[pt[i.index],pt].map((e=>{e?.[s]?.(i,t,s)})),h[s]=n}));let{axes:s}=lt[i.index];s.leftstickx=i.axes[0],s.leftsticky=i.axes[1],s.rightstickx=i.axes[2],s.rightsticky=i.axes[3]}}function xt(){window.addEventListener("gamepadconnected",ft),window.addEventListener("gamepaddisconnected",gt),window.addEventListener("blur",mt),p("tick",wt)}function yt(t,e,{gamepad:i,handler:s="gamepaddown"}={}){let n="gamepaddown"==s?ut:pt;[].concat(t).map((t=>{isNaN(i)?n[t]=e:(n[i]=n[i]||{},n[i][t]=e)}))}function bt(t,{gamepad:e,handler:i="gamepaddown"}={}){let s="gamepaddown"==i?ut:pt;[].concat(t).map((t=>{isNaN(e)?delete s[t]:(s[e]=s[e]||{},delete s[e][t])}))}let vt,St={},Ct=!1,At={swipe:{touches:1,threshold:10,touchend({0:t}){let e=t.x-t.start.x,i=t.y-t.start.y,s=Math.abs(e),n=Math.abs(i);if(!(s<this.threshold&&n<this.threshold))return s>n?e<0?"left":"right":i<0?"up":"down"}},pinch:{touches:2,threshold:2,touchstart({0:t,1:e}){this.prevDist=Math.hypot(t.x-e.x,t.y-e.y)},touchmove({0:t,1:e}){let i=Math.hypot(t.x-e.x,t.y-e.y);if(Math.abs(i-this.prevDist)<this.threshold)return;let s=i>this.prevDist?"out":"in";return this.prevDist=i,s}}};function kt(){Ct||(Ct=!0,p("touchChanged",((t,e)=>{Object.keys(At).map((i=>{let s,n=At[i];(!vt||vt==i)&&e.length==n.touches&&[...Array(e.length).keys()].every((t=>e[t]))&&(s=n[t.type]?.(e)??"")&&St[i+s]&&(vt=i,St[i+s](t,e))}))})),p("touchEnd",(()=>{vt=0})))}function jt(t,e){[].concat(t).map((t=>{St[t]=e}))}function Mt(t){[].concat(t).map((t=>{St[t]=0}))}let Et={set:(t,e,i)=>(e.startsWith("_")||(t._d=!0),Reflect.set(t,e,i))},Pt={start:t=>t?1:0,center:()=>.5,end:t=>t?0:1};class Ot extends W{init({flow:t="column",align:e="start",justify:i="start",colGap:s=0,rowGap:n=0,numCols:h=1,dir:r="",breakpoints:a=[],...o}={}){return super.init({flow:t,align:e,justify:i,colGap:s,rowGap:n,numCols:h,dir:r,breakpoints:a,...o}),this._p(),new Proxy(this,Et)}addChild(t){this._d=!0,super.addChild(t)}removeChild(t){this._d=!0,super.removeChild(t)}render(){this._d&&this._p(),super.render()}destroy(){this.children.map((t=>t.destroy&&t.destroy()))}_p(){this._d=!1,this.breakpoints.map((t=>{t.metric.call(this)&&this._b!==t&&(this._b=t,t.callback.call(this))}));let t=this._g=[],e=this._cw=[],i=this._rh=[],s=this.children,n=this._nc="column"==this.flow?1:"row"==this.flow?s.length:this.numCols,h=0,r=0;for(let a,o=0;a=s[o];o++){t[h]=t[h]||[],a._p&&a._p();let{width:s,height:o}=a.world||a;i[h]=Math.max(i[h]||0,o);let d=a.colSpan||1,c=d;do{e[r]=Math.max(e[r]||0,s/c),t[h][r]=a}while(r++<=n&&--d);r>=n&&(r=0,h++)}for(;r>0&&r<n;)t[h][r++]=!1;let a=t.length,o=[].concat(this.colGap),d=[].concat(this.rowGap);this._w=e.reduce(((t,e)=>t+e),0);for(let t=0;t<n-1;t++)this._w+=o[t%o.length];this._h=i.reduce(((t,e)=>t+e),0);for(let t=0;t<a-1;t++)this._h+=d[t%d.length];this._uw();let c="rtl"==this.context.canvas.dir&&!this.dir||"rtl"==this.dir;this._rtl=c,c&&(this._g=t.map((t=>t.reverse())),this._cw=e.reverse(),o=o.reverse());let l=-this.anchor.y*this.height,u=[],p=[].concat(this.justify),_=[].concat(this.align);this._g.map(((t,s)=>{let n=-this.anchor.x*this.width;t.map(((t,h)=>{if(t&&!u.includes(t)){u.push(t);let r=Pt[t.justifySelf||p[h%p.length]](this._rtl),a=Pt[t.alignSelf||_[s%_.length]](),d=t.colSpan||1,c=e[h];if(d>1&&h+d<=this._nc)for(let t=1;t<d;t++)c+=e[h+t]+o[(h+t)%o.length];let f=c*r,g=i[s]*a,m=0,w=0,{width:x,height:y}=t.world||t;if(t.anchor&&(m=t.anchor.x,w=t.anchor.y),0==r)f+=x*m;else if(.5==r){f+=(m<.5?-1:.5==m?0:1)*x*r}else f-=x*(1-m);if(0==a)g+=y*w;else if(.5==a){g+=(w<.5?-1:.5==w?0:1)*y*a}else g-=y*(1-w);t.x=n+f,t.y=l+g}n+=e[h]+o[h%o.length]})),l+=i[s]+d[s%d.length]}))}}let Lt,It={},Dt={},Gt={},Nt={Enter:"enter",Escape:"esc",Space:"space",ArrowLeft:"arrowleft",ArrowUp:"arrowup",ArrowRight:"arrowright",ArrowDown:"arrowdown"};function Xt(t=n,e){t._pd&&e.preventDefault(),t(e)}function Yt(t){let e=Nt[t.code],i=It[e];Gt[e]=!0,Xt(i,t)}function Tt(t){let e=Nt[t.code],i=Dt[e];Gt[e]=!1,Xt(i,t)}function zt(){Gt={}}function Rt(){let t;for(t=0;t<26;t++)Nt["Key"+String.fromCharCode(t+65)]=String.fromCharCode(t+97);for(t=0;t<10;t++)Nt["Digit"+t]=Nt["Numpad"+t]=""+t;window.addEventListener("keydown",Yt),window.addEventListener("keyup",Tt),window.addEventListener("blur",zt)}function Wt(t,e,{handler:i="keydown",preventDefault:s=!0}={}){let n="keydown"==i?It:Dt;e._pd=s,[].concat(t).map((t=>n[t]=e))}function Ft(t,{handler:e="keydown"}={}){let i="keydown"==e?It:Dt;[].concat(t).map((t=>delete i[t]))}function Bt(t,e){return Object.values(e).includes(t)}function Ht(t){return Object.keys(At).some((e=>t.startsWith(e)))}function Ut(t){let e=t.substr(t.search(/[A-Z]/));return e[0].toLowerCase()+e.substr(1)}class qt{constructor({create:t,maxSize:e=1024}={}){this._c=t,this.objects=[t()],this.size=0,this.maxSize=e}get(t={}){if(this.size==this.objects.length){if(this.size==this.maxSize)return;for(let t=0;t<this.size&&this.objects.length<this.maxSize;t++)this.objects.push(this._c())}let e=this.objects[this.size];return this.size++,e.init(t),e}getAliveObjects(){return this.objects.slice(0,this.size)}clear(){this.size=this.objects.length=0,this.objects.push(this._c())}update(t){let e,i=!1;for(let s=this.size;s--;)e=this.objects[s],e.update(t),e.isAlive()||(i=!0,this.size--);i&&this.objects.sort(((t,e)=>e.isAlive()-t.isAlive()))}render(){for(let t=this.size;t--;)this.objects[t].render()}}function Kt(t,e){let i=[],s=e.x+e.width/2,n=e.y+e.height/2,h=t.y<n,r=t.y+t.height>=n;return t.x<s&&(h&&i.push(0),r&&i.push(2)),t.x+t.width>=s&&(h&&i.push(1),r&&i.push(3)),i}class Vt{constructor({maxDepth:t=3,maxObjects:e=25,bounds:i}={}){this.maxDepth=t,this.maxObjects=e;let s=m();this.bounds=i||{x:0,y:0,width:s.width,height:s.height},this._b=!1,this._d=0,this._o=[],this._s=[],this._p=null}clear(){this._s.map((t=>{t.clear()})),this._b=!1,this._o.length=0}get(t){let e=new Set;for(;this._s.length&&this._b;)return Kt(t,this.bounds).map((i=>{this._s[i].get(t).map((t=>e.add(t)))})),Array.from(e);return this._o.filter((e=>e!==t))}add(...t){t.flat().map((t=>{this._b?this._a(t):(this._o.push(t),this._o.length>this.maxObjects&&this._d<this.maxDepth&&(this._sp(),this._o.map((t=>this._a(t))),this._o.length=0))}))}_a(t){Kt(t,this.bounds).map((e=>{this._s[e].add(t)}))}_sp(t,e,i){if(this._b=!0,!this._s.length)for(t=this.bounds.width/2|0,e=this.bounds.height/2|0,i=0;i<4;i++)this._s[i]=new Vt({bounds:{x:this.bounds.x+(i%2==1?t:0),y:this.bounds.y+(i>=2?e:0),width:t,height:e},maxDepth:this.maxDepth,maxObjects:this.maxObjects}),this._s[i]._d=this._d+1}}function $t(){Lt??=Date.now(),Lt|=0,Lt=Lt+2654435769|0;let t=Lt^Lt>>>16;return t=Math.imul(t,569420461),t^=t>>>15,t=Math.imul(t,1935289751),((t^=t>>>15)>>>0)/4294967296}function Jt(t){let e=[];return t._dn?e.push(t._dn):t.children&&t.children.map((t=>{e=e.concat(Jt(t))})),e}class Qt{constructor({id:t,name:e=t,objects:s=[],context:n=w(),cullObjects:r=!0,cullFunction:o=i,sortFunction:d,...c}){this._o=[],Object.assign(this,{id:t,name:e,context:n,cullObjects:r,cullFunction:o,sortFunction:d,...c});let l=this._dn=document.createElement("section");l.tabIndex=-1,l.style=h,l.id=t,l.setAttribute("aria-label",e);let u=this;this.camera=new class extends W{set x(t){u.sx=t-this.centerX,super.x=t}get x(){return super.x}set y(t){u.sy=t-this.centerY,super.y=t}get y(){return super.y}}({context:n,anchor:{x:.5,y:.5},render:this._rf.bind(this)}),this.add(s),this._i=()=>{this.context??=w();let t=this.context.canvas,{width:e,height:i}=t,s=e/2,n=i/2;Object.assign(this.camera,{centerX:s,centerY:n,x:s,y:n,width:e,height:i}),l.isConnected||a(l,t)},this.context&&this._i(),p("init",this._i)}set objects(t){this.remove(this._o),this.add(t)}get objects(){return this._o}get node(){return this._dn}add(...t){t.flat().map((t=>{this._o.push(t),t.parent=this,this._dn.append(...Jt(t))}))}remove(...t){t.flat().map((t=>{o(this._o,t),t.parent=null,Jt(t).map((t=>{a(t,this.context.canvas)}))}))}show(){this.hidden=this._dn.hidden=!1;let t=this._o.find((t=>t.focus));t?t.focus(r):this._dn.focus(r),this.onShow()}hide(){this.hidden=this._dn.hidden=!0,this.onHide()}destroy(){_("init",this._i),this._dn.remove(),this._o.map((t=>t.destroy&&t.destroy()))}lookAt(t){let{x:e,y:i}=t.world||t;this.camera.x=e,this.camera.y=i}update(t){this.hidden||this._o.map((e=>e.update&&e.update(t)))}_rf(){let{_o:t,context:e,_sx:i,_sy:s,camera:n,sortFunction:h,cullObjects:r,cullFunction:a}=this;e.translate(i,s);let o=t;r&&(o=o.filter((t=>a(n,t)))),h&&o.sort(h),o.map((t=>t.render&&t.render()))}render(){if(!this.hidden){let{context:t,camera:e}=this,{x:i,y:s,centerX:n,centerY:h}=e;t.save(),this._sx=n-i,this._sy=h-s,t.translate(this._sx,this._sy),e.render(),t.restore()}}onShow(){}onHide(){}}function Zt(t){if(+t==t)return t;let e=[],i=t.split(".."),s=+i[0],n=+i[1],h=s;if(s<n)for(;h<=n;h++)e.push(h);else for(;h>=n;h--)e.push(h);return e}class te{constructor({image:t,frameWidth:e,frameHeight:i,spacing:s=0,margin:n=0,animations:h}={}){this.animations={},this.image=t,this.frame={width:e,height:i,spacing:s,margin:n},this._f=(t.width-n)/e|0,this.createAnimations(h)}createAnimations(t){let e,i;for(i in t){let{frames:s,frameRate:n,loop:h}=t[i];e=[],[].concat(s).map((t=>{e=e.concat(Zt(t))})),this.animations[i]=y({spriteSheet:this,frames:e,frameRate:n,loop:h,name:i})}}}let ee=2147483648,ie=1073741824,se=536870912;function ne(t,e){return t/e|0}function he(t,e){return t/e|0}class re{constructor(t={}){let{width:e,height:i,tilewidth:s,tileheight:n,tilesets:h}=t,r=e*s,a=i*n,o=document.createElement("canvas");o.width=r,o.height=a,this._c=o,this._ctx=o.getContext("2d"),h.map((e=>{let{__k:i,location:s}=window,n=(i?i.dm.get(t):"")||s.href,{source:h}=e;if(h){let t=i.d[i.u(h,n)];Object.keys(t).map((i=>{e[i]=t[i]}))}let{image:r}=e;if(""+r===r){let t=i.i[i.u(r,n)];e.image=t}})),Object.assign(this,{context:w(),layerMap:{},layerCanvases:{},mapwidth:r,mapheight:a,_sx:0,_sy:0,_o:[],...t}),this.context&&this._p(),p("init",(()=>{this.context??=w(),this._p()}))}get sx(){return this._sx}get sy(){return this._sy}set sx(t){let i=Math.max(0,this.mapwidth-m().width);this._sx=e(0,i,t)}set sy(t){let i=Math.max(0,this.mapheight-m().height);this._sy=e(0,i,t)}set objects(t){this.remove(this._o),this.add(t)}get objects(){return this._o}add(...t){t.flat().map((t=>{this._o.push(t),t.parent=this}))}remove(...t){t.flat().map((t=>{o(this._o,t),t.parent=null}))}getPosition(t){let e=m().getBoundingClientRect(),i=t.x-e.x,s=t.y-e.y;return i+=this.sx,s+=this.sy,{x:i,y:s,row:ne(s,this.tileheight),col:he(i,this.tilewidth)}}setTileAtLayer(t,e,i){let{layerMap:s,tileheight:n,tilewidth:h,width:r}=this,{row:a,col:o,x:d,y:c}=e,l=a??ne(c,n),u=o??he(d,h);s[t]&&(this._d=!0,s[t]._d=!0,s[t].data[l*r+u]=i)}setLayer(t,e){let{layerMap:i}=this;i[t]&&(this._d=!0,i[t]._d=!0,i[t].data=e)}layerCollidesWith(t,e){let{tilewidth:i,tileheight:n,layerMap:h}=this,{x:r,y:a,width:o,height:d}=s(e),c=ne(a,n),l=he(r,i),u=ne(a+d,n),p=he(r+o,i),_=h[t];for(let t=c;t<=u;t++)for(let e=l;e<=p;e++)if(_.data[e+t*this.width])return!0;return!1}tileAtLayer(t,e){let{layerMap:i,tileheight:s,tilewidth:n,width:h}=this,{row:r,col:a,x:o,y:d}=e,c=r??ne(d,s),l=a??he(o,n);return i[t]?i[t].data[c*h+l]:-1}render(t=this._c,e=!0){let{_d:i,context:s,sx:n=0,sy:h=0}=this;i&&this._p();let{width:r,height:a}=m(),o=Math.min(t.width,r),d=Math.min(t.height,a);s.drawImage(t,n,h,o,d,0,0,o,d),e&&(s.save(),(n||h)&&s.translate(-n,-h),this.objects.map((t=>t.render&&t.render())),s.restore())}renderLayer(t){let{layerCanvases:e,layerMap:i}=this,s=i[t],n=e[t],h=n?.getContext("2d");if(!n){let{mapwidth:i,mapheight:r}=this;n=document.createElement("canvas"),h=n.getContext("2d"),n.width=i,n.height=r,e[t]=n,this._rl(s,h)}s._d&&(s._d=!1,h.clearRect(0,0,n.width,n.height),this._rl(s,h)),this.render(n,!1)}_p(){let{_ctx:t,layers:e=[],layerMap:i}=this;this._d=!1,e.map((e=>{let{name:s,data:n,visible:h}=e;e._d=!1,i[s]=e,n&&0!=h&&this._rl(e,t)}))}_rl(t,e){let{opacity:i,data:s=[]}=t,{tilesets:n,width:h,tilewidth:r,tileheight:a}=this;e.save(),e.globalAlpha=i,s.map(((t,i)=>{if(!t)return;let s,o=0,d=0,c=t&ee,l=t&ie,u=0,p=0,_=0,f=0,g=0;o=c||l,g=(t&=1073741823)&se,g&&(c&&l?_=1:c?u=1:l?p=1:f=1,d=u||p||_||f,t&=-536870913);for(let e=n.length-1;e>=0&&(s=n[e],!(t/s.firstgid>=1));e--);let{image:m,spacing:w=0,margin:x=0,firstgid:y,columns:b}=s,v=t-y,S=b??m.width/(r+w)|0,C=i%h*r,A=(i/h|0)*a,k=x+v%S*(r+w),j=x+(v/S|0)*(a+w);d?(e.save(),e.translate(C+r/2,A+a/2),p||f?e.rotate(-Math.PI/2):(u||_)&&e.rotate(Math.PI/2),(_||f)&&e.scale(-1,1),C=-r/2,A=-a/2):o&&(e.save(),e.translate(C+(c?r:0),A+(l?a:0)),e.scale(c?-1:1,l?-1:1),C=o?0:C,A=o?0:A),e.drawImage(m,k,j,r,a,C,A,r,a),(o||d)&&e.restore()})),e.restore()}}let ae={Animation:y,AnimationClass:x,imageAssets:I,audioAssets:D,dataAssets:G,setImagePath:function(t){k=t},setAudioPath:function(t){j=t},setDataPath:function(t){M=t},loadImage:X,loadAudio:Y,loadData:T,load:function(...t){return N(),Promise.all(t.map((t=>{let e=O([].concat(t)[0]);return e.match(b)?X(t):e.match(v)?Y(t):T(t)})))},Button:function(){return new dt(...arguments)},ButtonClass:dt,init:function(t,{contextless:e=!1}={}){return c=document.getElementById(t)||t||document.querySelector("canvas"),e&&(c=c||new Proxy({},g)),l=c.getContext("2d")||new Proxy({},g),l.imageSmoothingEnabled=!1,f("init"),{canvas:c,context:l}},getCanvas:m,getContext:w,on:p,off:_,emit:f,GameLoop:function({fps:t=60,clearCanvas:e=!0,update:i=n,render:s,context:h=w(),blur:r=!1}={}){let a,o,d,c,l,u=0,_=1e3/t,g=1/t,m=e?ct:n,x=!0;function y(){if(o=requestAnimationFrame(y),x&&(d=performance.now(),c=d-a,a=d,!(c>1e3))){for(u+=c;u>=_;)f("tick"),l.update(g),u-=_;m(l.context),l.render()}}return r||(window.addEventListener("focus",(()=>{x=!0})),window.addEventListener("blur",(()=>{x=!1}))),p("init",(()=>{l.context??=w()})),l={update:i,render:s,isStopped:!0,context:h,start(){this.isStopped&&(a=performance.now(),this.isStopped=!1,requestAnimationFrame(y))},stop(){this.isStopped=!0,cancelAnimationFrame(o)}},l},GameObject:function(){return new W(...arguments)},GameObjectClass:W,gamepadMap:_t,updateGamepad:wt,initGamepad:xt,onGamepad:yt,offGamepad:bt,gamepadPressed:function(t,{gamepad:e}={}){return isNaN(e)?lt.some((e=>e.pressedButtons[t])):!!lt[e]&&!!lt[e].pressedButtons[t]},gamepadAxis:function(t,e){return lt[e]?.axes[t]||0},gestureMap:At,initGesture:kt,onGesture:jt,offGesture:Mt,Grid:function(){return new Ot(...arguments)},GridClass:Ot,degToRad:function(t){return t*Math.PI/180},radToDeg:function(t){return 180*t/Math.PI},angleToTarget:function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},rotatePoint:t,movePoint:function(t,e,i){return{x:t.x+Math.cos(e)*i,y:t.y+Math.sin(e)*i}},lerp:function(t,e,i){return t*(1-i)+e*i},inverseLerp:function(t,e,i){return(i-t)/(e-t)},clamp:e,setStoreItem:function(t,e){null==e?localStorage.removeItem(t):localStorage.setItem(t,JSON.stringify(e))},getStoreItem:function(t){let e=localStorage.getItem(t);try{e=JSON.parse(e)}catch(t){}return e},collides:i,getWorldRect:s,depthSort:function(t,e,i="y"){return[t,e]=[t,e].map(s),t[i]-e[i]},initInput:function(t={}){Rt();let e=ht(t.pointer);return kt(),xt(),{pointer:e}},onInput:function(t,e,{gamepad:i,key:s}={}){[].concat(t).map((t=>{Bt(t,_t)?yt(t,e,i):Ht(t)?jt(t,e):Bt(t,Nt)?Wt(t,e,s):["down","up"].includes(t)&&at(t,e)}))},offInput:function(t,{gamepad:e,key:i}={}){[].concat(t).map((t=>{Bt(t,_t)?bt(t,e):Ht(t)?Mt(t):Bt(t,Nt)?Ft(t,i):["down","up"].includes(t)&&ot(t)}))},keyMap:Nt,initKeys:Rt,onKey:Wt,offKey:Ft,keyPressed:function(t){return!![].concat(t).some((t=>Gt[t]))},registerPlugin:function(t,e){let i=t.prototype;i&&(i._inc||(i._inc={},i._bInc=function(t,e,...i){return this._inc[e].before.reduce(((e,i)=>{let s=i(t,...e);return s||e}),i)},i._aInc=function(t,e,i,...s){return this._inc[e].after.reduce(((e,i)=>{let n=i(t,e,...s);return n||e}),i)}),Object.getOwnPropertyNames(e).map((t=>{let s=Ut(t);i[s]&&(i["_o"+s]||(i["_o"+s]=i[s],i[s]=function(...t){let e=this._bInc(this,s,...t),n=i["_o"+s].call(this,...e);return this._aInc(this,s,n,...t)}),i._inc[s]||(i._inc[s]={before:[],after:[]}),t.startsWith("before")?i._inc[s].before.push(e[t]):t.startsWith("after")&&i._inc[s].after.push(e[t]))})))},unregisterPlugin:function(t,e){let i=t.prototype;i&&i._inc&&Object.getOwnPropertyNames(e).map((t=>{let s=Ut(t);t.startsWith("before")?o(i._inc[s].before,e[t]):t.startsWith("after")&&o(i._inc[s].after,e[t])}))},extendObject:function(t,e){let i=t.prototype;i&&Object.getOwnPropertyNames(e).map((t=>{i[t]||(i[t]=e[t])}))},initPointer:ht,getPointer:function(t=m()){return q.get(t)},track:rt,untrack:function(...t){t.flat().map((t=>{let e=t.context?t.context.canvas:m(),i=q.get(e);t.render=t.__r,t.__r=0,o(i._o,t)}))},pointerOver:function(t){let e=t.context?t.context.canvas:m(),i=q.get(e);return i._o.includes(t)&&J(i)===t},onPointer:at,offPointer:ot,pointerPressed:function(t){return!!V[t]},Pool:function(){return new qt(...arguments)},PoolClass:qt,Quadtree:function(){return new Vt(...arguments)},QuadtreeClass:Vt,rand:$t,randInt:function(t,e,i=$t){return(i()*(e-t+1)|0)+t},getSeed:function(){return Lt},seedRand:function(t=Date.now()){if(Lt=t,"string"==typeof t){for(var e=0,i=1779033703^t.length;e<t.length;e++)i=(i=Math.imul(i^t.charCodeAt(e),3432918353))<<13|i>>>19;i=Math.imul(i^i>>>16,2246822507),i=Math.imul(i^i>>>13,3266489909),Lt=(i^=i>>>16)>>>0}},Scene:function(){return new Qt(...arguments)},SceneClass:Qt,Sprite:function(){return new F(...arguments)},SpriteClass:F,SpriteSheet:function(){return new te(...arguments)},SpriteSheetClass:te,Text:U,TextClass:H,TileEngine:function(){return new re(...arguments)},TileEngineClass:re,Vector:R,VectorClass:z};return ae}();