-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
8363 lines (7850 loc) · 306 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
All this code is copyright Orteil, 2016-2020.
Spoilers ahead.
welcome to my awful soup
https://orteil.dashnet.org
*/
/*
Note : this is the game engine. It loads and interprets data files.
The default data file is located at /data.js and contains all techs, traits, units, policies, resources, terrains etc.
*/
VERSION=1;//increment by 1 with every major change; will make old datasets incompatible
SAVESLOT='alpha';//actual slot will be 'legacySave-'+SAVESLOT
UPDATELOG=[
{date:'2013-2014',title:'Prototype',text:['started working on a prototype for a cross between Civilization and an idle game after the sudden success of my game, <a href="https://orteil.dashnet.org/cookieclicker/" target="_blank">Cookie Clicker</a>','encountered some issues with gameplay design and ended up putting the project on hold']},
{date:'2015',title:'Prototype, part II',text:['the broken, buggy prototype has been <a href="https://orteil.dashnet.org/experiments/legacy/" target="_blank">put online for all to see</a>']},
{date:'2016',title:'Return of the Prototype',text:['motivated by the positive response to the previous prototype, a new version was started from scratch with fresh new ideas']},
{date:'3/23/2017',title:'Alpha launch',text:['a playable alpha is launched publicly','at this point, the game features 54 technologies, 42 units, and 91 resources']},
{date:'3/24/2017',title:'Alpha patch',text:['added an outline to your explored territory on the map','hunters dying, quarries/mines collapsing and scouts getting lost should no longer disproportionately harm your population; those effects have also been made less frequent','people get sick less often','added a new policy to control birth rate','mines can now mine for salt','resources now display how much you\'re gaining and losing every tick']},
{date:'3/25/2017',title:'Alpha patch 2',text:['units are now queued for automatic purchase rather than being purchased directly; this allows them to be automatically replaced should they be harmed','fixed bug with units getting lost or wounded way too much (maybe for good this time?)','buildings no longer require you to have available tools and workers to build them, as this was confusing and not very fun','graves now decay over time to make room for more; architects now have an "undertaker" mode that automatically creates graves if there are unburied corpses','material and food decay were slowed and storage units have bigger capacity']},
{date:'3/25/2017',title:'Alpha patch 3',text:['units can now be active or inactive; a building that lacks workers, or a crafter that lacks its tools, will simply go inactive instead of disappearing, and will be made active again when the requirements are met; units are inactive when they\'re first created and when they\'ve just been set to a new mode','the mausoleum can be completed again','graves should behave better']},
{date:'3/26/2017',title:'Alpha patch 4',text:['fixed many miscellaneous bugs, hopefully','scouting and exploring speed now properly depends on how many wanderers or scouts you have','gathering is now soft-capped by natural resources; this means having many gathering units but few tiles won\'t have optimal results','removing units now removes the idle ones first']},
{date:'3/26/2017',title:'Alpha patch 5',text:['your people will no longer be completely apathetic and neutrally healthy from some bug with consuming food','fire pits warm more people','clothiers no longer need to know leatherworking to sew grass clothing','happiness and health sources are detailed more explicitly','many messages now have icons']},
{date:'3/28/2017',title:'Alpha patch 6',text:['unit modes now have icons','added custom bulk-buying in units','gathering was reworked, expect different rates for resource production','workers dying while working probably won\'t result in ghost workers anymore','units have innate priorities in the context of being created and acting, with food-producing units going first','happier people now produce more babies, while unhappy people just aren\'t feeling it as much','corpses decay slowly']},
];
//misc handy stuff
function l(what) {return document.getElementById(what);}
function choose(arr) {return arr[Math.floor(Math.random()*arr.length)];}
function randomFloor(x) {if ((x%1)<Math.random()) return Math.floor(x); else return Math.ceil(x);}
String.prototype.replaceAll=function(search,replacement)
{var target=this;return target.replace(new RegExp(search,'g'),replacement);};
function AddEvent(html_element,event_name,event_function)
{
if(html_element.attachEvent) html_element.attachEvent("on" + event_name, function() {event_function.call(html_element);});
else if(html_element.addEventListener) html_element.addEventListener(event_name, event_function, false);
}
function addHover(el,className)
{
AddEvent(el,'mouseover',function(className){return function(e){e.target.classList.add(className);};}(className));
AddEvent(el,'mouseout',function(className){return function(e){e.target.classList.remove(className);};}(className));
}
function addCSSRule(sheet, selector, rules, index)
{
if("insertRule" in sheet) sheet.insertRule(selector + "{" + rules + "}", index);
else if("addRule" in sheet) sheet.addRule(selector, rules, index);
}
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
function addObjects(obj1,obj2)
{
var out={};
for (var i in obj1)
{out[i]=obj1[i];}
for (var i in obj2)
{
if (!out[i]) out[i]=0;
out[i]+=obj2[i];
}
return out;
}
function isEmpty(obj)
{
return (Object.keys(obj).length === 0 && obj.constructor === Object);
}
function byteCount(s){return encodeURI(s).split(/%..|./).length-1;}
//also see : http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/
function decodeEntities(string){
var elem=document.createElement('div');
elem.innerHTML=string;
return elem.textContent;
}
function b64EncodeUnicode(str){
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function b64DecodeUnicode(str){
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function triggerAnim(element,anim)
{
if (!element) return;
element.classList.remove(anim);
void element.offsetWidth;
element.classList.add(anim);
}
//file save function from https://github.com/eligrey/FileSaver.js
var saveAs=saveAs||function(view){"use strict";if(typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var doc=view.document,get_URL=function(){return view.URL||view.webkitURL||view},save_link=doc.createElementNS("http://www.w3.org/1999/xhtml","a"),can_use_save_link="download"in save_link,click=function(node){var event=new MouseEvent("click");node.dispatchEvent(event)},is_safari=/Version\/[\d\.]+.*Safari/.test(navigator.userAgent),webkit_req_fs=view.webkitRequestFileSystem,req_fs=view.requestFileSystem||webkit_req_fs||view.mozRequestFileSystem,throw_outside=function(ex){(view.setImmediate||view.setTimeout)(function(){throw ex},0)},force_saveable_type="application/octet-stream",fs_min_size=0,arbitrary_revoke_timeout=500,revoke=function(file){var revoker=function(){if(typeof file==="string"){get_URL().revokeObjectURL(file)}else{file.remove()}};if(view.chrome){revoker()}else{setTimeout(revoker,arbitrary_revoke_timeout)}},dispatch=function(filesaver,event_types,event){event_types=[].concat(event_types);var i=event_types.length;while(i--){var listener=filesaver["on"+event_types[i]];if(typeof listener==="function"){try{listener.call(filesaver,event||filesaver)}catch(ex){throw_outside(ex)}}}},auto_bom=function(blob){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)){return new Blob(["\ufeff",blob],{type:blob.type})}return blob},FileSaver=function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}var filesaver=this,type=blob.type,blob_changed=false,object_url,target_view,dispatch_all=function(){dispatch(filesaver,"writestart progress write writeend".split(" "))},fs_error=function(){if(target_view&&is_safari&&typeof FileReader!=="undefined"){var reader=new FileReader;reader.onloadend=function(){var base64Data=reader.result;target_view.location.href="data:attachment/file"+base64Data.slice(base64Data.search(/[,;]/));filesaver.readyState=filesaver.DONE;dispatch_all()};reader.readAsDataURL(blob);filesaver.readyState=filesaver.INIT;return}if(blob_changed||!object_url){object_url=get_URL().createObjectURL(blob)}if(target_view){target_view.location.href=object_url}else{var new_tab=view.open(object_url,"_blank");if(new_tab==undefined&&is_safari){view.location.href=object_url}}filesaver.readyState=filesaver.DONE;dispatch_all();revoke(object_url)},abortable=function(func){return function(){if(filesaver.readyState!==filesaver.DONE){return func.apply(this,arguments)}}},create_if_not_found={create:true,exclusive:false},slice;filesaver.readyState=filesaver.INIT;if(!name){name="download"}if(can_use_save_link){object_url=get_URL().createObjectURL(blob);setTimeout(function(){save_link.href=object_url;save_link.download=name;click(save_link);dispatch_all();revoke(object_url);filesaver.readyState=filesaver.DONE});return}if(view.chrome&&type&&type!==force_saveable_type){slice=blob.slice||blob.webkitSlice;blob=slice.call(blob,0,blob.size,force_saveable_type);blob_changed=true}if(webkit_req_fs&&name!=="download"){name+=".download"}if(type===force_saveable_type||webkit_req_fs){target_view=view}if(!req_fs){fs_error();return}fs_min_size+=blob.size;req_fs(view.TEMPORARY,fs_min_size,abortable(function(fs){fs.root.getDirectory("saved",create_if_not_found,abortable(function(dir){var save=function(){dir.getFile(name,create_if_not_found,abortable(function(file){file.createWriter(abortable(function(writer){writer.onwriteend=function(event){target_view.location.href=file.toURL();filesaver.readyState=filesaver.DONE;dispatch(filesaver,"writeend",event);revoke(file)};writer.onerror=function(){var error=writer.error;if(error.code!==error.ABORT_ERR){fs_error()}};"writestart progress write abort".split(" ").forEach(function(event){writer["on"+event]=filesaver["on"+event]});writer.write(blob);filesaver.abort=function(){writer.abort();filesaver.readyState=filesaver.DONE};filesaver.readyState=filesaver.WRITING}),fs_error)}),fs_error)};dir.getFile(name,{create:false},abortable(function(file){file.remove();save()}),abortable(function(ex){if(ex.code===ex.NOT_FOUND_ERR){save()}else{fs_error()}}))}),fs_error)}),fs_error)},FS_proto=FileSaver.prototype,saveAs=function(blob,name,no_auto_bom){return new FileSaver(blob,name,no_auto_bom)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(blob,name,no_auto_bom){if(!no_auto_bom){blob=auto_bom(blob)}return navigator.msSaveOrOpenBlob(blob,name||"download")}}FS_proto.abort=function(){var filesaver=this;filesaver.readyState=filesaver.DONE;dispatch(filesaver,"abort")};FS_proto.readyState=FS_proto.INIT=0;FS_proto.WRITING=1;FS_proto.DONE=2;FS_proto.error=FS_proto.onwritestart=FS_proto.onprogress=FS_proto.onwrite=FS_proto.onabort=FS_proto.onerror=FS_proto.onwriteend=null;return saveAs}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!=null){define([],function(){return saveAs})}
//the old Beautify function from Cookie Clicker, shortened to B(value)
//initially adapted from http://cookieclicker.wikia.com/wiki/Frozen_Cookies_%28JavaScript_Add-on%29
function formatEveryThirdPower(notations)
{
return function (value)
{
var base = 0,
notationValue = '';
if (value >= 1000 && isFinite(value))
{
value /= 1000;
while(Math.round(value) >= 1000)
{
value /= 1000;
base++;
}
if (base > notations.length) {return 'Inf';} else {notationValue = notations[base];}
}
return ( Math.round(value * 10) / 10 ) + notationValue;
};
}
var magixNote = false
function rawFormatter(value) {return value % 1 ? Math.floor(value * 1000) / 1000 : value;}
var numberFormatters =
[
rawFormatter,
formatEveryThirdPower([
' thousand',
' million',
' billion',
' trillion',
' quadrillion',
' quintillion',
' sextillion',
' septillion',
' octillion',
' nonillion',
' decillion',
' undecillion',
' duodecillion',
' tredecillion'
]),
formatEveryThirdPower([
'k',
'M',
'B',
'T',
'Qa',
'Qi',
'Sx',
'Sp',
'Oc',
'No',
'Dc',
'Ud',
'Dd',
'Td'
])
];
function Beautify(value,floats)
{
var negative=(value<0);
var decimal='';
if (Math.abs(value)<1000 && floats>0) decimal='.'+(value.toFixed(floats).toString()).split('.')[1];
value=Math.floor(Math.abs(value));
var formatter=numberFormatters[2];
var output=formatter(value).toString().replace(/\B(?=(\d{3})+(?!\d))/g,',');
if (output=='0') negative=false;
return negative?'-'+output:output+decimal;
}
var B=Beautify;
function BeautifyTime(value)
{
//value should be in seconds
value=Math.max(Math.ceil(value,0));
var years=Math.floor(value/31536000);
value-=years*31536000;
var days=Math.floor(value/86400);
value-=days*86400;
var hours=Math.floor(value/3600)%24;
value-=hours*3600;
var minutes=Math.floor(value/60)%60;
value-=minutes*60;
var seconds=Math.floor(value)%60;
var str='';
if (years) str+=B(years)+'Y';
if (days || str!='') str+=B(days)+'d';
if (hours || str!='') str+=hours+'h';
if (minutes || str!='') str+=minutes+'m';
if (seconds || str!='') str+=seconds+'s';
if (str=='') str+='0s';
return str;
}
var BT=BeautifyTime;
function cap(str)
{return str.charAt(0).toUpperCase()+str.slice(1);}
//polyfills
if (!String.prototype.includes) {
Object.defineProperty(String.prototype, "includes", {value:
function(search, start) {
'use strict';
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
}
});
}
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, "includes", {value:
function(searchElement /*, fromIndex*/ ) {
'use strict';
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement) { // NaN !== NaN
return true;
}
k++;
}
return false;
}
});
}
//other fun stuff
//seeded random function, courtesy of http://davidbau.com/archives/2010/01/30/random_seeds_coded_hints_and_quintillions.html
(function(a,b,c,d,e,f){function k(a){var b,c=a.length,e=this,f=0,g=e.i=e.j=0,h=e.S=[];for(c||(a=[c++]);d>f;)h[f]=f++;for(f=0;d>f;f++)h[f]=h[g=j&g+a[f%c]+(b=h[f])],h[g]=b;(e.g=function(a){for(var b,c=0,f=e.i,g=e.j,h=e.S;a--;)b=h[f=j&f+1],c=c*d+h[j&(h[f]=h[g=j&g+b])+(h[g]=b)];return e.i=f,e.j=g,c})(d)}function l(a,b){var e,c=[],d=(typeof a)[0];if(b&&"o"==d)for(e in a)try{c.push(l(a[e],b-1))}catch(f){}return c.length?c:"s"==d?a:a+"\0"}function m(a,b){for(var d,c=a+"",e=0;c.length>e;)b[j&e]=j&(d^=19*b[j&e])+c.charCodeAt(e++);return o(b)}function n(c){try{return a.crypto.getRandomValues(c=new Uint8Array(d)),o(c)}catch(e){return[+new Date,a,a.navigator.plugins,a.screen,o(b)]}}function o(a){return String.fromCharCode.apply(0,a)}var g=c.pow(d,e),h=c.pow(2,f),i=2*h,j=d-1;c.seedrandom=function(a,f){var j=[],p=m(l(f?[a,o(b)]:0 in arguments?a:n(),3),j),q=new k(j);return m(o(q.S),b),c.random=function(){for(var a=q.g(e),b=g,c=0;h>a;)a=(a+c)*d,b*=d,c=q.g(1);for(;a>=i;)a/=2,b/=2,c>>>=1;return(a+c)/b},p},m(c.random(),b)})(this,[],Math,256,6,52);
chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRSTUVWXYZ0123456789'.split('');
makeSeed=function(len)
{
var str='';
for (var i=0;i<len;i++)
{str+=choose(chars);}
return str;
}
pics=[];
Pic=function(url)
{
return pics[url];
}
PicLoader=function(urls,callback)
{
this.pics=[];
this.toLoad=urls.length;
this.loaded=0;
this.callback=callback;
for (var i in urls)
{
var pic=new Image();
//pic.setAttribute('crossOrigin','Anonymous');
pic.src=urls[i];
pic.onload=function(loader){return function(){loader.toLoad--;loader.loaded++;if (loader.toLoad<=0) loader.callback();}}(this);
pics[urls[i]]=pic;
}
}
ERROR=function(what)
{
console.log(what);
console.trace();
}
//getting this started
G={};//(actually short for "Game")
G.Launch=function()
{
/*=====================================================================================
INITIALIZE
=======================================================================================*/
G.engineVersion=VERSION;
G.LoadResources=function()
{
var resources=[
'img/terrain.png',
'img/blot.png',
'img/iconSheet.png?v=1'
];
var loader=new PicLoader(resources,function(){G.Init();});//load all resources then init the game when done
}
G.selectVersion=function(e)
{
var version=G.versionsById[e.target.value];
if (version) window.location.href=version.url;
}
G.Init=function()
{
G.T=0;
G.drawT=0;
G.fps=30;
G.l=l('game');
G.wrapl=l('wrap');
G.wrapl.classList.add('skinRock');
G.local=true;
if (window.location.protocol=='http:' || window.location.protocol=='https:') G.local=false;
G.isIE=false;
if (document.documentMode || /Edge/.test(navigator.userAgent)) G.isIE=true;
if (G.versions)
{
G.versionsById=[];
for (var i in G.versions)
{
G.versionsById[G.versions[i].version]=G.versions[i];
}
var str='';
str+='<select id="versionsSelect" onchange="G.selectVersion(event);">';
for (var i in G.versions)
{
var version=G.versions[i];
str+='<option '+(version.version==G.engineVersion?'selected="selected" ':'')+'value="'+version.version+'">'+version.name+'</option>';
}
str+='</select>';
l('versions').innerHTML=str;
}
//upscale pixel icons and apply to stylesheet (this is kind of cheaty)
//only for Edge and IE since they have """"trouble"""" with nearest-neighbor
G.iconScale=1;
G.iconURL='img/iconSheet.png?v=1';
if (G.isIE)
{
var img=Pic('img/iconSheet.png?v=1');
var c=document.createElement('canvas');c.width=img.width*2;c.height=img.height*2;
var ctx=c.getContext('2d');
ctx.mozImageSmoothingEnabled=false;
ctx.webkitImageSmoothingEnabled=false;
ctx.msImageSmoothingEnabled=false;
ctx.imageSmoothingEnabled=false;
ctx.drawImage(img,0,0,img.width*2,img.height*2);
var sheet=(function()
{
var style=document.createElement('style');
style.appendChild(document.createTextNode(''));
document.head.appendChild(style);
return style.sheet;
})();
addCSSRule(sheet,'.IE .icon','background-image:url('+c.toDataURL('image/png')+')');
G.iconURL=c.toDataURL('image/png');
addCSSRule(sheet,'.IE .icon.double','background-image:url('+G.iconURL+'),url('+G.iconURL+')');
G.wrapl.classList.add('IE');
G.iconScale=2;
}
G.w=window.innerWidth;
G.h=window.innerHeight;
G.resizing=false;
G.stabilizeResize=function()
{
G.resizing=false;
//change page layout to fit width
if (G.w<288*3) {G.wrapl.classList.remove('narrow');G.wrapl.classList.add('narrower');}
else if (G.w<384*3) {G.wrapl.classList.remove('narrower');G.wrapl.classList.add('narrow');}
else {G.wrapl.classList.remove('narrower');G.wrapl.classList.remove('narrow');}
//if (G.tab.id=='unit') G.cacheUnitBounds();
}
G.resize=function()
{
G.resizing=true;
}
window.addEventListener('resize',function(event)
{
G.w=window.innerWidth;
G.h=window.innerHeight;
G.resize();
});
G.mouseDown=false;//mouse button just got pressed
G.mouseUp=false;//mouse button just got released
G.mousePressed=false;//mouse button is currently down
G.clickL=0;//what element got clicked
AddEvent(document,'mousedown',function(event){G.mouseDown=true;G.mousePressed=true;G.mouseDragFrom=event.target;G.mouseDragFromX=G.mouseX;G.mouseDragFromY=G.mouseY;});
AddEvent(document,'mouseup',function(event){G.mouseUp=true;G.mouseDragFrom=0;});
AddEvent(document,'click',function(event){G.clickL=event.target;});
G.mouseX=0;
G.mouseY=0;
G.mouseMoved=0;
G.draggedFrames=0;//increment every frame when we're moving the mouse and we're clicking
G.GetMouseCoords=function(e)
{
var posx=0;
var posy=0;
if (!e) var e=window.event;
if (e.pageX||e.pageY)
{
posx=e.pageX;
posy=e.pageY;
}
else if (e.clientX || e.clientY)
{
posx=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
posy=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;
}
var x=0;
var y=0;
G.mouseX=posx-x;
G.mouseY=posy-y;
G.mouseMoved=1;
}
AddEvent(document,'mousemove',G.GetMouseCoords);
G.Scroll=0;
G.handleScroll=function(e)
{
if (!e) e=event;
G.Scroll=(e.detail<0||e.wheelDelta>0)?1:-1;
};
AddEvent(document,'DOMMouseScroll',G.handleScroll);
AddEvent(document,'mousewheel',G.handleScroll);
G.keys=[];//key is being held down
G.keysD=[];//key was just pressed down
G.keysU=[];//key was just pressed up
//shift=16, ctrl=17
AddEvent(window,'keyup',function(e){
if ((document.activeElement.nodeName=='TEXTAREA' || document.activeElement.nodeName=='INPUT') && e.keyCode!=27) return;
if (e.keyCode==27) {}//esc
else if (e.keyCode==13) {}//enter
G.keys[e.keyCode]=0;
G.keysD[e.keyCode]=0;
G.keysU[e.keyCode]=1;
});
AddEvent(window,'keydown',function(e){
if (!G.keys[e.keyCode])//prevent repeats
{
if (e.ctrlKey && e.keyCode==83) {e.preventDefault();}//ctrl-s
if ((document.activeElement.nodeName=='TEXTAREA' || document.activeElement.nodeName=='INPUT') && e.keyCode!=27) return;
if (e.keyCode==32) {e.preventDefault();}//space
G.keys[e.keyCode]=1;
G.keysD[e.keyCode]=1;
G.keysU[e.keyCode]=0;
//console.log('Key pressed : '+e.keyCode);
}
});
AddEvent(window,'blur',function(e){
G.keys=[];
G.keysD=[];
G.keysU=[];
});
//latency compensator stuff
G.time=new Date().getTime();
G.fpsMeasure=new Date().getTime();
G.accumulatedDelay=0;
G.catchupLogic=0;
G.fpsStartTime=0;
G.frameNumber=0;
G.getFps=function()
{
G.frameNumber++;
var currentTime=(Date.now()-G.fpsStartTime )/1000;
var result=Math.floor((G.frameNumber/currentTime));
if (currentTime>1)
{
G.fpsStartTime=Date.now();
G.frameNumber=0;
}
return result;
}
G.fpsGraph=l('fpsGraph');
G.fpsGraphCtx=G.fpsGraph.getContext('2d');
var ctx=G.fpsGraphCtx;
ctx.fillStyle='#000';
ctx.fillRect(0,0,128,64);
G.currentFps=0;
G.previousFps=0;
G.animIntro=true;
G.introDur=G.fps*1;
//is there a file save already? if yes, load it, if not, hard-reset and start a new game
if (!G.Load())
{
G.Reset(true);
G.NewGame();
}
G.resize();
G.Loop();
}
/*=====================================================================================
UPDATES, DRAWS & LOGICS
=======================================================================================*/
G.update=[];//these involve rebuilding a whole display's DOM
G.draw=[];//these involve updating elements within the display and should be invoked within G.Draw
G.logic=[];//these involve updating gameplay elements and should be invoked within G.Logic
/*=====================================================================================
SAVING AND LOADING
=======================================================================================*/
G.saveTo='legacySave-'+SAVESLOT;
G.FileSave=function()
{
var filename='legacySave';
var text=G.Export();
var blob=new Blob([text],{type:'text/plain;charset=utf-8'});
saveAs(blob,filename+'.txt');
}
G.FileLoad=function(e)
{
if (e.target.files.length==0) return false;
var file=e.target.files[0];
var reader=new FileReader();
reader.onload=function(e)
{
G.Import(e.target.result);
}
reader.readAsText(file);
}
G.Export=function()
{
return G.Save(true);
}
G.Import=function(str)
{
// Magix will override the G.Load function, so we add an extra step here
try {
G.importStr=b64EncodeUnicode(escape(unescape(b64DecodeUnicode(str)).replace("https://file.garden/Xbm-ilapeDSxWf1b/MagixOfficialR55B.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magix.js").replace("https://file.garden/Xbm-ilapeDSxWf1b/MagixUtilsR55B.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magixUtils.js").replace("https://file.garden/ZmatEHzFI2_QBuAF/magix.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magix.js").replace("https://file.garden/ZmatEHzFI2_QBuAF/magixUtils.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magixUtils.js")));
} catch (e) {
alert("The save that you have provided was invalid.");
console.warn(e);
return;
}
G.Load(false);
}
G.Save=function(toStr)
{
//if toStr is true, don't actually save; return a string containing the save
if (!toStr && G.local && G.isIE) return false;
var str='';
//general
G.lastDate=parseInt(Date.now());
str+=
parseFloat(G.engineVersion).toString()+';'+
parseFloat(G.startDate).toString()+';'+
parseFloat(G.fullDate).toString()+';'+
parseFloat(G.lastDate).toString()+';'+
parseFloat(G.year).toString()+';'+
parseFloat(G.day).toString()+';'+
parseFloat(G.fastTicks).toString()+';'+
parseFloat(G.furthestDay).toString()+';'+
parseFloat(G.totalDays).toString()+';'+
parseFloat(G.resets).toString()+';'+
'';
str+='|';
//settings
for (var i in G.settings)
{
var me=G.settings[i];
if (me.type=='toggle') str+=(me.value?'1':'0');
else if (me.type=='int') str+=parseInt(me.value).toString();
str+=';';
}
str+='|';
//mods
for (var i in G.mods)
{
var me=G.mods[i];
str+='"'+me.url.replaceAll('"','"')+'":';
if (me.achievs)
{
//we save achievements separately for each mod
for (var ii in me.achievs)
{
str+=parseInt(me.achievs[ii].won).toString()+',';
}
}
str+=':';
//tracked stats (not fully implemented yet)
str+=parseFloat(G.trackedStat).toString();
str+=';';
}
str+='|';
//culture and names
str+=(G.cultureSeed)+';';
str+=G.getSafeName('ruler')+';';
str+=G.getSafeName('civ')+';';
str+=G.getSafeName('civadj')+';';
str+=G.getSafeName('inhab')+';';
str+=G.getSafeName('inhabs')+';';
str+='|';
//maps
str+=(G.currentMap.seed)+';';
var map=G.currentMap;
for (var x=0;x<map.w;x++)
{
for (var y=0;y<map.h;y++)
{
var tile=map.tiles[x][y];
str+=
parseInt(tile.owner).toString()+':'+
parseInt(Math.floor(tile.explored*100)).toString()+':'+
',';
}
}
str+='|';
//techs & traits
var len=G.techsOwned.length;
for (var i=0;i<len;i++)
{
str+=parseInt(G.techsOwned[i].tech.id).toString()+';';
}
str+='|';
var len=G.traitsOwned.length;
for (var i=0;i<len;i++)
{
str+=parseInt(G.traitsOwned[i].trait.id).toString()+';';
}
str+='|';
//policies
var len=G.policy.length;
for (var i=0;i<len;i++)
{
var me=G.policy[i];
if (me.visible)
{
str+=parseInt(me.id).toString()+','+parseInt(me.mode?me.mode.num:0).toString()+';';
}
}
str+='|';
//res
var len=G.res.length;
for (var i=0;i<len;i++)
{
var me=G.res[i];
str+=
(!me.meta?(parseFloat(Math.round(me.amount)).toString()+','):'')+
(me.displayUsed?(parseFloat(Math.round(me.used)).toString()+','):'')+
(me.visible?'1':'0')+';';
}
str+='|';
//units
var len=G.unitsOwned.length;
for (var i=0;i<len;i++)
{
var me=G.unitsOwned[i];
if (true)//me.amount>0)
{
str+=parseInt(me.unit.id).toString()+','+
parseFloat(Math.round(me.amount)).toString()+
((me.unit.gizmos||me.unit.wonder)?
(','+parseInt(me.unit.wonder?me.mode:(me.mode?me.mode.num:0)).toString()+','+//mode
parseInt(me.percent).toString())//percent
:'')+
','+parseFloat(Math.round(me.targetAmount)).toString()+
','+parseFloat(Math.round(me.idle)).toString()+
';';
}
}
str+='|';
//chooseboxes
var len=G.chooseBox.length;
for (var i=0;i<len;i++)
{
var me=G.chooseBox[i];
var choices=[parseFloat(me.roll)];
for (var ii in me.choices)
{
choices.push(parseInt(me.choices[ii].id));
}
str+=choices.join(',')+';';
}
str+='|';
if (toStr)
{
str=str.replace("https://raw.githubusercontent.com/plasma4/magix-fix/master/magix.js","https://file.garden/ZmatEHzFI2_QBuAF/magix.js").replace("https://raw.githubusercontent.com/plasma4/magix-fix/master/magixUtils.js","https://file.garden/ZmatEHzFI2_QBuAF/magixUtils.js")
}
//console.log('SAVE');
//console.log(str);
str=escape(str);
str=b64EncodeUnicode(str);
//console.log(Math.ceil(byteCount(str)/1000)+'kb');
if (!toStr)
{
window.localStorage.setItem(G.saveTo,str);
G.middleText('- Game saved -');
//console.log('Game saved successfully.');
}
else return str;
}
G.stringsLoadedN=0;
G.stringsLoaded=[];
G.parseLoadStrings=function(str)
{
str=str.substring(1,str.length-1);
//str=decodeEntities(str);
G.stringsLoaded[G.stringsLoadedN]=str;
G.stringsLoadedN++;
return 'str'+(G.stringsLoadedN-1);
}
G.readLoadedString=function(str)
{
if (!str || str.indexOf('str')==-1) return 0;
return G.stringsLoaded[parseInt(str.split('str')[1])];
}
G.importStr=0;
G.Load=function(doneLoading)
{
if (G.importStr) {var local=G.importStr;}
else
{
if (G.local && G.isIE) return false;
if (!window.localStorage) return false;
var local=window.localStorage.getItem(G.saveTo);
}
if (!local) return false;
var str='';
str=b64DecodeUnicode(local);
//console.log('LOAD');
//console.log(Math.ceil(byteCount(str)/1000)+'kb');
str=unescape(str);
//console.log(str);
if (str!='null' && str!='')
{
G.Reset();
G.resetSettings();
//take care of strings first
G.stringsLoadedN=0;
G.stringsLoaded=[];
str=str.replace("https://file.garden/Xbm-ilapeDSxWf1b/MagixOfficialR55B.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magix.js").replace("https://file.garden/Xbm-ilapeDSxWf1b/MagixUtilsR55B.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magixUtils.js").replace("https://file.garden/ZmatEHzFI2_QBuAF/magix.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magix.js").replace("https://file.garden/ZmatEHzFI2_QBuAF/magixUtils.js","https://raw.githubusercontent.com/plasma4/magix-fix/master/magixUtils.js").replace(/"(.*?)"/gi,G.parseLoadStrings);
str=str.split('|');
var s=0;
//general
var spl=str[s++].split(';');
//console.log('General : '+spl);
var i=0;
var fromVersion=parseFloat(spl[i++]);
G.startDate=parseFloat(spl[i++]);
G.fullDate=parseFloat(spl[i++]);
G.lastDate=parseFloat(spl[i++]);
G.year=parseFloat(spl[i++]);
G.day=parseFloat(spl[i++]);
G.fastTicks=parseFloat(spl[i++]);
G.furthestDay=parseFloat(spl[i++]);
G.totalDays=parseFloat(spl[i++]);
G.resets=parseFloat(spl[i++]);
//accumulate fast ticks when offline
var timeOffline=Math.max(0,(Date.now()-G.lastDate)/1000);
G.fastTicks+=Math.floor(timeOffline);
G.nextFastTick=Math.ceil((1-(timeOffline-Math.floor(timeOffline)))*G.tickDuration);
//settings
var spl=str[s++].split(';');
//console.log('Settings : '+spl);
var len=spl.length;
for (var i=0;i<len;i++)
{
if (spl[i]!='' && G.settings[i])
{
var me=G.settings[i];
if (me.type=='toggle') me.value=(spl[i]=='1'?true:false);
else if (me.type=='int') me.value=parseInt(spl[i]);
}
}
for (var i in G.settings)
{
var me=G.settings[i];
if (me.onChange) me.onChange();
}
if (!doneLoading)
{
//mods
var spl=str[s++].split(';');
var mods=[];
for (var i in spl)
{
var spl2=spl[i].split(':');
var val=G.readLoadedString(spl2[0]);
if (val)
{
mods.push(val.replaceAll('"','"'));
}
}
G.LoadMods(mods,G.Load,false);
return 1;
}
G.importStr=0;
//mod achievs & tracked stats
var spl=str[s++].split(';');
for (var i in spl)
{
var spl2=spl[i].split(':');
var mod=G.mods[i];
if (spl2[1] && mod.achievs)
{
bit=spl2[1].split(',');
for (var ii in bit)
{
if (bit[ii])
{
if (mod.achievs[ii]) mod.achievs[ii].won=parseInt(bit[ii]);
}
}
}
if (spl2[2])
{
bit=spl2[2].split(',');
for (var ii in bit)
{
if (bit[ii])
{
G.trackedStat=parseFloat(bit[ii]);
}
}
}
}
//culture and names
var spl=str[s++].split(';');
var ss=0;
G.cultureSeed=spl[ss++];
G.setSafeName('ruler',G.readLoadedString(spl[ss++]),'Anonymous');
G.setSafeName('civ',G.readLoadedString(spl[ss++]),'nameless tribe');
G.setSafeName('civadj',G.readLoadedString(spl[ss++]),'tribal');
G.setSafeName('inhab',G.readLoadedString(spl[ss++]),'inhabitant');
G.setSafeName('inhabs',G.readLoadedString(spl[ss++]),'inhabitants');
//maps
var spl=str[s++].split(';');
//console.log('Map tiles : '+spl);
G.currentMap=new G.Map(0,24,24,spl[0]);
var map=G.currentMap;
var spl2=spl[1].split(',');
var I=0;
for (var x=0;x<map.w;x++)
{
for (var y=0;y<map.h;y++)
{
if (spl2[I])
{
var tile=map.tiles[x][y];
spl3=spl2[I].split(':');
tile.owner=parseInt(spl3[0]);
tile.explored=parseInt(spl3[1])/100;
}
I++;
}
}
G.updateMapForOwners(map);
G.centerMap(map);
//techs & traits
var spl=str[s++].split(';');
//console.log('Techs : '+spl);
var len=spl.length;
for (var i=len-1;i>=0;i--)
{if (spl[i]!='') {G.gainTech(G.know[parseInt(spl[i])]);}}
var spl=str[s++].split(';');
//console.log('Traits : '+spl);
var len=spl.length;
for (var i=len-1;i>=0;i--)
{if (spl[i]!='') G.gainTrait(G.know[parseInt(spl[i])]);}
//policies
var spl=str[s++].split(';');
//console.log('Policies : '+spl);
var len=spl.length;
for (var i=len-1;i>=0;i--)
{if (spl[i]!='') {
var spl2=spl[i].split(',');
var me=G.policy[parseInt(spl2[0])];
G.gainPolicy(me);
me.mode=me.modesById[parseInt(spl2[1])];
}}
//res
var spl=str[s++].split(';');
//console.log('Resources : '+spl);
var len=G.res.length;
for (var i=0;i<len;i++)
{
if (spl[i])
{
var me=G.res[i];
var spl2=spl[i].split(',');
if (parseInt(spl2[spl2.length-1])==1) me.visible=true; else me.visible=false;
if (!me.meta) me.amount=parseFloat(spl2[0]);
if (me.displayUsed) me.used=parseFloat(spl2[1]);
}
}
//units
var spl=str[s++].split(';');
//console.log('Units : '+spl);
var len=spl.length;
for (var i=len-1;i>=0;i--)
{if (spl[i]!='')
{
var spl2=spl[i].split(',');
//unit id, amount, and if unit has gizmos : mode, percent
var obj={
id:G.unitN,
unit:G.unit[parseInt(spl2[0])],
amount:parseFloat(spl2[1]),
targetAmount:((typeof spl2[4]!=='undefined')?parseFloat(spl2[4]):parseFloat(spl2[1])),
idle:((typeof spl2[5]!=='undefined')?parseFloat(spl2[5]):0),
displayedAmount:0,
mode:parseInt(spl2[2])||0,
percent:parseInt(spl2[3]),
popups:[]
};
G.unitsOwned.unshift(obj);
var unit=G.unitsOwned[0];
if (unit.unit.modesById[0]) unit.mode=unit.unit.modesById[unit.mode];
G.unitsOwnedNames.unshift(G.unit[parseInt(spl2[0])].name);
G.unitN++;
}
}
//assign unit .splitOf
var prev=0;
var len=G.unitsOwned.length;
for (var i=0;i<len;i++)
{