Advertisement
Guest User

Untitled

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