Advertisement
_Cynder_

HiveScript

Apr 7th, 2020
1,102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function l(what) {return document.getElementById(what);}
  2. function choose(arr) {return arr[Math.floor(Math.random()*arr.length)];}
  3. function randomFloor(x) {if ((x%1)<Math.random()) return Math.floor(x); else return Math.ceil(x);}
  4. String.prototype.replaceAll=function(search,replacement)
  5. //{var target=this;return target.replace(new RegExp(search,'g'),replacement);};
  6. {return this.split(search).join(replacement);};
  7. function AddEvent(html_element,event_name,event_function)
  8. {
  9.     if(html_element.attachEvent) html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
  10.     else if(html_element.addEventListener) html_element.addEventListener(event_name, event_function, false);
  11. }
  12.  
  13. function LoadScript(url,callback,onerror)
  14. {
  15.     var script=document.createElement('script');
  16.     script.setAttribute('src',url);
  17.     if (callback) script.onload=callback;
  18.     if (onerror) script.onerror=onerror;
  19.     document.head.appendChild(script);
  20.     return script;
  21. }
  22.  
  23. function ajax(url,callback)
  24. {
  25.     var ajaxRequest;
  26.     try{ajaxRequest=new XMLHttpRequest();} catch (e){try{ajaxRequest=new ActiveXObject('Msxml2.XMLHTTP');} catch (e) {try{ajaxRequest=new ActiveXObject('Microsoft.XMLHTTP');} catch (e){alert("Something broke!");return false;}}}
  27.     if (callback){ajaxRequest.onreadystatechange=function(){if(ajaxRequest.readyState==4){callback(ajaxRequest.responseText);}}}
  28.     ajaxRequest.open('GET',url+'&nocache='+(new Date().getTime()),true);ajaxRequest.send(null);
  29. }
  30.  
  31. var INFRAME=INFRAME||false;
  32. var EDITOR=EDITOR||false;
  33.  
  34. G={};
  35.  
  36. G.Launch=function()
  37. {
  38.  
  39.     G.Init=function(){};
  40.     G._Init=function()
  41.     {
  42.         G.T=0;
  43.         G.drawT=0;
  44.         G.fps=30;
  45.        
  46.         G.l=l('game');
  47.         G.wrapl=l('wrap');
  48.        
  49.         G.local=true;
  50.         if (window.location.protocol=='http:' || window.location.protocol=='https:') G.local=false;
  51.         G.isIE=false;
  52.         if (document.documentMode || /Edge/.test(navigator.userAgent)) G.isIE=true;
  53.        
  54.         if (!G.local && !INFRAME)
  55.         {
  56.             window.cookieconsent_options={"message":"This website uses cookies for ads and traffic analysis.","dismiss":"Got it!","learnMore":"Learn more","link":"http://orteil.dashnet.org/cookieconsentpolicy.html","target":"_blank","theme":"http://orteil.dashnet.org/cookieconsent.css","domain":"dashnet.org"};
  57.             LoadScript("//cdnjs.cloudflare.com/ajax/libs/cookieconsent2/1.0.9/cookieconsent.min.js");
  58.         }
  59.        
  60.         G.w=window.innerWidth;
  61.         G.h=window.innerHeight;
  62.         G.resizing=false;
  63.         if (!G.stabilizeResize) G.stabilizeResize=function(){}
  64.         G._stabilizeResize=function()
  65.         {
  66.             G.resizing=false;
  67.             G.stabilizeResize();
  68.         }
  69.         G.resize=function()
  70.         {
  71.             G.resizing=true;
  72.         }
  73.         window.addEventListener('resize',function(event)
  74.         {
  75.             G.w=window.innerWidth;
  76.             G.h=window.innerHeight;
  77.             G.resize();
  78.         });
  79.    
  80.         G.mouseDown=false;//mouse button just got pressed
  81.         G.mouseUp=false;//mouse button just got released
  82.         G.mousePressed=false;//mouse button is currently down
  83.         G.clickL=0;//what element got clicked
  84.         AddEvent(document,'mousedown',function(event){G.mouseDown=true;G.mousePressed=true;G.mouseDragFrom=event.target;G.mouseDragFromX=G.mouseX;G.mouseDragFromY=G.mouseY;});
  85.         AddEvent(document,'mouseup',function(event){G.mouseUp=true;G.mouseDragFrom=0;});
  86.         AddEvent(document,'click',function(event){G.clickL=event.target;});
  87.        
  88.         G.mouseX=0;
  89.         G.mouseY=0;
  90.         G.mouseMoved=0;
  91.         G.draggedFrames=0;//increment every frame when we're moving the mouse and we're clicking
  92.         G.GetMouseCoords=function(e)
  93.         {
  94.             var posx=0;
  95.             var posy=0;
  96.             if (!e) var e=window.event;
  97.             if (e.pageX||e.pageY)
  98.             {
  99.                 posx=e.pageX;
  100.                 posy=e.pageY;
  101.             }
  102.             else if (e.clientX || e.clientY)
  103.             {
  104.                 posx=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
  105.                 posy=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;
  106.             }
  107.             var x=0;
  108.             var y=0;
  109.             G.mouseX=posx-x;
  110.             G.mouseY=posy-y;
  111.             G.mouseMoved=1;
  112.         }
  113.         AddEvent(document,'mousemove',G.GetMouseCoords);
  114.        
  115.         G.Scroll=0;
  116.         G.handleScroll=function(e)
  117.         {
  118.             if (!e) e=event;
  119.             G.Scroll=(e.detail<0||e.wheelDelta>0)?1:-1;
  120.         };
  121.         AddEvent(document,'DOMMouseScroll',G.handleScroll);
  122.         AddEvent(document,'mousewheel',G.handleScroll);
  123.        
  124.         G.keys={};//key is being held down
  125.         G.keysD={};//key was just pressed down
  126.         G.keysU={};//key was just pressed up
  127.         //shift=16, ctrl=17
  128.         AddEvent(window,'keyup',function(e){
  129.             if ((document.activeElement.nodeName=='TEXTAREA' || document.activeElement.nodeName=='INPUT') && e.keyCode!=27) return;
  130.             if (e.keyCode==27) {}//esc
  131.             else if (e.keyCode==13) {}//enter
  132.             G.keys[e.keyCode]=0;
  133.             G.keysD[e.keyCode]=0;
  134.             G.keysU[e.keyCode]=1;
  135.         });
  136.         AddEvent(window,'keydown',function(e){
  137.             if (!G.keys[e.keyCode])//prevent repeats
  138.             {
  139.                 if (e.ctrlKey && e.keyCode==83) {e.preventDefault();}//ctrl-s
  140.                 if ((document.activeElement.nodeName=='TEXTAREA' || document.activeElement.nodeName=='INPUT') && e.keyCode!=27) return;
  141.                 if (e.keyCode==32) {e.preventDefault();}//space
  142.                 G.keys[e.keyCode]=1;
  143.                 G.keysD[e.keyCode]=1;
  144.                 G.keysU[e.keyCode]=0;
  145.                 //console.log('Key pressed : '+e.keyCode);
  146.             }
  147.         });
  148.         AddEvent(window,'blur',function(e){
  149.             G.keys={};
  150.             G.keysD={};
  151.             G.keysU={};
  152.         });
  153.        
  154.         //latency compensator stuff
  155.         G.time=new Date().getTime();
  156.         G.fpsMeasure=new Date().getTime();
  157.         G.accumulatedDelay=0;
  158.         G.catchupLogic=0;
  159.         G.fpsStartTime=0;
  160.         G.frameNumber=0;
  161.         G.getFps=function()
  162.         {
  163.             G.frameNumber++;
  164.             var currentTime=(Date.now()-G.fpsStartTime )/1000;
  165.             var result=Math.ceil((G.frameNumber/currentTime));
  166.             if (currentTime>1)
  167.             {
  168.                 G.fpsStartTime=Date.now();
  169.                 G.frameNumber=0;
  170.             }
  171.             return result;
  172.         }
  173.        
  174.         var div=document.createElement('div');
  175.         div.id='fpsCounter';
  176.         G.wrapl.appendChild(div);
  177.         G.fpsCounter=div;
  178.         var div=document.createElement('canvas');
  179.         div.id='fpsGraph';
  180.         div.width=128;
  181.         div.height=64;
  182.         G.wrapl.appendChild(div);
  183.         G.fpsGraph=div;
  184.         G.fpsGraphCtx=G.fpsGraph.getContext('2d');
  185.         var ctx=G.fpsGraphCtx;
  186.         ctx.fillStyle='#000';
  187.         ctx.fillRect(0,0,128,64);
  188.         G.currentFps=0;
  189.         G.previousFps=0;
  190.        
  191.         G.resize();
  192.        
  193.         G.Init();
  194.        
  195.         G.Loop();
  196.     }
  197.    
  198.     //callbacks system : basically we have functions that return HTML but also add a callback to the callbacks array; after the HTML has been added to the DOM we call G.addCallbacks() to apply all the pending callbacks - this lets us centralize HTML and callbacks in one function
  199.     G.Callbacks=[];
  200.     G.callbackDepth=0;
  201.     G.addCallbacks=function()
  202.     {
  203.         if (G.callbackDepth>0) return false;//prevent nesting callbacks
  204.         G.callbackDepth++;
  205.         var len=G.Callbacks.length;
  206.         for (var i=0;i<len;i++)
  207.         {G.Callbacks[i]();}
  208.         G.Callbacks=[];
  209.         G.callbackDepth--;
  210.     }
  211.     G.pushCallback=function(func)
  212.     {
  213.         G.Callbacks.push(func);
  214.     }
  215.    
  216.    
  217.     G.buttonsN=0;
  218.     G.button=function(obj)
  219.     {
  220.         //returns a string for a new button; creates a callback that must be applied after the html has been created, with G.addCallbacks()
  221.         //obj can have text, tooltip (text that shows on hover), onclick (function executed when button is clicked), classes (CSS classes added to the button), id (force button to have that id)
  222.         var id=obj.id||('button-'+G.buttonsN);
  223.         var str='<div '+(obj.style?('style="'+obj.style+'" '):'')+'class="systemButton'+(obj.classes?(' '+obj.classes):'')+'" id="'+id+'">'+(obj.text||'-')+'</div>';
  224.         if (obj.onclick || obj.tooltip)
  225.         {
  226.             G.pushCallback(function(id,obj){return function(){
  227.                 if (l(id))
  228.                 {
  229.                     if (typeof obj.tooltip==='function') G.addTooltip(l(id),{func:obj.tooltip});
  230.                     else G.addTooltip(l(id),{text:obj.tooltip});
  231.                     if (obj.onclick) l(id).onclick=obj.onclick;
  232.                 }
  233.             }}(id,obj));
  234.         }
  235.         G.buttonsN++;
  236.         return str;
  237.     }
  238.    
  239.     G.textN=0;
  240.     G.updateTextTimer=function(id,func,freq)
  241.     {
  242.         var el=l('updatabletextspan-'+id);
  243.         if (el)
  244.         {
  245.             var delay=freq*1000;
  246.             if (freq<0) {freq=-freq;delay=100;}//a trick : the first update always occurs 100ms after being declared
  247.             el.innerHTML=func();
  248.             G.addCallbacks();
  249.             setTimeout(function(id,func){return function(){G.updateTextTimer(id,func,freq);}}(id,func),delay);
  250.         }
  251.     }
  252.     G.selfUpdatingText=function(func,freq)
  253.     {
  254.         if (!freq) freq=1;
  255.         //returns a string for a span of text that updates itself every second; creates a callback that must be applied after the html has been created, with G.addCallbacks()
  256.         var id=G.textN;
  257.         var str='<span class="updatabletextspan" id="updatabletextspan-'+id+'">'+func()+'</span>';
  258.         G.pushCallback(function(id,func,freq){return function(){
  259.             G.updateTextTimer(id,func,-freq);
  260.         }}(id,func,freq));
  261.         G.textN++;
  262.         return str;
  263.     }
  264.    
  265.     G.tooltipdN=0;
  266.     G.tooltipped=function(text,obj,style)
  267.     {
  268.         var id='tooltippedspan-'+G.tooltipdN;
  269.         //var str='<span class="tooltippedspan"'+(style?' style="'+style+'"':'')+' id="'+id+'">'+text+'</span>';
  270.         var div=document.createElement('div');
  271.         //weird trickery here, don't even ask
  272.         div.innerHTML=text;
  273.         if (div.firstChild.nodeType==3) div.innerHTML='<span>'+div.innerHTML+'</span>';
  274.         if (!div.firstChild.id) div.firstChild.id=id;
  275.         else id=div.firstChild.id;
  276.         str=div.innerHTML;
  277.         G.pushCallback(function(id,obj){return function(){
  278.             if (typeof obj==='string') G.addTooltip(l(id),{text:obj});
  279.             else G.addTooltip(l(id),obj);
  280.         }}(id,obj));
  281.         G.tooltipdN++;
  282.         return str;
  283.     }
  284.    
  285.    
  286.    
  287.     /*=====================================================================================
  288.     LOGIC
  289.     =======================================================================================*/
  290.     G.Logic=function(){}
  291.     G._Logic=function()
  292.     {
  293.         G.Logic();
  294.         if (G.T%5==0 && G.resizing) {G._stabilizeResize();}
  295.        
  296.         if (G.mouseUp) G.mousePressed=false;
  297.         G.mouseDown=false;
  298.         G.mouseUp=false;
  299.         if (G.mouseMoved && G.mousePressed) G.draggedFrames++; else if (!G.mousePressed) G.draggedFrames=0;
  300.         G.mouseMoved=0;
  301.         G.Scroll=0;
  302.         G.clickL=0;
  303.         G.keysD={};
  304.         G.keysU={};
  305.         if (document.activeElement.nodeName=='TEXTAREA' || document.activeElement.nodeName=='INPUT') G.keys={};
  306.        
  307.         G.T++;
  308.     }
  309.    
  310.     /*=====================================================================================
  311.     DRAW
  312.     =======================================================================================*/
  313.     G.Draw=function(){};
  314.     G._Draw=function()
  315.     {
  316.         G.Draw();
  317.         G.drawT++;
  318.     }
  319.    
  320.     /*=====================================================================================
  321.     MAIN LOOP
  322.     =======================================================================================*/
  323.     G.Loop=function()
  324.     {
  325.         //update game logic !
  326.         G.catchupLogic=0;
  327.         G._Logic();
  328.         G.catchupLogic=1;
  329.        
  330.         //latency compensator
  331.         G.accumulatedDelay+=((new Date().getTime()-G.time)-1000/G.fps);
  332.         G.accumulatedDelay=Math.min(G.accumulatedDelay,1000*5);//don't compensate over 5 seconds; if you do, something's probably very wrong
  333.         G.time=new Date().getTime();
  334.         while (G.accumulatedDelay>0)
  335.         {
  336.             G._Logic();
  337.             G.accumulatedDelay-=1000/G.fps;//as long as we're detecting latency (slower than target fps), execute logic (this makes drawing slower but makes the logic behave closer to correct target fps)
  338.         }
  339.         G.catchupLogic=0;
  340.        
  341.         if (!document.hidden || document.hasFocus() || G.T%5==0) G._Draw();
  342.        
  343.         //fps counter and graph
  344.         G.previousFps=G.currentFps;
  345.         G.currentFps=G.getFps();
  346.         if (INFRAME && !EDITOR)
  347.         {
  348.             l('fpsCounter').innerHTML=G.currentFps+' fps';
  349.             var ctx=G.fpsGraphCtx;
  350.             ctx.drawImage(G.fpsGraph,-1,0);
  351.             ctx.fillStyle='rgb('+Math.round((1-G.currentFps/G.fps)*128)+',0,0)';
  352.             ctx.fillRect(128-1,0,1,64);
  353.             ctx.strokeStyle='#fff';
  354.             ctx.beginPath();
  355.             ctx.moveTo(128-1,(1-G.previousFps/G.fps)*64);
  356.             ctx.lineTo(128,(1-G.currentFps/G.fps)*64);
  357.             ctx.stroke();
  358.         }
  359.        
  360.         setTimeout(G.Loop,1000/G.fps);
  361.     }
  362. }
  363.  
  364. G.Launch();
  365.  
  366. if (!INFRAME)
  367. {
  368.     window.onload=function()
  369.     {
  370.         if (!G.ready)
  371.         {
  372.             G.ready=true;
  373.             var vars={};
  374.             var parts=window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value){vars[key]=value;});
  375.             G.vars=vars;
  376.             if (G.vars.e)
  377.             {
  378.                 l('code').innerHTML='<iframe id="editor" src="editor.html"></iframe>';
  379.                 l('wrap').classList.add('withCode');
  380.             }
  381.             if (G.vars.g)
  382.             {
  383.                 l('game').innerHTML='<iframe id="player" src="player.html"></iframe>';
  384.             }
  385.             else
  386.             {
  387.                 l('game').innerHTML='<iframe id="main" src="main.html"></iframe>';
  388.             }
  389.         }
  390.     };
  391.     G.loadedEditor=false;
  392.     G.loadedPlayer=false;
  393.     window.addEventListener('message',function(e)
  394.     {
  395.         if (e.data.playerReady && !G.loadedPlayer)
  396.         {
  397.             G.loadedPlayer=true;
  398.             l('player').contentWindow.postMessage({launch:true,loc:window.location.origin,vars:G.vars},'*');
  399.         }
  400.         else if (e.data.editorReady) {}
  401.         else if (e.data.code && !G.loadedEditor && l('editor'))
  402.         {
  403.             G.loadedEditor=true;
  404.             l('editor').contentWindow.postMessage({code:e.data.code},'*');
  405.         }
  406.         else if (e.data.refresh)
  407.         {
  408.             l('game').innerHTML='<iframe id="player" src="player.html"></iframe>';
  409.             setTimeout(function(){l('player').contentWindow.postMessage({launch:true,loc:window.location.origin,vars:G.vars,code:e.data.refresh},'*');},100);
  410.         }
  411.     });
  412. }
  413. else
  414. {
  415.     if (!G.ready)
  416.     {
  417.         if (EDITOR)
  418.         {
  419.             G.ready=true;
  420.             G.timeSinceTyped=0;
  421.             l('game').innerHTML=`
  422.             <div id="codeWrap">
  423.                 <textarea id="code"></textarea>
  424.             </div>
  425.             `;
  426.             AddEvent(l('code'),'input',function(){G.timeSinceTyped=Math.ceil(G.fps/2);});
  427.             G.Logic=function(){
  428.                 if (G.timeSinceTyped>0) G.timeSinceTyped--;
  429.                 if (G.timeSinceTyped==1) parent.postMessage({refresh:l('code').value},'*');
  430.             }
  431.             G._Init();
  432.             parent.postMessage({editorReady:true},'*');
  433.         }
  434.         else
  435.         {
  436.             parent.postMessage({playerReady:true},'*');
  437.         }
  438.     }
  439.     window.addEventListener('message',function(e)
  440.     {
  441.         if (EDITOR)
  442.         {
  443.             if (e.data.code)
  444.             {
  445.                 l('code').value=e.data.code;
  446.                 l('game').style.display='block';
  447.             }
  448.         }
  449.         else
  450.         {
  451.             if (!G.ready && e.data.launch)
  452.             {
  453.                 G.ready=true;
  454.                 if (e.data.loc==window.location.origin)
  455.                 {
  456.                     if (e.data.code) TOPARSE=e.data.code;
  457.                     G.urlVars=e.data.vars;
  458.                     LoadScript('game.js?v='+(document.lastModified),G._Init);
  459.                 }
  460.             }
  461.         }
  462.     });
  463. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement