-
Notifications
You must be signed in to change notification settings - Fork 0
/
magixUtils.js
5768 lines (5425 loc) · 344 KB
/
magixUtils.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
/*
Setup process:
- IF YOU ALREADY HAVE MAGIX INSTALLED:
Paste the script below into the console.
javascript:localStorage.setItem("legacySave-alpha",b64EncodeUnicode(escape(unescape(b64DecodeUnicode(G.Export())).replace("Xbm-ilapeDSxWf1b/MagixOfficialR55B.js","ZmatEHzFI2_QBuAF/magix.js").replace("Xbm-ilapeDSxWf1b/MagixUtilsR55B.js","ZmatEHzFI2_QBuAF/magixUtils.js")))),onbeforeunload=null,location.reload()
>>> It's that easy! If you can't open the console for some reason, you can try selecting all the code above and dragging it to your browser's bookmark bar. Then, go to the tab with NeverEnding Legacy open and click on the bookmark. After that, the bookmark isn't needed anymore and can be removed.
==========
- IF YOU ARE STARTING FROM A NEW GAME:
To set up this mod, go to Orteil's NeverEnding Legacy and click on the Load Mod button. From the text box that pops up, delete the default text and paste in the following 2 lines:
https://file.garden/ZmatEHzFI2_QBuAF/magixUtils.js
https://file.garden/ZmatEHzFI2_QBuAF/magix.js
>>> If you pasted them in with that order and deleted the default text, it should work!
==========
- DOWNLOADING MAGIX LOCALLY:
If you wish to download Magix in a local copy for offline use or modding, you can do so download the .zip file at https://github.com/plasma4/magix-fix/archive/refs/heads/main.zip to get started!
>>> You next step should be to extract the .zip file (to ensure assets work properly) and to open the index.html file. Congrats! You can now use Magix or load other mods in without internet.
*/
/* Additionally, PLEASE BE AWARE: The creator of this mod has personally stated in Discord messages that the Magix mod may be modded by anyone who wishes. This mod provides a few important fixes that prevent the game from breaking, as well as a large amount of rewritings and small changes. To compare, visit https://file.garden/Xbm-ilapeDSxWf1b/MagixUtilsR55B.js to find the original source. */
// Custom storage tools that 1) don't break the save data and 2) are saved when exporting
if (!window.magixLoaded) {
window.magixLoaded = 1
var conflictingStorageObjects = ["civ"]
G.storageObject = {}
try {
G.storageObject = localStorage.getItem("legacySave-alpha")
if (G.storageObject) {
G.storageObject = unescape(b64DecodeUnicode(G.storageObject)).match(/\$\{.+?\}/)
if (G.storageObject) {
G.storageObject = G.storageObject[G.storageObject.length - 1]
if (G.storageObject) {
G.storageObject = JSON.parse(G.storageObject.slice(1).replaceAll('&QOT', '"'))
} else {
G.storageObject = {}
}
} else {
G.storageObject = {}
}
} else {
G.storageObject = {}
}
} catch (e) {
console.warn("Storage data could not be obtained.")
G.storageObject = {}
}
}
var isUsingFile = window.offlineMode != null
var magixURL = isUsingFile ? "Magix/" : "https://file.garden/Xbm-ilapeDSxWf1b/"
var magixURL2 = isUsingFile ? "Magix/" : "https://file.garden/ZmatEHzFI2_QBuAF/"
var orteilURL = window.offlineMode ? "Magix/" : "https://orteil.dashnet.org/cookieclicker/snd/"
// Cookies aren't really needed for this case, so they have been replaced with localStorage from now on; in addition, i've made it so that the game can detect the object data anyway without them by changing the releaseNumber value: this is just a backup method for those older versions
function getObj(key) {
var storageItem = G.storageObject[key]
if (storageItem != null) {
return storageItem
}
try {
var localItem = localStorage.getItem(key)
if (localItem !== null) {
return localItem
}
} catch (e) {
}
if (navigator.cookieEnabled) {
let name = key + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
}
return null;
}
function setObj(key, value) {
G.storageObject[key] = value
}
function unitAmount(res, res2, cap) {
var item = G.unitByName[res]
return (item.amount - item.idle) * Math.min(res2 == null ? 1 : G.getAmount(res2), cap == null ? Infinity : cap)
}
G.setDict = function (name, what) {
// No more warnings :p
G.dict[name] = what
}
/*==========================
TABS (yeah, this needs some changing and touch-ups, eh?)
==========================*/
function tabs() {
if (G.tabs[0].name.slice(0, 5) === "<font") {
return
}
var tabIds = [];
var newText = ['<font color="lime">Production</font>', '<font color="#7f7fff">Territory</font>', '<font color="fuschia">Policies</font>', '<font color="pink">Traits</font>', '<font color="#bbbbff">Research</font>', '<font color="yellow">Settings</font>', '<font color="yellow">Update log (Vanilla)</font>', '<font color="yellow">Legacy</font>', '<font color="orange">Magix</font>'];
for (i in G.tabs) {
tabIds[i] = G.tabs[i].id;
G.tabs[i].name = newText[i];
}
var tabL = G.tabs.length;
if (tabIds.indexOf('Magix') == -1)
G.tabs[tabL] = { name: '<font color="orange">Magix</font>', showMap: false, id: 'Magix', popup: true, addClass: 'right', desc: 'Options and info about the Magix mod.' };
G.buildTabs();
}
/*==========================
Saveload
==========================*/
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.releaseNumber).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() + ';' +
parseInt(G.influenceTraitRemovalCooldown).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 += G.getSafeName('island') + ';';
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 += parseInt(G.traitsOwned[i].trait.yearOfObtainment).toString() + ';'; //we need to make temporality of the traits work as it should
}
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 += '|';
for (var i = 0; i < len; i++) {
var me = G.chooseBox[i];
str += me.cooldown + ';';
}
// storage object
str += '$' + JSON.stringify(G.storageObject).replaceAll('"', '&QOT') + (G.PARTY ? '$' : '')
str += '|';
//console.log('SAVE');
//console.log(str);
str = escape(str);
str = b64EncodeUnicode(str);
//console.log(Math.ceil(byteCount(str)/1000)+'kb');
if (!toStr) {
localStorage.setItem(G.saveTo, str);
G.middleText('- Game saved -');
//console.log('Game saved successfully.');
}
else return str;
}
G.Load = function (doneLoading) {
document.title = "NeverEnding Legacy"
G.middleText('<p id="loading">Loading save...</p>', "slow");
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 != '') {
var oldStorage = G.storageObject;
try {
G.storageObject = unescape(b64DecodeUnicode(local)).match(/\$\{.+?\}/);
if (G.storageObject) {
G.storageObject = G.storageObject[G.storageObject.length - 1];
if (G.storageObject) {
G.storageObject = JSON.parse(G.storageObject.slice(1).replaceAll('&QOT', '"'));
for (var i = 0; i < conflictingStorageObjects.length; i++) {
var key = conflictingStorageObjects[i]; // over here we compare storage object data and try to detect conflicts
var newItem = G.storageObject[key];
if (oldStorage[key] !== newItem) {
G.dialogue.popup(function (div) {
return '<div style="padding:16px;">Are you sure you want to load this save?<br>Your previous save will be wiped, as there is a storage conflict that requires a reload to fix.<br><br>' + G.button({
text: 'Yes', onclick: function () {
try {
localStorage.setItem(G.saveTo, local);
location.reload();
} catch (e) {
throw TypeError("The game failed to store the data locally.");
}
}
}) + G.button({
text: 'No', onclick: function () {
G.dialogue.close();
}
}) + '</div>';
});
return false;
}
}
} else {
G.storageObject = {};
}
} else {
G.storageObject = {};
}
} catch (e) {
console.warn("Storage data could not be obtained.");
G.storageObject = oldStorage;
}
G.Reset();
G.resetSettings();
//take care of strings first
G.stringsLoadedN = 0;
G.stringsLoaded = [];
str = str.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.releaseNumber = parseFloat(spl[i++]);
if (G.releaseNumber > 1000) {
G.releaseNumber = 54; // assume it's NOT the newest version
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++]);
G.influenceTraitRemovalCooldown = 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');
if (G.releaseNumber > 54)
G.setSafeName('island', G.readLoadedString(spl[ss++]), 'Plain Island');
//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] != '') {
var spl2 = spl[i].split(',');
G.gainTrait(G.know[parseInt(spl2[0])]);
if (G.releaseNumber > 54) G.know[parseInt(spl2[0])].yearOfObtainment = parseFloat(spl2[1]);
}
}
//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++) {
var me = G.unitsOwned[i];
if (prev && me.unit.id == prev.unit.id) me.splitOf = prev;
else prev = me;
}
prev = 0;
//chooseboxes
var spl = str[s++].split(';');
var len = spl.length;
for (var i = len - 1; i >= 0; i--) {
if (spl[i] != '') {
G.chooseBox[i].choices = [];
var spl2 = spl[i].split(',');
for (var ii in spl2) {
if (ii == 0) G.chooseBox[i].roll = parseFloat(spl2[ii]);
else G.chooseBox[i].choices[ii - 1] = G.know[parseInt(spl2[ii])];
}
}
}
var tSpl = str[s++].split('$')
var spl = tSpl[0].split(';');
var num = parseInt(spl[0]);
G.getDict('research box').cooldown = isFinite(num) ? num : 0;
if (tSpl.length >= 3) G.PARTY = 1; // new feature added: there will be an added $ sign if G.PARTY is true, and there is a button to toggle this in the debug menu because why not (this is right after G.storageObject data but that is pre-calculated in an attempt to avoid conflicting data issues like civ mismatches)
G.runUnitReqs();
G.runPolicyReqs();
G.applyAchievEffects('load');
G.updateEverything();
G.createTopInterface();
G.createDebugMenu();
if (G.tabs[G.settingsByName['tab'].value]) G.setTab(G.tabs[G.settingsByName['tab'].value]);
G.setSetting('forcePaused', 0);
l('blackBackground').style.opacity = 0;
if (timeOffline >= 1) G.middleText('- Welcome back -<br><small>You accumulated ' + B(timeOffline) + ' fast ticks while you were away.</small>', true);
G.rememberAchievs = true;
G.animIntro = true;
G.introDur = G.fps * 1;
G.doFunc('game loaded');
G.Logic(true);//force a tick (solves some issues with display updates; this however means loading a paused game, saving and reloading will make a single day go by every time, which isn't ideal)
G.releaseNumber = 55; //this must be assigned here or else we will have issues
tabs();
console.log('Game loaded successfully (release ' + G.releaseNumber + ').');
return true;
}
return false;
}
// Remove the empty tick functions for a little performance boost (how much? not sure...in particular, considering the amount of problems this has/may cause)
G.Res = function (obj) {
this.type = 'res';
this.amount = 0;
this.used = 0;//only used by some special resources (houses occupied, workers busy...); will only be handled and saved if the resource has .displayUsed=true
this.mult = 1;//gain multiplier; all gains of this resource are multiplied by this; updated every tick
this.displayedAmount = 0;//used to tick up the displayed number
this.displayedUsedAmount = 0;//used to tick up the displayed number
this.startWith = 0;
this.gained = 0;//gained this tick
this.lost = 0;//lost this tick
this.gainedBy = [];//filled by unit names and other processes that create this resource; emptied after every tick
this.lostBy = [];//filled by unit names and other processes that use up this resource; emptied after every tick
this.meta = false;//does this resource have subparts?
this.partOf = false;//is this resource a subpart of another resource? (a resource cannot be a subresource AND have subresources of its own)
this.subRes = [];//subresources if this is a meta-resource; handled automatically
this.getMult = function () { return 1; };
this.getDisplayAmount = function () {
if (this.displayUsed) return B(this.displayedUsedAmount) + '<wbr>/' + B(this.displayedAmount);
else return B(this.displayedAmount);
};
this.category = '';
this.icon = [0, 0];
this.visible = false;//a resource will only be displayed if you've had some of the resource at some point (you can set .visible to force it to start visible; you can also set .hidden to override .visible)
for (var i in obj) this[i] = obj[i];
this.id = G.res.length;
if (!this.displayName) this.displayName = cap(this.name);
G.res.push(this);
G.resByName[this.name] = this;
G.setDict(this.name, this);
this.mod = G.context;
}
G.NewGameConfirm = function () {
//the player has selected a starting location; launch the game proper
//G.Reset();
G.sequence = 'main';
G.T = 0;
G.rememberAchievs = true;
for (var i in G.savedAchievs) {
//reload achievements
if (G.modsByName[i] && G.modsByName[i].achievs) {
for (var ii in G.savedAchievs[i]) {
if (G.modsByName[i].achievs[ii]) G.modsByName[i].achievs[ii].won = G.savedAchievs[i][ii];
}
}
}
//init everything
G.createMaps();
for (var i in G.res) {
G.res[i].amount = G.res[i].startWith;
}
for (var i in G.tech) {
if (G.tech[i].startWith) G.gainTech(G.tech[i]);
}
for (var i in G.trait) {
if (G.trait[i].startWith) G.gainTrait(G.trait[i]);
}
for (var i in G.policy) {
if (G.policy[i].startWith) G.gainPolicy(G.policy[i]);
}
for (var i in G.res) {
var item = G.res[i]
if (item.tick) item.tick(item, G.tick);
}
G.runUnitReqs();
G.runPolicyReqs();
G.applyAchievEffects('new');
G.updateEverything();
G.createTopInterface();
G.createDebugMenu();
for (var i in G.unit) {
if (G.unit[i].startWith) { G.buyUnitByName(G.unit[i].name, G.unit[i].startWith); }
}
l('blackBackground').style.opacity = 0;
G.setSetting('forcePaused', 0);
G.setSetting('paused', 0);
G.setSetting('fast', 0);
G.animIntro = true;
G.introDur = G.fps * 3;
G.doFunc('new game');
G.Message({
type: 'important', text: 'If this is your first time playing, you may want to consult some quick ' + G.button({
text: 'Getting started', tooltip: 'Read a few tips on how to make it past the first stages of the game.', onclick: function () {
G.dialogue.popup(function (div) {
return '<div style="width:480px;min-height:320px;height:75%;">' +
'<div class="fancyText title">A few tips on how to not die horribly:</div>' +
'<div class="fancyText bitBiggerText scrollBox underTitle" style="text-align:left;padding:16px;">' +
'<div class="bulleted">early on, focus most of your workers on food gathering</div>' +
'<div class="bulleted">your people will want to eat and drink a lot, so give them as much food as you can once you can change that</div>' +
'<div class="bulleted">assign a few spare workers as dreamers, in order to get some Insight which you can use to research technologies</div>' +
'<div class="bulleted">wanderers might not seem that useful, but they can acquire some more useful land for you!</div>' +
'<div class="bulleted">check the territory tab and click your starting location; if you\'ve got very few sources of food or water, you might want to restart the game</div>' +
'<div class="bulleted">don\'t bother researching fishing or hunting if none of your tiles have animals or fish!</div>' +
'<div class="bulleted">enabling elder/child work policies can be useful if you need extra workers, but may prove detrimental to your people\'s health</div>' +
'<div class="bulleted">if things get too hectic, you can always pause the game and take your time</div>' +
'<div class="bulleted">you don\'t have to worry about meeting other civilizations</div>' +
'<div class="bulleted">sometimes things just go wrong; don\'t lose hope and start over when needed!</div>' +
'</div>' +
'</div><div class="buttonBox">' +
G.dialogue.getCloseButton('Got it!') +
'</div></div>';
});
}
}) + ' tips.'
});
}
G.logic['res'] = function () {
//update visibility
var len = G.res.length;
for (var i = 0; i < len; i++) {
var res = G.res[i];
res.gainedBy = [];
res.lostBy = [];
res.gained = 0;
res.lost = 0;
}
for (var i = 0; i < len; i++) {
var realRes = G.res[i];
var res = G.resolveRes(realRes);
if (res != realRes) {
if (realRes.tick) realRes.tick(realRes, G.tick);
if (realRes.hidden) realRes.visible = false;
else if (res.amount != 0) realRes.visible = true;
}
else {
if (res.tick) res.tick(res, G.tick);
res.mult = res.getMult();
if (res.hidden) res.visible = false;
else if (res.amount != 0) res.visible = true;
}
}
//resolve meta-resources with sub-resources
var len = G.metaRes.length;
for (var i = 0; i < len; i++) {
var me = G.resolveRes(G.metaRes[i]); me.amount = 0;
}
var len = G.subRes.length;
for (var i = 0; i < len; i++) {
var me = G.subRes[i];
var meta = G.getRes(me.partOf);
meta.amount += me.amount;
meta.gained += me.gained;
meta.lost += me.lost;
for (var ii in me.gainedBy) { if (!meta.gainedBy.includes(me.gainedBy[ii])) meta.gainedBy.push(me.gainedBy[ii]); }
for (var ii in me.lostBy) { if (!meta.lostBy.includes(me.lostBy[ii])) meta.lostBy.push(me.lostBy[ii]); }
}
}
//change page layout to fit width (for Magix, the defaults are TOO LOW, sadly)
G.stabilizeResize = function () {
G.resizing = false;
l('sections').style.marginTop = ((G.w < 550) + (G.w < 590) + (G.w < 645) + (G.w < 755)) * 20 + 'px'
l('game').style.bottom = G.h < 600 ? 0 : null;
l('fpsGraph').style.display = G.h < 600 ? 'none' : 'block';
if (G.w * G.h < 200000 || G.w < 625) { document.body.classList.add('halfSize'); } else { document.body.classList.remove('halfSize'); }
if (G.w < 950) { G.wrapl.classList.remove('narrow'); G.wrapl.classList.add('narrower'); }
else if (G.w < 1152) { 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.CreateData = function () {
//cleanse all data first
G.dict = [];
G.res = [];
G.resByName = [];
G.resCategories = [];
G.unit = [];
G.unitByName = [];
G.unitCategories = [];
G.policy = [];
G.policyByName = [];
G.policyCategories = [];
G.know = [];
G.knowByName = [];
G.knowCategories = [];
G.tech = [];
G.techByName = [];
G.techByTier = {};
G.trait = [];
G.traitByName = [];
G.traitByTier = {};
G.goods = [];
G.goodsByName = [];
G.land = [];
G.landByName = [];
G.achiev = [];
G.achievByName = [];
G.achievByTier = [];
G.legacyBonuses = [];
G.chooseBox = [];
G.contextNames = [];
G.contextVisibility = [];
G.funcs = [];//keyed array; store functions tied to hard-coded events in here
G.props = [];//keyed array; store anything you want in here
G.context = 0;
G.sheets = {};//icon sheets added by mods
//create new data
for (var i in G.mods) {
G.context = G.mods[i];
if (G.mods[i].sheets) {
for (var ii in G.mods[i].sheets) {
G.sheets[ii] = G.mods[i].sheets[ii];
}
}
G.mods[i].func();
}
G.context = 0;
//cache some stuff
G.cacheMetaResources();
var newBonuses = {};
for (var i in G.legacyBonuses) {
var me = G.legacyBonuses[i];
newBonuses[me.id] = me;
}
G.legacyBonuses = newBonuses;
for (var i in G.unit) {
G.unit[i].modesById = [];
var index = 0;
for (var ii in G.unit[i].modes) {
var mode = G.unit[i].modes[ii];
G.unit[i].modesById[index] = mode;
mode.id = ii;
mode.num = index;
mode.use = mode.use || {};
index++;
}
}
for (var i in G.policy) {
G.policy[i].modesById = [];
var index = 0;
for (var ii in G.policy[i].modes) {
var mode = G.policy[i].modes[ii];
G.policy[i].modesById[index] = mode;
mode.id = ii;
mode.num = index;
index++;
}
}
for (var i in G.know) {
var me = G.know[i];
me.leadsTo = [];
me.precededBy = [];
}
for (var i in G.know) {
var me = G.know[i];
for (var ii in me.req) {
var req = G.getDict(ii);
if (me.req[ii] && req && (req.type == 'tech' || req.type == 'trait')) {
G.getKnow(ii).leadsTo.push(me);
me.precededBy.push(G.getKnow(ii));
}
if (!req) console.log('ERROR: ' + me.name + ' has "' + ii + '" as a requirement, but no such thing was found.');
}
}
//create tiers
var getTier = function (me) {
var tier = 0;
for (var i in me.req) {
var req = G.getDict(i);
if (me.req[i] && req && req.type == me.type) {
tier = Math.max(tier, req.tier || Math.max(getTier(req)));
}
}
me.tier = tier + 1;
return me.tier;
}
for (var i in G.know) {
var me = G.know[i];
getTier(me);
if (me.type == 'tech') {
if (!G.techByTier[me.tier]) G.techByTier[me.tier] = [];
G.techByTier[me.tier].push(me);
}
else if (me.type == 'trait') {
if (!G.traitByTier[me.tier]) G.traitByTier[me.tier] = [];
G.traitByTier[me.tier].push(me);
}
}
//compute combined research costs
if (true) {
G.techByTier = {};
G.traitByTier = {};
for (var i in G.know) {
var me = G.know[i]; me.tier = 0;
}
var getAncestors = function (me) {
var out = [me];
for (var i in me.req) {
var req = G.getDict(i);
if (me.req[i] && req && req.type == me.type) {
out = out.concat(getAncestors(req));
}
}
return out;
}
for (var i in G.know) {
var me = G.know[i];
me.ancestors = getAncestors(me);
me.ancestors = me.ancestors.filter(function (elem, index, self) { return index == self.indexOf(elem); })//remove duplicates
for (var ii in me.ancestors) {
for (var iii in me.ancestors[ii].cost) {
me.tier += me.ancestors[ii].cost[iii];
}
}
}
for (var i in G.know) {
var me = G.know[i];
if (me.type == 'tech') {
if (!G.techByTier[me.tier]) G.techByTier[me.tier] = [];
G.techByTier[me.tier].push(me);
}
else if (me.type == 'trait') {
if (!G.traitByTier[me.tier]) G.traitByTier[me.tier] = [];
G.traitByTier[me.tier].push(me);
}
}
}
for (var i in G.achiev) {
var me = G.achiev[i];
if (me.fromUnit) {
var unit = G.getUnit(me.fromUnit);
if (!me.desc) me.desc = unit.desc;
if (me.icon[0] == 0 && me.icon[1] == 0) me.icon = unit.icon;
if (!me.wideIcon && unit.wideIcon) me.wideIcon = unit.wideIcon;
}
}
}
G.getDataAmounts = function () {
return 'Data created.\n' +
' - ' + G.res.length + ' resources\n' +
' - ' + G.unit.length + ' units\n' +
' - ' + G.tech.length + ' technologies\n' +
' - ' + G.trait.length + ' cultural traits\n' +
' - ' + G.policy.length + ' policies\n' +
' - ' + G.land.length + ' terrains\n' +
' - ' + G.goods.length + ' terrain goods\n' +
' - ' + G.achiev.length + ' achievements\n' +
''
}
if (getObj("civ") === null) setObj("civ", 0);
var magix2Link = magixURL2 + 'magix2.png?v=2.2' // Version 2.2: 63 sprites
G.AddData({
name: 'MagixUtils',
author: 'pelletsstarPL',
desc: 'Some mechanics that are in Magix code are contained within this mod. Required to play Magix.',
engineVersion: 1,
sheets: { 'magixmod': magixURL + 'magixmod.png', 'magix2': magix2Link, 'seasonal': magixURL + 'seasonalMagix.png', 'c2': magixURL + 'CiV2IconSheet.png' },//just for achievs
func: function () {
///FOR SEASONAL CONTENT. IK COPIED FROM CC, BUT IT WILL HELP ME. ALSO THAT IS HOW MODDING LOOKS LIKE THAT xD
var yer = new Date();
var leap = (((yer % 4 == 0) && (yer % 100 != 0)) || (yer % 400 == 0)) ? 1 : 0;
var day = Math.floor((new Date() - new Date(new Date().getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
var easterDay = function (Y) { var C = Math.floor(Y / 100); var N = Y - 19 * Math.floor(Y / 19); var K = Math.floor((C - 17) / 25); var I = C - Math.floor(C / 4) - Math.floor((C - K) / 3) + 19 * N + 15; I = I - 30 * Math.floor((I / 30)); I = I - Math.floor(I / 28) * (1 - Math.floor(I / 28) * Math.floor(29 / (I + 1)) * Math.floor((21 - N) / 11)); var J = Y + Math.floor(Y / 4) + I + 2 - C + Math.floor(C / 4); J = J - 7 * Math.floor(J / 7); var L = I - J; var M = 3 + Math.floor((L + 40) / 44); var D = L + 28 - 31 * Math.floor(M / 4); return new Date(Y, M - 1, D); }(yer);
easterDay = Math.floor((easterDay - new Date(easterDay.getFullYear(), 0, 0)) / (1000 * 60 * 60 * 24));
///
// Add more numbers
var numberFormatters =
[
function rawFormatter(value) { return value % 1 ? Math.floor(value * 1000) / 1000 : value },
formatEveryThirdPower([
' thousand',
' million',
' billion',
' trillion',
' quadrillion',
' quintillion',
' sextillion',
' septillion',
' octillion',
' nonillion',