-
Notifications
You must be signed in to change notification settings - Fork 10
/
game.js
executable file
·7030 lines (6287 loc) · 310 KB
/
game.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
/*
Ethereal Farm
Copyright (C) 2020-2024 Lode Vandevenne
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
var state = undefined;
// values set before initUIGlobal, or undo's tooltip may show 'NaN' for these times
var minUndoTime = 10;
var maxUndoTime = 3600;
initUIGlobal();
var savegame_recovery_situation = false; // if true, makes it less likely to autosave, to ensure local storage preserves a valid older save
var last_daily_save = 0; // this gets reset on refresh but that is ok
function saveDailyCycle(e) {
var time = util.getTime();
if(time > last_daily_save + 24 * 3600) {
var day_cycle = (Math.floor(time / (24 * 3600)) % 2);
if(day_cycle == 0) util.setLocalStorage(e, localstorageName_daily1);
if(day_cycle == 1) util.setLocalStorage(e, localstorageName_daily2);
last_daily_save = time;
}
}
// saves to local storage
function saveNow(onsuccess) {
save(state, function(s) {
util.setLocalStorage(s, localstorageName);
if(!window_unloading) saveDailyCycle(s);
if(onsuccess) onsuccess(s);
});
}
function loadFromLocalStorage(onsuccess, onfail) {
var e = util.getLocalStorage(localstorageName);
if(!e) {
e = util.getLocalStorage(localstorageName_undo);
if(e) console.log('local storage was corrupted, loaded from last undo save');
}
if(!e) {
if(onfail) onfail(undefined); // there was no save in local storage
return;
}
var prev_version = version;
if(e.length > 4 && isBase64(e)) {
prev_version = 4096 * fromBase64[e[2]] + 64 * fromBase64[e[3]] + fromBase64[e[4]];
// NOTE: if there is a bug, and prev_version is a bad version with bug, then do NOT overwrite if prev_version is that bad one
if(prev_version < version) {
util.setLocalStorage(e, localstorageName_prev_version);
}
}
load(e, function(state) {
initUI();
update();
onsuccess(state);
// save a "last successful load" save for recovery purposes, if the game has any substantial time duration (at least 3 days)
var save_last_known_good = true;
var duration = state.g_numticks;
var lastsuccess = util.getLocalStorage(localstorageName_success);
// only overwrite existing last known save if it has at least as much ticks (indicated in character 6 of the save, "ticks_code")
if(!lastsuccess || !lastsuccess.length || fromBase64[e[6]] >= fromBase64[lastsuccess[6]]) {
util.setLocalStorage(e, localstorageName_success);
}
}, function(state) {
onfail(state);
if(e.length > 22 && isBase64(e) && e[0] == 'E' && e[1] == 'F') {
// save a recovery save in case something went wrong, but only if there isn't already one. Only some specific later actions like importing a save and hard reset will clear this
var has_recovery = !!util.getLocalStorage(localstorageName_recover);
if(!has_recovery) util.setLocalStorage(e, localstorageName_recover);
var saves = getRecoverySaves();
for(var i = 0; i < saves.length; i++) {
showMessage(saves[i][0] + ' : ' + saves[i][1], C_ERROR, 0, 0);
}
if(saves.length == 0) {
showMessage('current: ' + e, C_ERROR, 0, 0);
}
var text = loadlocalstoragefailedmessage;
if(state && state.error_reason == 4) text += ' ' + loadfailreason_format;
if(state && state.error_reason == 5) text += ' ' + loadfailreason_decompression;
if(state && state.error_reason == 6) text += ' ' + loadfailreason_checksum;
if(state && state.error_reason == 7) text += ' ' + loadfailreason_toonew;
if(state && state.error_reason == 8) text += ' ' + loadfailreason_tooold;
showMessage(text, C_ERROR, 0, 0);
showSavegameRecoveryDialog(true);
savegame_recovery_situation = true;
}
});
}
// set the state back to normal after state.amberkeepseason. Go to next season and make it take 24 hours, if needed.
// also refunds amber if needed
// returns true if season changed, false if it stayed the same
function restoreAmberSeason() {
if(!state.amberkeepseason) {
state.amberkeepseasonused = false; // this should not be needed, this should not be set when amberkeepseason is not active, but done just to be sure...
return false;
}
if(!state.amberkeepseasonused) {
showMessage('Keep season did not yet activate, refunding amber', C_UNDO, 872341239);
state.res.amber = state.res.amber.add(ambercost_keep_season);
state.g_numamberkeeprefunds++;
state.amberkeepseason = false;
return false;
}
var season = getPureSeason(); // must be called before resetting state.amberkeepseasonused below
var next_season = (season + 1) & 3;
state.amberkeepseason = false;
state.amberkeepseasonused = false;
// getSeasonTime(time) has following implementation (indirectly): return time - state.g_starttime - state.g_pausetime - state.seasonshift + getSeasonCorrection();
// this is then the part of a 4-day cycle starting at spring (season 0)
// so adjust state.seasonshift now such that it has exactly the next season with 24h left
state.seasoncorrection = 0; // disable the need to care about getSeasonCorrection(), it's not needed when we'll update the season time ourselves
var seasontime = getSeasonTime(state.time);
var seasontime2 = seasontime + state.seasonshift;
var rem = seasontime2 % (4 * 24 * 3600);
//var shift = 4 * 24 * 3600 - rem;
var shift = rem;
//var shift = rem;
shift -= next_season * 24 * 3600;
shift -= 1; // ensure no numerical issues if just at boundary
state.seasonshift = shift;
return true;
}
// Why there are so many recovery saves: because different systems may break in different ways, hopefully at least one still has a valid recent enough save but not too recent to have the breakage
// This mostly protects against loss of progress due to accidental bugs of new game versions that break old saves. This cannot recover anything if local storage was deleted.
function getRecoverySaves() {
var result = [];
var prev = util.getLocalStorage(localstorageName_prev_version);
if(prev) {
result.push(['last from older game version', prev]);
}
var day;
day = util.getLocalStorage(localstorageName_daily1);
if(day) {
result.push(['daily cycle A', day]);
}
day = util.getLocalStorage(localstorageName_daily2);
if(day) {
result.push(['daily cycle B', day]);
}
var undo = util.getLocalStorage(localstorageName_undo);
if(undo) {
result.push(['last save for undo feature', undo]);
}
var lastsuccess = util.getLocalStorage(localstorageName_success);
if(lastsuccess) {
result.push(['last known good', lastsuccess]);
}
var recovery = util.getLocalStorage(localstorageName_recover);
if(recovery) {
result.push(['last known attempted', recovery]);
}
var current = util.getLocalStorage(localstorageName);
if(lastsuccess) {
result.push(['last', current]);
}
return result;
}
// the ones that should be reset when loading a save
function resetGlobalStateVars(opt_state) {
savegame_recovery_situation = false;
prefield = [];
prev_season = undefined;
prev_season2 = undefined;
prev_season_gain = undefined;
large_time_delta = false;
heavy_computing = false;
large_time_delta_time = 0;
large_time_delta_res = opt_state ? Res(opt_state.res) : Res();
global_season_changes = 0;
global_tree_levelups = 0;
helpNeverAgainLocal = {};
prevGoal = GOAL_NONE;
prevGoalSubCode = 0;
actually_updated = false;
gain = Res();
showingConfigureAutoActionDialog = false;
showingConfigureAutoChoiceDialog = false;
aboutButtonCanvas_lastHoliday = -1;
}
function hardReset() {
initMessageUI();
showMessage('Hard reset performed, everything reset', C_META, 0, 0);
util.clearLocalStorage(localstorageName);
util.clearLocalStorage(localstorageName_recover);
util.clearLocalStorage(localstorageName_success);
util.clearLocalStorage(localstorageName_prev_version);
util.clearLocalStorage(localstorageName_undo);
util.clearLocalStorage(localstorageName_daily1);
util.clearLocalStorage(localstorageName_daily2);
// no longer supported, but cleared in case old game version created it
util.clearLocalStorage(localstorageName + '_manual');
util.clearLocalStorage(localstorageName + '_transcend');
util.clearLocalStorage(localstorageName + '_prev_version2');
util.clearLocalStorage(localstorageName + '_daily3');
postload(createInitialState());
removeChallengeChip();
removeMedalChip();
removeHelpChip();
undoSave = '';
lastUndoSaveTime = 0;
lastUndoKeepLong = false;
prev_store_undo = false;
resetGlobalStateVars();
initUI();
update();
}
// use at the start of challenges that only have some specific of their own upgrades, ...
function lockAllUpgrades() {
for(var i = 0; i < registered_upgrades.length; i++) {
var u = state.upgrades[registered_upgrades[i]];
u.unlocked = false;
}
}
// unlock any templates that are available, or lock them if not
function unlockTemplates() {
var wither_incomplete = (state.challenge == challenge_wither) && state.challenges[challenge_wither].completed < 2;
if(automatonUnlocked() && state.challenge != challenge_nodelete && !wither_incomplete && state.challenge != challenge_bees && basicChallenge() != 2) {
state.crops[watercress_template].unlocked = true;
state.crops[berry_template].unlocked = true;
state.crops[mush_template].unlocked = true;
state.crops[flower_template].unlocked = true;
state.crops[nettle_template].unlocked = true;
if(state.challenges[challenge_bees].completed) state.crops[bee_template].unlocked = true;
var no_twigs_challenge = !!state.challenge && !challenges[state.challenge].allowstwigs;
var no_nuts_challenge = !!state.challenge && !challenges[state.challenge].allowsnuts;
if(state.upgrades2[upgrade2_mistletoe].count && !no_twigs_challenge) state.crops[mistletoe_template].unlocked = true;
if(state.challenge == challenge_bees) {
state.crops[bee_template].unlocked = false;
state.crops[nettle_template].unlocked = false;
}
if(!no_nuts_challenge) state.crops[nut_template].unlocked = haveSquirrel();
// the pumpkin_0 unlocked check there is so that if the holiday event ends, the blueprint is still available throughout the current run where pumpkin_0 was already unlocked, so auto-blueprints still work. This because unlockTemplates is called every frame so would disable the template otherwise.
state.crops[pumpkin_template].unlocked = pumpkinUnlocked() || state.crops[pumpkin_0].unlocked;
} else {
// templates disabled in bee challenge because: no templates available for some challenge-specific crops, could be confusing. note also that the beehive template is not for the bee challenge's special beehive.
// templates disabled in nodelete challenge because: not a strong reason actually and the code to allow deleting templates in nodelete challenge is even implemented, but by default templates cause automaton to upgrade them, and that would cause nodelete challenge to fail early since the cropss ey cannot be upgraded to a better type
// templates disabled in wither challenge in the beginning because: this challenge should be hard like that on purpose, plus all its corps wither and leave behind template-less field cells all the time anyway
state.crops[watercress_template].unlocked = false;
state.crops[berry_template].unlocked = false;
state.crops[mush_template].unlocked = false;
state.crops[flower_template].unlocked = false;
state.crops[nettle_template].unlocked = false;
state.crops[bee_template].unlocked = false;
state.crops[mistletoe_template].unlocked = false;
state.crops[nut_template].unlocked = false;
state.crops[pumpkin_template].unlocked = false;
}
if(state.crops2[automaton2_0].unlocked) {
state.crops2[berry2_template].unlocked = true;
state.crops2[mush2_template].unlocked = true;
state.crops2[flower2_template].unlocked = true;
state.crops2[lotus2_template].unlocked = true;
state.crops2[fern2_template].unlocked = true;
state.crops2[nettle2_template].unlocked = (state.crops2[nettle2_0].unlocked);
state.crops2[automaton2_template].unlocked = (state.crops2[automaton2_0].unlocked);
state.crops2[squirrel2_template].unlocked = (state.crops2[squirrel2_0].unlocked);
state.crops2[bee2_template].unlocked = (state.crops2[bee2_0].unlocked);
state.crops2[mistletoe2_template].unlocked = (state.crops2[mistletoe2_0].unlocked);
state.crops2[brassica2_template].unlocked = (state.crops2[brassica2_0].unlocked);
} else {
state.crops2[berry2_template].unlocked = false;
state.crops2[mush2_template].unlocked = false;
state.crops2[flower2_template].unlocked = false;
state.crops2[lotus2_template].unlocked = false;
state.crops2[fern2_template].unlocked = false;
state.crops2[nettle2_template].unlocked = false;
state.crops2[automaton2_template].unlocked = false;
state.crops2[squirrel2_template].unlocked = false;
state.crops2[bee2_template].unlocked = false;
state.crops2[mistletoe2_template].unlocked = false;
state.crops2[brassica2_template].unlocked = false;
}
}
function getRocksChallengeTimeSeed() {
return Math.floor(util.getTime() / (3600 * 3));
}
function getRocksChallengeTimeTilNextSeed() {
return 3600 * 3 - (util.getTime() % (3600 * 3));
}
// set up everything for a challenge after softreset
function startChallenge(challenge_id) {
if(!challenge_id) return; // nothing to do
if(challenge_id == challenge_bees) {
lockAllUpgrades();
state.crops[challengecrop_0].unlocked = true;
state.crops[challengecrop_1].unlocked = true;
state.crops[challengecrop_2].unlocked = true;
state.crops[challengeflower_0].unlocked = true;
state.crops[mush_0].unlocked = true;
state.crops[berry_0].unlocked = true;
state.upgrades[challengecropmul_0].unlocked = true;
state.upgrades[challengecropmul_1].unlocked = true;
state.upgrades[challengecropmul_2].unlocked = true;
// add the watercress upgrade as well so one isn't forced to refresh it every minute during this challenge
state.upgrades[brassicamul_0].unlocked = true;
}
if(challenge_id == challenge_towerdefense) {
state.crops[challengestatue_0].unlocked = true;
state.crops[challengestatue_1].unlocked = true;
state.crops[challengestatue_2].unlocked = true;
state.crops[challengestatue_3].unlocked = true;
state.crops[challengestatue_4].unlocked = true;
state.crops[challengestatue_5].unlocked = true;
state.crops[challengestatue_0_template].unlocked = true;
state.crops[challengestatue_1_template].unlocked = true;
state.crops[challengestatue_2_template].unlocked = true;
state.crops[challengestatue_3_template].unlocked = true;
state.crops[challengestatue_4_template].unlocked = true;
state.crops[challengestatue_5_template].unlocked = true;
resetTD();
}
if(challenge_id == challenge_rocks || challenge_id == challenge_thistle) {
// use a fixed seed for the random, which changes every 3 hours, and is the same for all players (depends only on the time)
// changing the seed only every 4 hours ensures you can't quickly restart the challenge to find a good pattern
// making it the same for everyone makes it fair
var timeseed = getRocksChallengeTimeSeed();
var seed;
if(challenge_id == challenge_rocks) {
seed = xor48(timeseed, 0x726f636b73); // ascii for "rocks"
} else {
seed = xor48(timeseed, 0x5555555555);
}
var num_rocks = Math.floor(state.numw * state.numh / 3);
var array = [];
for(var y = 0; y < state.numh; y++) {
for(var x = 0; x < state.numw; x++) {
var f = state.field[y][x];
if(f.index != 0) continue;
array.push([x, y]);
}
}
for(var i = 0; i < num_rocks; i++) {
if(array.length == 0) break;
var roll = getRandomRoll(seed);
seed = roll[0];
var r = Math.floor(roll[1] * array.length);
var x = array[r][0];
var y = array[r][1];
array.splice(r, 1);
if(challenge_id == challenge_rocks) {
state.field[y][x].index = FIELD_ROCK;
} else {
state.field[y][x].index = (CROPINDEX + nettle_1);
state.field[y][x].growth = 1;
}
}
}
if(challenge_id == challenge_rockier) {
// similar to challenge_rocks, but more rocks
// here the layouts rotate around each time you complete the challenge
var layout_index = state.challenges[challenge_rockier].num_completed % rockier_layouts.length;
var layout = rockier_layouts[layout_index];
var array = [];
for(var y = 0; y < state.numh; y++) {
for(var x = 0; x < state.numw; x++) {
var f = state.field[y][x];
if(f.index != 0) continue;
f.index = FIELD_ROCK;
}
}
var treex0 = Math.floor((state.numw - 1) / 2);
var treey0 = Math.floor(state.numh / 2);
var x0 = treex0 - 2;
var y0 = treey0 - 2;
for(var y = 0; y < 5; y++) {
for(var x = 0; x < 5; x++) {
var c = layout[y * 5 + x];
if(c != '1') continue;
var f = state.field[y0 + y][x0 + x];
if(f.index != FIELD_ROCK) continue;
f.index = 0;
}
}
}
if(challenge_id == challenge_poisonivy) {
for(var y = 0; y < state.numh; y++) {
for(var x = 0; x < state.numw; x++) {
if(!(x & 1) || !(y & 1)) continue; // the pattern
var f = state.field[y][x];
if(f.index != 0) continue;
f.index = (CROPINDEX + nettle_2);
}
}
}
if(challenge_id == challenge_blackberry) {
lockAllUpgrades();
state.crops[brassica_0].unlocked = true;
state.crops[mush_0].unlocked = true;
state.crops[berry_0].unlocked = true;
state.crops[flower_0].unlocked = true;
state.crops[mistletoe_0].unlocked = true;
state.crops[nettle_0].unlocked = true;
state.upgrades[brassicamul_0].unlocked = true;
state.upgrades[mushmul_0].unlocked = true;
state.upgrades[berrymul_0].unlocked = true;
state.upgrades[flowermul_0].unlocked = true;
state.upgrades[nettlemul_0].unlocked = true;
if(state.challenges[challenge_bees].completed) {
state.crops[bee_0].unlocked = true;
state.upgrades[beemul_0].unlocked = true;
}
}
if(challenge_id == challenge_towerdefense) {
state.field[0][0].index = FIELD_BURROW;
showRegisteredHelpDialog(44);
var text = 'Welcome to tower defense! Build a maze of crops, press the GO button at the top when ready to start the waves'
showMessage(text, C_TD, 1920341654, undefined, undefined, true);
showTdChip(text)
}
}
// get the field size to have after a reset
function getNewFieldSize() {
if(basicChallenge() == 2) return [5, 5];
var result = [5, 5];
if(state.upgrades2[upgrade2_field9x8].count) {
result = [9, 8];
} else if(state.upgrades2[upgrade2_field8x8].count) {
result = [8, 8];
} else if(state.upgrades2[upgrade2_field7x8].count) {
result = [7, 8];
} else if(state.upgrades2[upgrade2_field7x7].count) {
result = [7, 7];
} else if(state.upgrades2[upgrade2_field7x6].count) {
result = [7, 6];
} else if(state.upgrades2[upgrade2_field6x6].count) {
result = [6, 6];
}
if(state.challenge == challenge_towerdefense) result = [result[0] + 2, result[1] + 2];
return result;
}
function endPreviousRun() {
var res_before = new Res(state.res);
var c2 = state.challenges[state.challenge];
if(state.challenge) {
var c = challenges[state.challenge];
c2.maxlevel = Math.max(state.treelevel, c2.maxlevel);
// even for the "attempt" counter, do not count attempts that don't even level up the tree, those are counted as state.g_numresets_challenge_0 instead
if(state.treelevel) c2.num++;
if(c.cycling) {
var cycle = c.getCurrentCycle();
c2.maxlevels[cycle] = Math.max(state.treelevel, c2.maxlevels[cycle]);
}
if(c.numStages() == 0) {
c2.completed = (c2.num > 0); // it has no stages, but at least consider ending it as being completed
} else if(c.stageCompleted(0)) {
var i = c2.completed;
c2.num_completed++;
// whether a next stage of the challenge completed. Note, you can only complete one stage at the time, even if you immediately reach the target level of the highest stage, you only get 1 stage for now
if(i < c.numStages() && c.stageCompleted(i)) {
if(c.numStages() > 1) {
showMessage('Completed the next stage of the challenge and got reward: ' + c.rewarddescription[i], C_UNLOCK, 38658833);
} else {
showMessage('Completed the challenge and got reward: ' + c.rewarddescription[i], C_UNLOCK, 38658833);
}
c2.completed++;
c.rewardfun[i]();
}
}
if(c.numStages() > 1 && c2.completed >= c.numStages()) {
c2.num_completed2++;
}
}
var resin_no_ferns = getUpcomingResin(); // does not include resin from ferns, infinity symbols, ...
state.p_res_no_ferns = Res();
state.p_res_no_ferns.resin = Num(resin_no_ferns);
var resin = getUpcomingResinIncludingFerns();
var do_fruit = true; // sacrifice the fruits even if not above transcension level (e.g. when resetting a challenge)
// if false, still sets the upcoming resin to 0!
var do_resin = state.treelevel >= min_transcension_level;
if(resin.eqr(0)) do_resin = false;
if(state.challenge && !challenges[state.challenge].allowsresin) do_resin = false;
var twigs = getUpcomingTwigs();
var do_twigs = state.treelevel >= min_transcension_level;
if(twigs.eqr(0)) do_twigs = false;
if(state.challenge && !challenges[state.challenge].allowstwigs) do_twigs = false;
var essence = Num(0);
var message = '';
if(do_fruit) {
essence = getUpcomingFruitEssence();
}
if(state.challenge) {
message += 'Starting new run';
} else {
message += 'Transcended';
}
if(do_resin) {
message += '. Got resin: ' + resin.toString();
}
if(do_twigs) {
message += '. Got twigs: ' + twigs.toString();
}
if(do_fruit) {
if(state.fruit_sacr.length) message += '. Sacrificed ' + state.fruit_sacr.length + ' fruits and got ' + essence.toString();
}
// last run stats of challenge, but also of regular no-challenge run
c2.last_completion_level = state.treelevel;
c2.last_completion_time = state.c_runtime;
c2.last_completion_resin = resin;
c2.last_completion_twigs = twigs;
c2.last_completion_date = util.getTime();
c2.last_completion_total_resin = state.g_res.resin;
c2.last_completion_level2 = state.treelevel2;
c2.last_completion_g_level = state.g_treelevel;
showMessage(message, C_ETHEREAL, 669840411);
if(state.g_numresets == 0) {
showRegisteredHelpDialog(1);
}
state.res.resin.addInPlace(resin);
state.g_res.resin.addInPlace(resin);
state.c_res.resin.addInPlace(resin);
state.g_resin_from_transcends.addInPlace(resin);
state.resin = Num(0); // future resin from next tree
state.fernresin = new Res(); // future resin from next ferns
state.res.twigs.addInPlace(twigs);
state.g_res.twigs.addInPlace(twigs);
state.c_res.twigs.addInPlace(twigs);
state.twigs = Num(0);
state.fruit_recover = [];
// fruits
if(do_fruit) {
state.res.addInPlace(essence);
state.g_res.addInPlace(essence);
state.c_res.addInPlace(essence);
// TODO: maybe only keep the best fruits to avoid irrelevant ones in there
for(var i = 0; i < state.fruit_sacr.length; i++) {
var f = state.fruit_sacr[i];
if(f.justdropped) state.fruit_recover.push(f);
}
state.fruit_sacr = [];
state.fruit_seen = true; // any new fruits are likely sacrificed now, no need to indicate fruit tab in red anymore
}
for(var i = 0; i < state.fruit_sacr.length; i++) state.fruit_sacr[i].justdropped = false;
for(var i = 0; i < state.fruit_stored.length; i++) state.fruit_stored[i].justdropped = false;
for(var i = 0; i < state.fruit_recover.length; i++) state.fruit_recover[i].justdropped = false;
// this one should not include the resin from ferns
var res_no_fernresin = new Res(state.c_res);
res_no_fernresin.resin = resin_no_ferns;
state.g_max_res_earned = Res.max(state.g_max_res_earned, res_no_fernresin);
if(state.treelevel > 0) {
var addStat = function(array, stat) {
array.push(stat);
var maxlen = 50;
if(array.length > maxlen) array.splice(0, array.length - maxlen);
};
addStat(state.reset_stats_level, state.treelevel);
addStat(state.reset_stats_level2, state.treelevel2);
// divided through 300: best precision 5 minutes, and even lower when saved for larger times
addStat(state.reset_stats_time, state.time - state.c_starttime);
addStat(state.reset_stats_total_resin, state.g_res.resin);
addStat(state.reset_stats_resin, resin);
addStat(state.reset_stats_twigs, twigs);
addStat(state.reset_stats_challenge, state.challenge);
addStat(state.reset_stats_season, getSeason());
}
// The previous run stats are to compare regular runs with previous ones, so don't count it in case of a challenge
if(!state.challenge) {
state.p_starttime = state.c_starttime;
state.p_runtime = state.c_runtime;
state.p_numticks = state.c_numticks;
state.p_res = state.c_res;
state.p_max_res = state.c_max_res;
state.p_max_prod = state.c_max_prod;
state.p_numferns = state.c_numferns;
state.p_numplantedbrassica = state.c_numplantedbrassica;
state.p_numplanted = state.c_numplanted;
state.p_numfullgrown = state.c_numfullgrown;
state.p_numunplanted = state.c_numunplanted;
state.p_numupgrades = state.c_numupgrades;
state.p_numupgrades_unlocked = state.c_numupgrades_unlocked;
state.p_numabilities = state.c_numabilities;
state.p_numfruits = state.c_numfruits;
state.p_numfruitupgrades = state.c_numfruitupgrades;
state.p_numautoupgrades = state.c_numautoupgrades;
state.p_numautoplant = state.c_numautoplant;
state.p_numautodelete = state.c_numautodelete;
state.p_numfused = state.c_numfused;
state.p_res_hr_best = state.c_res_hr_best;
state.p_res_hr_at = state.c_res_hr_at;
state.p_res_hr_at_time = state.c_res_hr_at_time;
state.p_pausetime = state.c_pausetime;
state.p_numprestiges = state.c_numprestiges;
state.p_numautoprestiges = state.c_numautoprestiges;
state.p_treelevel = state.treelevel;
}
if(state.challenge == challenge_stormy) {
state.p_lightnings = state.c_lightnings;
}
if(state.challenge == challenge_towerdefense) {
state.p_td_waves = state.c_td_waves;
state.p_td_waves_skipped = state.c_td_waves_skipped;
state.p_td_spawns = state.c_td_spawns;
state.p_td_hits = state.c_td_hits;
state.p_td_kills = state.c_td_kills;
}
var runtime2 = state.time - state.c_starttime;
// this type of statistics, too, is only for regular runs
if(!state.challenge) {
if(state.g_slowestrun == 0) {
state.g_fastestrun = state.c_runtime;
state.g_slowestrun = state.c_runtime;
state.g_fastestrun2 = runtime2;
state.g_slowestrun2 = runtime2;
} else {
state.g_fastestrun = Math.min(state.g_fastestrun, state.c_runtime);
state.g_slowestrun = Math.max(state.g_slowestrun, state.c_runtime);
state.g_fastestrun2 = Math.min(state.g_fastestrun2, runtime2);
state.g_slowestrun2 = Math.max(state.g_slowestrun2, runtime2);
}
}
// this too only for non-challenges, highest tree level of challenge is already stored in the challenes themselves
if(!state.challenge) {
state.g_treelevel = Math.max(state.treelevel, state.g_treelevel);
state.g_p_treelevel = Math.max(state.treelevel, state.g_p_treelevel);
}
if(state.challenge) {
if(state.treelevel) {
state.g_numresets_challenge++;
if(state.treelevel >= 10) state.g_numresets_challenge_10++;
} else {
state.g_numresets_challenge_0++;
}
} else {
state.g_numresets++;
}
// if you had 'hold season' active but the season did not yet change, then this ensures getting the 30 amber back
if(state.amberkeepseason) restoreAmberSeason();
state.automaticTranscendRes.addInPlace(state.res.sub(res_before));
}
function beginNextRun(opt_challenge) {
state.challenge = opt_challenge || 0;
state.challenge_completed = 0;
state.amberprod = false;
state.amber_reset_choices = false;
state.lastEtherealDeleteTime = 0;
state.lastEtherealPlantTime = 0;
// first ethereal crops
state.crops2[berry2_0].unlocked = true;
state.crops2[mush2_0].unlocked = true;
state.crops2[flower2_0].unlocked = true;
state.crops2[fern2_0].unlocked = true;
state.crops2[lotus2_0].unlocked = true;
// todo: remove this? softReset is called during the update() function, that one already manages the time
//state.time = util.getTime();
//state.prevtime = state.time;
// state.c_runtime = util.getTime() - state.c_starttime; // state.c_runtime was computed by incrementing each delta, but this should be numerically more precise
state.c_starttime = state.time;
state.c_runtime = 0;
state.c_numticks = 0;
state.c_res = Res();
state.c_max_res = Res();
state.c_max_prod = Res();
state.c_numferns = 0;
state.c_numplantedbrassica = 0;
state.c_numplanted = 0;
state.c_numfullgrown = 0;
state.c_numunplanted = 0;
state.c_numupgrades = 0;
state.c_numupgrades_unlocked = 0;
state.c_numabilities = 0;
state.c_numfruits = 0;
state.c_numfruitupgrades = 0;
state.c_numautoupgrades = 0;
state.c_numautoplant = 0;
state.c_numautodelete = 0;
state.c_numfused = 0;
state.c_res_hr_best = Res();
state.c_res_hr_at = Res();
state.c_res_hr_at_time = Res();
state.c_pausetime = 0;
state.c_numprestiges = 0;
state.c_numautoprestiges = 0;
state.c_lightnings = 0;
state.c_td_waves = 0;
state.c_td_waves_skipped = 0;
state.c_td_spawns = 0;
state.c_td_hits = 0;
state.c_td_kills = 0;
state.fish_resinmul_weighted = Num(-1);
state.fish_resinmul_last = Num(0);
state.fish_resinmul_time = 0;
state.fish_resinmul_time_shift = 0;
state.fish_twigsmul_weighted = Num(-1);
state.fish_twigsmul_last = Num(0);
state.fish_twigsmul_time = 0;
state.fish_twigsmul_time_shift = 0;
state.infinity_prodboost_weighted = Num(-1);
state.infinity_prodboost_last = Num(0);
state.infinity_prodboost_time = 0;
state.infinity_prodboost_time_shift = 0;
state.infinity_infprod_weighted = Res();
state.infinity_infprod_last = Res();
state.infinity_infprod_time = -Infinity;
state.res.seeds = Num(0);
state.res.spores = Num(0);
var starterResources = getStarterResources();
state.res.addInPlace(starterResources);
state.g_res.addInPlace(starterResources);
state.c_res.addInPlace(starterResources);
var fieldsize = getNewFieldSize();
if(fieldsize[0] != state.numw || fieldsize[1] != state.numh) {
state.numw = fieldsize[0];
state.numh = fieldsize[1];
clearField(state);
initFieldUI();
} else {
clearField(state);
}
for(var y = 0; y < state.numh2; y++) {
for(var x = 0; x < state.numw2; x++) {
state.field2[y][x].justplanted = false;
}
}
state.treelevel = 0;
state.prevleveltime = [0, 0, 0];
state.recentweighedleveltime = [0, 0];
state.recentweighedleveltime_time = 0;
state.fernres = new Res();
state.fern = false;
state.lastFernTime = state.time;
gain = new Res();
state.misttime = 0;
state.suntime = 0;
state.rainbowtime = 0;
//state.lasttreeleveluptime = state.time; // commented out: this is preserved across runs now for amber computation
for(var i = 0; i < registered_crops.length; i++) {
if(!state.crops[registered_crops[i]]) state.crops[registered_crops[i]] = new CropState();
var c2 = state.crops[registered_crops[i]];
c2.unlocked = false;
c2.prestige = 0;
c2.had = 0;
}
state.crops[brassica_0].unlocked = true;
updateAllPrestigeData();
for(var i = 0; i < registered_upgrades.length; i++) {
if(!state.upgrades[registered_upgrades[i]]) state.upgrades[registered_upgrades[i]] = new UpgradeState();
var u2 = state.upgrades[registered_upgrades[i]];
u2.seen = false;
u2.unlocked = false;
u2.count = 0;
}
if(opt_challenge) {
startChallenge(opt_challenge);
}
state.challenge_autoaction_warning = false;
if(state.automaton_autoaction == 2) {
// if it was auto-disabled, enable it again next run
state.automaton_autoaction = 1;
}
if(state.upgrades2[upgrade2_blackberrysecret].count) applyBlackberrySecret();
if(state.upgrades2[upgrade2_blueberrysecret].count) applyBlueberrySecret();
if(state.upgrades2[upgrade2_cranberrysecret].count) applyCranberrySecret();
state.lastPlanted = -1;
//state.lastPlanted2 = -1;
if(state.crops[berry_0].unlocked) {
state.lastPlanted = berry_0;
} else if(state.crops[brassica_0].unlocked) {
state.lastPlanted = brassica_0;
}
state.resinfruitspores = Num(0);
state.twigsfruitspores = Num(0);
state.just_evolution = false;
for(var i = 0; i < state.automaton_autoactions.length; i++) {
state.automaton_autoactions[i].done = 0;
state.automaton_autoactions[i].time2 = 0;
}
//updateAbilitiesUI();
// after a transcend, it's acceptable to undo the penalty of negative time, but keep some of it. This avoid extremely long time penalties due to a clock mishap.
if(state.negative_time > 3600) state.negative_time = 3600;
// this function is called all the time during update, but also call it now already so that an auto-planted blueprint immediately works
unlockTemplates();
ethereal_basic_boost_cache_counter++;
}
// transcend
function softReset(opt_challenge, opt_automated) {
util.clearLocalStorage(localstorageName_recover); // if there was a recovery save, delete it now assuming that transcending means all about the game is going fine
savegame_recovery_situation = false;
// both of these functions are part of softReset, but endPreviousRun still assumes the old run's state (effects from the old challenge, ...) while
// beginNextRun sets up the state for the new run, applies any new challenge effects, ...
endPreviousRun();
beginNextRun(opt_challenge);
state.runHadAnyHumanAction = !opt_automated;
if(!opt_automated) setTab(0);
removeChallengeChip();
removeAllDropdownElements();
initInfoUI();
updateFruitUI();
}
// the divs and other non-saved-state info of a field cell
function CellDiv() {
this.div = undefined;
this.progress = undefined;
}
// every button click adds an action here, rather than do its effect directly
// reason: every single change must be checked and happen in the update
// function, don't want it done directly from UI button presses
// action object is: {type:action type, ... (other paramters depend on action)}
var actions = [];
var action_index = 0;
var ACTION_FERN = action_index++;
var ACTION_PRESENT = action_index++; // holiday event present or egg
var ACTION_INFSPAWN = action_index++;
var ACTION_PLANT = action_index++;
var ACTION_DELETE = action_index++; //un-plant
var ACTION_REPLACE = action_index++; //same as delete+plant, in one go (prevents hving situation where plant gets deleted but then not having enough resources to plant the other one)
var ACTION_UPGRADE = action_index++;
var ACTION_PLANT2 = action_index++;
var ACTION_DELETE2 = action_index++;
var ACTION_REPLACE2 = action_index++;
var ACTION_UPGRADE2 = action_index++;
var ACTION_ABILITY = action_index++; // action_weather
var ACTION_TRANSCEND = action_index++; // also includes starting a challenge
var ACTION_FRUIT_SLOT = action_index++; // move fruit to other slot. Variables inside: f:fruit object, slottype:0=stored,1=sacrificial, precise_slot:exact destination slot number (only one of slottype or precise_slot must be given)
var ACTION_FRUIT_ACTIVE = action_index++; // select active fruit
var ACTION_FRUIT_LEVEL = action_index++; // level up a fruit ability
var ACTION_FRUIT_REORDER = action_index++; // reorder an ability
var ACTION_FRUIT_FUSE = action_index++; // fuse two fruits together
var ACTION_FRUIT_RECOVER = action_index++;
var ACTION_PLANT_BLUEPRINT_AFTER_TRANSCEND = action_index++; // normally you can use the plantBlueprint function directly (since that one also merely adds more actions), but for transcend it needs to be delayed and that's done through having it as an action
var ACTION_SQUIRREL_UPGRADE = action_index++; // squirrel upgrade
var ACTION_SQUIRREL_RESPEC = action_index++; // respec squirrel upgrades
var ACTION_SQUIRREL_EVOLUTION = action_index++; // reset squirrel evolution
var ACTION_AMBER = action_index++; // amber effects
var ACTION_TOGGLE_AUTOMATON = action_index++; // action object is {toggle:what, on:boolean or int, fun:optional function to call after switching}, and what is: 0: entire automaton, 1: auto upgrades, 2: auto planting
var ACTION_MISTLE_UPGRADE = action_index++; // begin an ethereal mistletoe upgrade
var ACTION_CANCEL_MISTLE_UPGRADE = action_index++;
var ACTION_PLANT3 = action_index++;
var ACTION_DELETE3 = action_index++;
var ACTION_REPLACE3 = action_index++;
var ACTION_PLANT_FISH = action_index++;
var ACTION_DELETE_FISH = action_index++;
var ACTION_REPLACE_FISH = action_index++;
var ACTION_STORE_UNDO_BEFORE_AUTO_ACTION = action_index++; // saves undo and disables (marks as triggered without doing anything) the indicated auto-action, used by automaton when it does auto-action, to allow undoing it. (any action caused by automaton is marked with by_automaton and not stored for undo, but the ACTION_STORE_UNDO_BEFORE_AUTO_ACTION is an exception and is saved, to allow the player to undo an unwanted/unexpected auto-action, and auto-transcends)
var ACTION_FORCE_NO_UNDO_BEFORE_AUTO_ACTION = action_index++; // used to not store undo before the second part of auto-actions, used when this one is triggered by the player (so actions don't have by_automaton marked)
var ACTION_TD_GO = action_index++;
var lastSaveTime = util.getTime();
var lastnonpausetime = 0;
var undoSave = '';
var lastUndoSaveTime = 0;
var lastUndoKeepLong = false; // if true, does not apply maxUndoTime to this undo save (this is used for undoing auto-transcend)
var prev_store_undo = false; // this variable is only used for auto-save after actions and is not directly related to undo
function clearUndo() {
undoSave = '';
lastUndoSaveTime = 0;
lastUndoKeepLong = false;
}
var next_undo_is_redo = false; // TODO: this works as long as you're in the same session, but when refreshing this may make it say the opposite thing than it should
function storeUndo(state) {
// use state.time, not util.getTime() here: auto-actions are an exceptional case where undo is saved automatically without player-action, and so can happen during fast-forward time. so if it uses the real time, it sets the lastUndoSaveTime wrongly (to a too recent time, namely right now), so if player then does a manual action now, undo for the player action won't be saved but the saved undo from right before the auto-action, even if it was long ago in actuality, will be kept.
lastUndoSaveTime = state.time; //util.getTime();
save(state, function(s) {
//console.log('undo saved');
undoSave = s;
util.setLocalStorage(undoSave, localstorageName_undo);
next_undo_is_redo = false;
}, function() {
undoSave = '';
});
}
function loadUndo() {
auto_action_manual_window_timeout_enabled = false;
if(lastUndoSaveTime != 0 && !lastUndoKeepLong && state.time - lastUndoSaveTime > maxUndoTime) {