frontend.js 18 KB

1
  1. window.mainDisplay=(()=>{"use strict";var e={86:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.BackendClient=t.RequestMetod=void 0,function(e){e.Post="post",e.Get="get"}(i=t.RequestMetod||(t.RequestMetod={})),t.BackendClient=class{constructor(e=window.location.host,t="main"){this.host=e,this.partition=t,this.apiEndpoint=`https://${e}/db/ecal`}req(e,t,s=i.Post){const a=new XMLHttpRequest;if(s===i.Post)a.open(s,`${this.apiEndpoint}${e}`,!0);else{const i=Object.keys(t).map((e=>{const i=t[e];return`${e}=${encodeURIComponent(i)}`})).join("&"),r=`${this.apiEndpoint}${e}?${i}`;a.open(s,r,!0)}return a.setRequestHeader("content-type","application/json"),new Promise((function(e,r){a.onload=function(){try{if(200===a.status)e(JSON.parse(a.response));else{let e;try{e=JSON.parse(a.responseText).errors}catch(t){e=a.responseText.trim()}r(e)}}catch(e){r(e)}},s===i.Post?a.send(JSON.stringify(t)):a.send()}))}}},382:(e,t)=>{var i;Object.defineProperty(t,"__esModule",{value:!0}),t.EliasDBGraphQLClient=t.RequestMetod=void 0,function(e){e.Post="post",e.Get="get"}(i=t.RequestMetod||(t.RequestMetod={})),t.EliasDBGraphQLClient=class{constructor(e=window.location.host,t="main"){this.delayedOperations=[],this.subscriptionQueue=[],this.subscriptionCallbacks={},this.host=e,this.partition=t,this.graphQLEndpoint=`https://${e}/db/v1/graphql/${t}`,this.graphQLReadOnlyEndpoint=`https://${e}/db/v1/graphql-query/${t}`}initWebsocket(){const e=`wss://${this.host}/db/v1/graphql-subscriptions/${this.partition}`;this.ws=new WebSocket(e),this.ws.onmessage=this.message.bind(this),this.ws.onopen=()=>{this.ws&&this.ws.send(JSON.stringify({type:"init",payload:{}}))}}req(e,t={},s="",a=i.Post){const r=new XMLHttpRequest,n={operationName:s,variables:t,query:e};if(a===i.Post)r.open(a,this.graphQLEndpoint,!0);else{const e=Object.keys(n).map((e=>{const t="variables"!==e?n[e]:JSON.stringify(n[e]);return`${e}=${encodeURIComponent(t)}`})).join("&"),t=`${this.graphQLReadOnlyEndpoint}?${e}`;r.open(a,t,!0)}return r.setRequestHeader("content-type","application/json"),new Promise((function(e,t){r.onload=function(){try{if(200===r.status)e(JSON.parse(r.response));else{let e;try{e=JSON.parse(r.responseText).errors}catch(t){e=r.responseText.trim()}t(e)}}catch(e){t(e)}},a===i.Post?r.send(JSON.stringify(n)):r.send()}))}subscribe(e,t,i=null){if(this.ws||this.initWebsocket(),this.ws){const s=this,a=function(){s.ws&&(s.ws.send(JSON.stringify({id:s.subscriptionQueue.length,query:e,type:"subscription_start",variables:i})),s.subscriptionQueue.push(t))};this.ws.readyState!==WebSocket.OPEN?this.delayedOperations.push(a):a()}}message(e){const t=JSON.parse(e.data);if("init_success"==t.type)this.delayedOperations.forEach((e=>e())),this.delayedOperations=[];else if("subscription_success"==t.type){const e=this.subscriptionQueue.shift();if(e){const i=t.id;this.subscriptionCallbacks[i]=e}}else if("subscription_data"==t.type){const e=this.subscriptionCallbacks[t.id];e&&e(t.payload)}else"subscription_fail"==t.type&&console.error("Subscription failed: ",t.payload.errors.join("; "))}}},386:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DefaultPlayerState=t.DefaultSpriteState=t.DefaultEngineOptions=t.DefaultEngineEventHandler=void 0,t.DefaultEngineEventHandler=class{onkeydown(e,t){switch((t=t||window.event).code){case"ArrowUp":e.speed+=.006,e.stateUpdate(["speed"]);break;case"ArrowDown":e.speed+=-.008,e.stateUpdate(["speed"]);break;case"ArrowRight":t.ctrlKey||t.shiftKey?(e.strafe=1,e.stateUpdate(["strafe"])):(e.dir=1,e.rotSpeed<e.maxRotSpeed?(e.rotSpeed=e.deltaRotSpeed(e.rotSpeed),e.stateUpdate(["dir","rotSpeed"])):e.stateUpdate(["dir"]));break;case"ArrowLeft":t.ctrlKey||t.shiftKey?(e.strafe=-1,e.stateUpdate(["strafe"])):(e.dir=-1,e.rotSpeed<e.maxRotSpeed?(e.rotSpeed=e.deltaRotSpeed(e.rotSpeed),e.stateUpdate(["dir","rotSpeed"])):e.stateUpdate(["dir"]))}this.stopBubbleEvent(t)}onkeyup(e,t){"ArrowRight"!=(t=t||window.event).code&&"ArrowLeft"!=t.code||(e.dir=0,e.strafe=0,e.rotSpeed=e.minRotSpeed,e.stateUpdate(["dir","strafe","rotSpeed"])),this.stopBubbleEvent(t)}stopBubbleEvent(e){(e=e||window.event).stopPropagation&&e.stopPropagation(),null!==e.cancelBubble&&(e.cancelBubble=!0)}},t.DefaultEngineOptions=class{constructor(){this.backdrop=null,this.screenWidth=640,this.screenHeight=480,this.screenElementWidth=640,this.screenElementHeight=480}};class i{constructor(){this.id="",this.x=20,this.y=20,this.dim=20,this.isMoving=!0,this.displayLoop=!0,this.dir=0,this.rot=0,this.rotSpeed=9e-5,this.speed=0,this.strafe=0,this.moveSpeed=0}setState(e){this.id=e.id||this.id,this.x=e.x||this.x,this.y=e.y||this.y,this.dim=e.dim||this.dim,this.isMoving=e.isMoving||this.isMoving,this.displayLoop=e.displayLoop||this.displayLoop,this.dir=e.dir||this.dir,this.rot=e.rot||this.rot,this.rotSpeed=e.rotSpeed||this.rotSpeed,this.speed=e.speed||this.speed,this.strafe=e.strafe||this.strafe,this.moveSpeed=e.moveSpeed||this.moveSpeed}}t.DefaultSpriteState=i,t.DefaultPlayerState=class extends i{constructor(){super(...arguments),this.maxRotSpeed=9e-4,this.minRotSpeed=1e-4}stateUpdate(e){console.log("Player state update:",e)}deltaRotSpeed(e){return 1.000001*e}}},216:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MainDisplayController=void 0,t.MainDisplayController=class{constructor(e,t){this.running=!1,this.debugOutputElement=null,this.player={},this.sprites=[],this.animationFrame=0,this.lastRenderCycleTime=0,this.options=t;const i=document.getElementById(e);if(null===i)throw Error("Canvas element not found");this.canvas=i;const s=i.getContext("2d");if(null===s)throw Error("Could not get canvas rendering context");this.ctx=s,this.debugOutputElement=document.getElementById("game-debug-out"),this.canvas.width=this.options.screenWidth,this.canvas.height=this.options.screenHeight,this.canvas.style.width=this.options.screenElementWidth+"px",this.canvas.style.height=this.options.screenElementHeight+"px"}registerEventHandlers(){document.onkeydown=e=>{this.options.eventHandler.onkeydown(this.player,e)},document.onkeyup=e=>{this.options.eventHandler.onkeyup(this.player,e)}}deRegisterEventHandlers(){document.onkeydown=null,document.onkeyup=null}start(e){this.running=!0,this.player=e,this.registerEventHandlers(),this.drawLoop()}stop(){this.running=!1,this.deRegisterEventHandlers(),this.options.stopHandler()}addSprite(e){this.sprites.push(e)}removeSprite(e){this.sprites.splice(this.sprites.indexOf(e),1)}printDebug(e){null!==this.debugOutputElement&&(this.debugOutputElement.innerHTML+=e+"<br>")}drawLoop(){this.animationFrame++,this.animationFrame=this.animationFrame%1e3,null===this.options.backdrop?this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height):this.ctx.drawImage(this.options.backdrop,0,0,this.canvas.width,this.canvas.height),null!==this.debugOutputElement&&(this.debugOutputElement.innerHTML="");let e=(new Date).getTime();if(this.drawSprites(),this.drawPlayer(),this.options.drawHandler(this.ctx,this.player,this.sprites),0!==e){let e=(new Date).getTime();const t=e-this.lastRenderCycleTime,i=Math.floor(1e3/t);this.lastRenderCycleTime=e,this.printDebug("FPS: "+i)}this.running&&setTimeout((()=>{this.drawLoop()}),20)}drawPlayer(){try{return void this.player.draw(this.ctx,this.player)}catch(e){}this.ctx.beginPath(),this.ctx.arc(this.player.x,this.player.y,this.player.dim/2,0,2*Math.PI),this.ctx.moveTo(this.player.x,this.player.y),this.ctx.lineTo(this.player.x+20*Math.cos(this.player.rot),this.player.y+20*Math.sin(this.player.rot)),this.ctx.closePath(),this.ctx.stroke();let e=this.ctx.strokeStyle,t=this.player.dim/2;this.ctx.strokeStyle="red",this.ctx.rect(this.player.x-t,this.player.y-t,this.player.dim,this.player.dim),this.ctx.stroke(),this.ctx.strokeStyle=e}drawSprites(){for(let e of this.sprites){try{return void e.draw(this.ctx,e)}catch(e){}this.ctx.beginPath(),this.ctx.arc(e.x,e.y,e.dim/2,0,2*Math.PI),this.ctx.moveTo(e.x,e.y),this.ctx.lineTo(e.x+20*Math.cos(e.rot),e.y+20*Math.sin(e.rot)),this.ctx.closePath(),this.ctx.stroke();let t=this.ctx.strokeStyle,i=e.dim/2;this.ctx.strokeStyle="red",this.ctx.rect(e.x-i,e.y-i,e.dim,e.dim),this.ctx.stroke(),this.ctx.strokeStyle=t}}}},263:function(e,t,i){var s=this&&this.__awaiter||function(e,t,i,s){return new(i||(i=Promise))((function(a,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function o(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,o)}l((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0});const a=i(47),r=i(216),n=i(86),o=i(382),l=i(983),d=i(949);t.default={start:function(e){return s(this,void 0,void 0,(function*(){const t=`${window.location.hostname}:${window.location.port}`,i="main",s=new n.BackendClient(t,i),h=new a.GameOptions;try{const e=(yield s.req("/game",{gameName:i},n.RequestMetod.Get)).gameworld;h.backdrop=null,h.screenWidth=e.screenWidth,h.screenHeight=e.screenHeight,h.screenElementWidth=e.screenElementWidth,h.screenElementHeight=e.screenElementHeight}catch(e){throw new Error(`Could not register: ${e}`)}const p=new o.EliasDBGraphQLClient(t,i),c=new r.MainDisplayController(e,h);let u=d.getURLParams();u.player||(d.setURLParam("player",d.generateRandomName()),u=d.getURLParams());const y=u.player;try{yield s.req("/player",{player:y,gameName:i});const e=new l.MainGameController(i,y,c,s,p);yield e.start()}catch(e){throw new Error(`Could not register: ${e}`)}}))}}},983:function(e,t,i){var s=this&&this.__awaiter||function(e,t,i,s){return new(i||(i=Promise))((function(a,r){function n(e){try{l(s.next(e))}catch(e){r(e)}}function o(e){try{l(s.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):(t=e.value,t instanceof i?t:new i((function(e){e(t)}))).then(n,o)}l((s=s.apply(e,t||[])).next())}))};Object.defineProperty(t,"__esModule",{value:!0}),t.MainGameController=void 0;const a=i(47);t.MainGameController=class{constructor(e,t,i,s,r){this.gameName=e,this.display=i,this.backedClient=s,this.graphqlClient=r,this.playerState=new a.Player(e,s),this.playerState.id=t,this.spriteMap={}}start(){return s(this,void 0,void 0,(function*(){const e=()=>s(this,void 0,void 0,(function*(){const t=(yield this.graphqlClient.req("{ obj { id, x, y, dim, isMoving, displayLoop, dir, rot, rotSpeed, speed, strafe, moveSpeed } }")).data.obj;for(const e of t)if(e.id!==this.playerState.id){let t=this.spriteMap[e.id];t||(t=new a.Sprite,t.setState(e),this.spriteMap[t.id]=t,this.display.addSprite(t))}else this.playerState.setState(e);window.setTimeout(e,500)}));e(),this.registerObjectSubscription()}))}registerObjectSubscription(){this.graphqlClient.subscribe("\nsubscription {\n obj() {\n id,\n x,\n y,\n dim,\n rot\n }\n}",(e=>{const t=e.data.obj;for(const e of t)if(e.id===this.playerState.id)this.playerState.x=e.x,this.playerState.y=e.y,this.playerState.dim=e.dim,this.playerState.rot=e.rot;else{let t=this.spriteMap[e.id];t&&(t.x=e.x,t.y=e.y,t.dim=e.dim,t.rot=e.rot)}this.display.running||this.display.start(this.playerState)}))}}},47:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Sprite=t.Player=t.GameOptions=t.GameEventHandler=void 0;const s=i(386);class a extends s.DefaultEngineEventHandler{}t.GameEventHandler=a;class r extends s.DefaultEngineOptions{constructor(){super(),this.eventHandler=new a}drawHandler(){}stopHandler(){}}t.GameOptions=r;class n extends s.DefaultPlayerState{constructor(e,t){super(),this.gameName=e,this.backedClient=t}stateUpdate(){this.backedClient.req("/input",{player:this.id,gameName:this.gameName,state:{dir:this.dir,rotSpeed:this.rotSpeed,speed:this.speed,strafe:this.strafe}}).catch((e=>{throw e}))}draw(e,t){throw new Error(`Method not implemented. ${e}, ${t}`)}}t.Player=n;class o extends s.DefaultSpriteState{draw(e,t){throw new Error(`Method not implemented. ${e}, ${t}`)}}t.Sprite=o},949:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.generateRandomName=t.removeURLParam=t.setURLParam=t.getURLParams=void 0,t.getURLParams=function(){const e=/[?&]?([^=]+)=([^&]*)/g,t=document.location.search.split("+").join(" ");let i,s={};for(;i=e.exec(t);)s[decodeURIComponent(i[1])]=decodeURIComponent(i[2]);return s},t.setURLParam=function(e,t){let i=window.location.href;if(i.indexOf(e+"=")>=0){var s=i.substring(0,i.indexOf(e)),a=i.substring(i.indexOf(e));i=s+e+"="+t+(a=(a=a.substring(a.indexOf("=")+1)).indexOf("&")>=0?a.substring(a.indexOf("&")):"")}else i.indexOf("?")<0?i+="?"+e+"="+t:i+="&"+e+"="+t;window.history.pushState(null,document.title,i)},t.removeURLParam=function(e){let t=window.location.href,i=t.split("?");if(i.length>=2){for(var s=e+"=",a=i[1].split(/[&;]/g),r=a.length-1;r>=0;r--)-1!==a[r].lastIndexOf(s,0)&&a.splice(r,1);t=i[0]+(a.length>0?"?"+a.join("&"):""),window.history.pushState(null,document.title,t)}};const i=["adorable","adventurous","aggressive","agreeable","alert","alive","amused","angry","annoyed","annoying","anxious","arrogant","ashamed","attractive","average","awful","bad","beautiful","better","bewildered","black","bloody","blue","blue-eyed","blushing","bored","brainy","brave","breakable","bright","busy","calm","careful","cautious","charming","cheerful","clean","clear","clever","cloudy","clumsy","colorful","combative","comfortable","concerned","condemned","confused","cooperative","courageous","crazy","creepy","crowded","cruel","curious","cute","dangerous","dark","dead","defeated","defiant","delightful","depressed","determined","different","difficult","disgusted","distinct","disturbed","dizzy","doubtful","drab","dull","eager","easy","elated","elegant","embarrassed","enchanting","encouraging","energetic","enthusiastic","envious","evil","excited","expensive","exuberant","fair","faithful","famous","fancy","fantastic","fierce","filthy","fine","foolish","fragile","frail","frantic","friendly","frightened","funny","gentle","gifted","glamorous","gleaming","glorious","good","gorgeous","graceful","grieving","grotesque","grumpy","handsome","happy","healthy","helpful","helpless","hilarious","homeless","homely","horrible","hungry","hurt","ill","important","impossible","inexpensive","innocent","inquisitive","itchy","jealous","jittery","jolly","joyous","kind","lazy","light","lively","lonely","long","lovely","lucky","magnificent","misty","modern","motionless","muddy","mushy","mysterious","nasty","naughty","nervous","nice","nutty","obedient","obnoxious","odd","old-fashioned","open","outrageous","outstanding","panicky","perfect","plain","pleasant","poised","poor","powerful","precious","prickly","proud","putrid","puzzled","quaint","real","relieved","repulsive","rich","scary","selfish","shiny","shy","silly","sleepy","smiling","smoggy","sore","sparkling","splendid","spotless","stormy","strange","stupid","successful","super","talented","tame","tasty","tender","tense","terrible","thankful","thoughtful","thoughtless","tired","tough","troubled","ugliest","ugly","uninterested","unsightly","unusual","upset","uptight","vast","victorious","vivacious","wandering","weary","wicked","wide-eyed","wild","witty","worried","worrisome","wrong","zany","zealous"],s=["Aardvark","Albatross","Alligator","Alpaca","Anole","Ant","Anteater","Antelope","Ape","Armadillo","Baboon","Badger","Barracuda","Bat","Bear","Beaver","Bee","Binturong","Bird","Bison","Bluebird","Boar","Bobcat","Budgerigar","Buffalo","Butterfly","Camel","Capybara","Caracal","Caribou","Cassowary","Cat","Caterpillar","Cattle","Chamois","Cheetah","Chicken","Chimpanzee","Chinchilla","Chough","Coati","Cobra","Cockroach","Cod","Cormorant","Cougar","Coyote","Crab","Crane","Cricket","Crocodile","Crow","Cuckoo","Curlew","Deer","Dhole","Dingo","Dinosaur","Dog","Dogfish","Dolphin","Donkey","Dove","Dragonfly","Duck","Dugong","Dunlin","Eagle","Echidna","Eel","Eland","Elephant","Elk","Emu","Falcon","Ferret","Finch","Fish","Fisher","Flamingo","Fly","Flycatcher","Fox","Frog","Gaur","Gazelle","Gecko","Genet","Gerbil","Giant","Giraffe","Gnat","Gnu","Goat","Goldfinch","Goosander","Goose","Gorilla","Goshawk","Grasshopper","Grouse","Guanaco","Guinea","Guinea","Gull","Hamster","Hare","Hawk","Hedgehog","Hermit","Heron","Herring","Hippopotamus","Hoatzin","Hoopoe","Hornet","Horse","Human","Hummingbird","Hyena","Ibex","Ibis","Iguana","Impala","Jackal","Jaguar","Jay","Jellyfish","Jerboa","Kangaroo","Kingbird","Kingfisher","Kinkajou","Kite","Koala","Kodkod","Komodo","Kookaburra","Kouprey","Kudu","Langur","Lapwing","Lark","Lechwe","Lemur","Leopard","Lion","Lizard","Llama","Lobster","Locust","Loris","Louse","Lynx","Lyrebird","Macaque","Macaw","Magpie","Mallard","Mammoth","Manatee","Mandrill","Margay","Marmoset","Marmot","Meerkat","Mink","Mole","Mongoose","Monkey","Moose","Mosquito","Mouse","Myna","Narwhal","Newt","Nightingale","Nilgai","Ocelot","Octopus","Okapi","Oncilla","Opossum","Orangutan","Oryx","Ostrich","Otter","Ox","Owl","Oyster","Panther","Parrot","Panda","Partridge","Peafowl","Penguin","Pheasant","Pig","Pigeon","Pika","Polar bear","Pony","Porcupine","Porpoise","Prairie","Pug","Quail","Quelea","Quetzal","Rabbit","Raccoon","Ram","Rat","Raven","Red deer","Red panda","Reindeer","Rhea","Rhinoceros","Rook","Saki","Salamander","Salmon","Sand dollar","Sandpiper","Sardine","Sassaby","Sea lion","Seahorse","Seal","Serval","Shark","Sheep","Shrew","Shrike","Siamang","Skink","Skipper","Skunk","Sloth","Snail","Snake  ","Spider  ","Spoonbill","Squid","Squirrel","Starling","Stilt","Swan","Tamarin","Tapir","Tarsier","Termite","Thrush","Tiger","Toad","Topi","Toucan","Turaco","Turkey","Turtle","Vicuña","Vinegaroon","Viper","Vulture","Wallaby","Walrus","Wasp","Water buffalo","Waxwing","Weasel","Whale","Wobbegong","Wolf","Wolverine","Wombat","Woodpecker","Worm","Wren","Yak","Zebra"];t.generateRandomName=function(){let e=i[Math.floor(Math.random()*i.length)],t=s[Math.floor(Math.random()*s.length)];return e=e.charAt(0).toUpperCase()+e.slice(1),`${e}${t}`}}},t={};return function i(s){if(t[s])return t[s].exports;var a=t[s]={exports:{}};return e[s].call(a.exports,a,a.exports,i),a.exports}(263)})().default;