forked from tsolron/js-KittensGame
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathScriptKitties.js
2960 lines (2698 loc) · 127 KB
/
ScriptKitties.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
var SK = class {
constructor() {
this.model = new SK.Model();
this.scripts = new SK.Scripts(this.model);
this.tasks = new SK.Tasks(this.model, this.scripts);
this.gui = new SK.Gui(this.model, this.tasks);
this.loadOptions();
console.log("ScriptKittens loaded.");
}
bldTabChildren() {
let children = game.bldTab.children;
if (children.length === 0) children = game.bldTab.buttons;
return children;
}
clearScript() {
this.tasks.halt();
this.model.wipe();
this.gui.destroy();
sk = null;
delete(LCstorage['net.sagefault.ScriptKittens.savedata']);
game.msg('Script is dead');
}
// Note: this function is deliberately not exposed in the gui.
// Reloading is for people already playing around in console.
reloadScript() {
// unload and save
this.tasks.halt();
this.saveOptions();
this.model.wipe();
this.gui.destroy();
sk = null;
// reload
let src = null;
const origins = $('#SK_origin');
for (let i=0; i<origins.length; i+=1) {
if (origins[i].src) src = origins[i].src;
origins[i].remove();
}
if (src) {
const script = document.createElement('script');
script.src = src;
script.id = 'SK_origin';
document.body.appendChild(script);
} else {
console.error('No <script> found with id==="SK_origin"');
}
}
saveOptions() {
const options = {};
this.model.save(options);
this.scripts.save(options);
LCstorage['net.sagefault.ScriptKittens.savedata'] = JSON.stringify(options);
}
loadOptions() {
const dataString = LCstorage['net.sagefault.ScriptKittens.savedata'];
if (dataString) {
try {
var options = JSON.parse(dataString);
} catch (ex) {
console.error('Unable to load game data: ', ex);
console.log(dataString);
game.msg('Unable to load script settings. Settings were logged to console.', 'important');
delete(LCstorage['net.sagefault.ScriptKittens.loaddata']);
game.msg('Settings deleted.');
}
this.model.load(options);
this.scripts.load(options);
this.gui.refresh();
}
}
};
/**
* These are the data structures that govern the automation scripts
**/
SK.Model = class {
constructor() {
// Is a toggle holder. Use like ``auto.craft = true; if (auto.craft) { ...
this.auto = {};
// These are the assorted variables
this.books = ['parchment', 'manuscript', 'compedium', 'blueprint'];
this.option = {};
// These control the selections under [Minor Options]
this.minor = {};
this.minorNames = {
program: 'Space Programs',
observe: 'Auto Observe',
feed: 'Auto Feed Elders',
promote: 'Auto Promote Leader',
wait4void: 'Only Shatter at Season Start',
praiseAfter: 'Praise After Religion',
unicornIvory: 'Unicorn Ivory Optimization',
conserveExotic: 'Conserve Exotic Resources',
elderTrade: 'Always Trade with the Elders',
autoFixCC: 'Auto use Flux to fix Cryo Chambers',
permitReset: 'Permit Auto Play to Reset',
};
// These will allow quick selection of the buildings which consume energy
this.power = {};
for (const b of ['biolab', 'oilWell', 'factory', 'calciner', 'accelerator']) {
this.power[b] = game.bld.get(b);
}
// Note: per game: uncommon==luxuries==(trade goods), rare==unicorns+karma, exotic==relics+void+bc+bs
// This is the list of resources that conserveExotic cares about
this.exoticResources = [
'antimatter', // how is AM not exotic?
'blackcoin',
'bloodstone',
'relic',
'temporalFlux', // honorary
'void',
];
this.setDefaults();
this.populateDataStructures();
}
setDefaults() {
this.option = {
book: 'default',
assign: 'smart',
cycle: 'redmoon',
minSecResRatio: 1,
maxSecResRatio: 25,
script: 'none',
};
this.minor = {
// everything not specified defaults to false
observe: true,
conserveExotic: true,
partyLimit: 10,
elderTrade: true,
};
}
wipe() {
this.auto = {}; // wipe fields
this.minor = {};
this.option = {};
for (const buildset of [this.cathBuildings, this.spaceBuildings, this.timeBuildings]) {
for (const bid in buildset) {
delete buildset[bid].limit;
buildset[bid].enabled = false;
}
}
}
save(options) {
for (const key of ['auto', 'minor', 'option', 'cathBuildings', 'spaceBuildings', 'timeBuildings']) {
options[key] = this[key];
}
}
load(options) {
for (const key of ['auto', 'minor', 'option', 'cathBuildings', 'spaceBuildings', 'timeBuildings']) {
if (options[key]) this[key] = options[key];
}
}
populateDataStructures() {
// Building lists for controlling Auto Build/Space/Time
this.cathBuildings = {/* list is auto-generated, looks like:
field:{label:'Catnip Field', enabled:false},
...
*/};
this.cathGroups = [/*
['Food Production', ['field', 'pasture', 'aqueduct']],
...
*/];
for (const group of game.bld.buildingGroups) {
const buildings = group.buildings.map((n) => game.bld.get(n));
this.cathGroups.push([group.title, this.buildGroup(buildings, this.cathBuildings)]);
}
this.spaceBuildings = {/*
spaceElevator:{label:'Space Elevator', enabled:false},
...
*/};
this.spaceGroups = [/*
['Cath', ['spaceElevator', 'sattelite', 'spaceStation']],
...
*/];
for (const planet of game.space.planets) {
this.spaceGroups.push([planet.label, this.buildGroup(planet.buildings, this.spaceBuildings)]);
}
this.timeBuildings = {/*
// As above, but for Ziggurats, Cryptotheology, Chronoforge, Void Space
...
*/};
this.timeGroups = [/*
// As above
...
*/];
this.timeGroups.push(['Ziggurats', this.buildGroup(game.religion.zigguratUpgrades, this.timeBuildings)]);
this.timeGroups.push(['Cryptotheology', this.buildGroup(game.religion.transcendenceUpgrades, this.timeBuildings)]);
this.timeGroups.push(['Chronoforge', this.buildGroup(game.time.chronoforgeUpgrades, this.timeBuildings)]);
this.timeGroups.push(['Void Space', this.buildGroup(game.time.voidspaceUpgrades, this.timeBuildings)]);
}
buildGroup(buildings, dict) {
const group = [];
for (const building of buildings) {
if (buildings === game.religion.zigguratUpgrades && building.effects.unicornsRatioReligion) continue; // covered by autoUnicorn()
let label = building.stages?.map((x) => x.label).join(' / '); // for 'Library / Data Center', etc
label ||= building.label;
dict[building.name] = {label: label, enabled: false};
group.push(building.name);
}
return group;
}
};
/**
* This subclass contains the code that lays out the GUI elements
**/
SK.Gui = class {
constructor(model, tasks) {
this.model = model;
this.tasks = tasks;
this.switches = {};
this.dropdowns = {};
$('#footerLinks').append('<div id="SK_footerLink" class="column">'
+ ' | <a href="#" onclick="$(\'#SK_mainOptions\').toggle();"> ScriptKitties </a>'
+ '</div>');
$('#game').append(this.generateMenu());
$('#SK_mainOptions').hide(); // only way I can find to have display:grid but start hidden
$('#game').append(this.generateBuildingMenu());
this.switchTab('cath'); // default
$('#game').append(this.generateMinorOptionsMenu());
}
destroy() {
$('#SK_footerLink').remove();
$('#SK_mainOptions').remove();
$('#SK_buildingOptions').remove();
$('#SK_minorOptions').remove();
}
generateMenu() {
const grid = [ // Grid Layout
[this.autoButton('Kill Switch', 'sk.clearScript()')],
[this.autoButton('Check Efficiency', 'sk.tasks.kittenEfficiency()'), this.autoButton('Minor Options', '$(\'#SK_minorOptions\').toggle();')],
[this.autoSwitchButton('Auto Build', 'build'), this.autoButton('Select Building', '$(\'#SK_buildingOptions\').toggle();')],
[this.autoSwitchButton('Auto Assign', 'assign'), this.autoDropdown('assign', ['smart'], game.village.jobs)],
[this.autoSwitchButton('Auto Craft', 'craft'), this.autoDropdown('book', ['default'].concat(this.model.books), [])],
['<label style="{{grid}}">Secondary Craft %</label>',
`<span style="display:flex; justify-content:space-around; {{grid}}" title="Between 0 and 100">`
+ `<label>min:</label><input id="SK_minSRS" type="text" style="width:25px" onchange="sk.model.option.minSecResRatio=this.value" value="${this.model.option.minSecResRatio}">`
+ `<label>max:</label><input id="SK_maxSRS" type="text" style="width:25px" onchange="sk.model.option.maxSecResRatio=this.value" value="${this.model.option.maxSecResRatio}">`
+ `</span>`
],
['<span style="height:10px;{{grid}}"></span>'],
[this.autoSwitchButton('Auto Hunt', 'hunt'), this.autoSwitchButton('Auto Praise', 'praise')],
[this.autoSwitchButton('Auto Trade', 'trade'), this.autoSwitchButton('Auto Embassy', 'embassy')],
[this.autoSwitchButton('Auto Party', 'party'), this.autoSwitchButton('Auto Explore', 'explore')],
['<span style="height:10px;{{grid}}"></span>'],
[this.autoSwitchButton('Auto Cycle', 'cycle'), this.autoDropdown('cycle', [], game.calendar.cycles)],
[this.autoSwitchButton('Shatterstorm', 'shatter'), this.autoSwitchButton('Auto BCoin', 'bcoin')],
[this.autoSwitchButton('Auto Play', 'play'), this.autoDropdown('script', ['none'], SK.Scripts.listScripts(), 'sk.gui.scriptChange(this.value)')],
['<span style="height:10px;{{grid}}"></span>'],
[this.autoSwitchButton('Auto Science', 'research'), this.autoSwitchButton('Auto Upgrade', 'workshop')],
[this.autoSwitchButton('Auto Religion', 'religion'), this.autoSwitchButton('Auto Unicorn', 'unicorn')],
[this.autoSwitchButton('Energy Control', 'energy'), this.autoSwitchButton('Auto Flux', 'flux')],
];
this.dropdowns.minSecResRatio = 'SK_minSRS';
this.dropdowns.maxSecResRatio = 'SK_maxSRS';
let menu = '<div id="SK_mainOptions" class="dialog" style="display:grid; grid-template-columns:177px 177px; column-gap:5px; row-gap:5px; left:auto; top:auto !important; right:30px; bottom: 30px; padding:10px">';
menu += '<a href="#" onclick="$(\'#SK_mainOptions\').hide();" style="position: absolute; top: 10px; right: 15px;">close</a>';
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
if (!grid[row][col].includes('{{grid}}')) console.warn(`Cell at [${row+1},${col+1}] does not have position marker`);
menu += grid[row][col].replace('{{grid}}', `grid-row:${row+1}; grid-column:${col+1};`);
}
}
menu += '</div>';
return menu;
}
generateMinorOptionsMenu() {
let menu = '';
menu += '<div id="SK_minorOptions" class="dialog help" style="border: 1px solid gray; display:none;">';
menu += '<a href="#" onclick="$(\'#SK_minorOptions\').hide();" style="position: absolute; top: 10px; right: 15px;">close</a>';
for (const opt in this.model.minorNames) {
menu += `<input type="checkbox" id="SK_${opt}" onchange="sk.model.minor.${opt}=this.checked"${this.model.minor[opt]?' checked':''}>`;
menu += `<label style="padding-left:10px;" for="SK_${opt}">${this.model.minorNames[opt]}</label><br>`;
}
menu += '</div>';
return menu;
}
generateBuildingMenu() {
let menu = '';
menu += '<div id="SK_buildingOptions" class="dialog help" style="border: 1px solid gray; display:none; margin-top:-333px; margin-left:-200px;">';
menu += '<a href="#" onclick="$(\'#SK_buildingOptions\').hide();" style="position: absolute; top: 10px; right: 15px;">close</a>';
menu += '<div class="tabsContainer" style="position: static;">';
menu += '<a href="#" id="SK_cathTab" class="tab" onclick="sk.gui.switchTab(\'cath\')" style="white-space: nowrap;">Cath</a>';
menu += '<span> | </span>';
menu += '<a href="#" id="SK_spaceTab" class="tab" onclick="sk.gui.switchTab(\'space\')" style="white-space: nowrap;">Space</a>';
menu += '<span> | </span>';
menu += '<a href="#" id="SK_timeTab" class="tab" onclick="sk.gui.switchTab(\'time\')" style="white-space: nowrap;">Time</a>';
menu += '</div>';
menu += '<div id="SK_BuildingFrame" class="tabInner">';
menu += this.generateBuildingPane(this.model.cathGroups, 'cathBuildings');
menu += this.generateBuildingPane(this.model.spaceGroups, 'spaceBuildings');
menu += this.generateBuildingPane(this.model.timeGroups, 'timeBuildings');
menu += '</div>';
menu += '</div>';
return menu;
}
switchTab(name) {
$('#SK_cathTab').removeClass('activeTab');
$('#SK_spaceTab').removeClass('activeTab');
$('#SK_timeTab').removeClass('activeTab');
$('#SK_cathBuildingsPane').hide();
$('#SK_spaceBuildingsPane').hide();
$('#SK_timeBuildingsPane').hide();
switch (name) {
case 'cath':
$('#SK_cathTab').addClass('activeTab');
$('#SK_cathBuildingsPane').show();
break;
case 'space':
$('#SK_spaceTab').addClass('activeTab');
$('#SK_spaceBuildingsPane').show();
break;
case 'time':
$('#SK_timeTab').addClass('activeTab');
$('#SK_timeBuildingsPane').show();
break;
}
}
generateBuildingPane(groups, elementsName) {
let menu = '';
menu += `<div id="SK_${elementsName}Pane" style="display:none; columns:2; column-gap:20px;">\n`;
const tab = elementsName.substring(0, 4); // tab prefix
menu += `<input type="checkbox" id="SK_${tab}TabChecker" onchange="sk.gui.selectChildren('SK_${tab}TabChecker','SK_${tab}Check');">`;
menu += `<label for="SK_${tab}TabChecker">SELECT ALL</label><br>\n`;
for (const group of groups) {
const label = group[0];
const lab = label.substring(0, 3); // used for prefixes, "lab" is prefix of "label"
menu += '<p style="break-inside: avoid;">'; // we want grouping to avoid widows/orphans
menu += `<input type="checkbox" id="SK_${lab}Checker" class="SK_${tab}Check" onchange="sk.gui.selectChildren('SK_${lab}Checker','SK_${lab}Check');">`;
menu += `<label for="SK_${lab}Checker"><b>${label}</b></label><br>\n`;
for (const bld of group[1]) {
menu += `<input type="checkbox" id="SK_${bld}" class="SK_${lab}Check" onchange="sk.model.${elementsName}.${bld}.enabled=this.checked; sk.model.${elementsName}.${bld}.limit=false">`;
menu += `<label style="padding-left:10px;" for="SK_${bld}">${this.model[elementsName][bld].label}</label><br>\n`;
}
menu += '</p>\n';
}
menu += '</div>\n';
return menu;
}
selectChildren(checker, checkee) {
$('.'+checkee).prop('checked', document.getElementById(checker).checked).change();
}
autoSwitch(id, element) {
this.model.auto[id] = !this.model.auto[id];
game.msg(`${element} is now ${(this.model.auto[id] ? 'on' : 'off')}`);
$(`#${element}`).toggleClass('disabled', !this.model.auto[id]);
}
autoButton(label, script, id=null) {
let cssClass = 'btn nosel modern';
if (id) cssClass += ' disabled';
const content = `<div class="btnContent" style="padding:unset"><span class="btnTitle">${label}</span></div>`;
const button = `<div ${id?'id="'+id+'"':''} class="${cssClass}" style="width:auto; {{grid}}" onclick="${script}">${content}</div>`;
return button;
}
autoSwitchButton(label, auto) {
const element = 'SK_auto' + auto[0].toUpperCase() + auto.slice(1);
this.switches[auto] = element;
const script = `sk.gui.autoSwitch('${auto}', '${element}');`;
return this.autoButton(label, script, element);
}
autoDropdown(option, extras, items, script) {
const element = `SK_${option}Choice`;
this.dropdowns[option] = element;
script ||= `sk.model.option.${option}=this.value;`;
let dropdown = `<select id="${element}" style="{{grid}}" onchange="${script}">`;
for (const name of extras) {
const sel = (name === this.model.option[option]) ? ' selected="selected"' : '';
const title = name[0].toUpperCase() + name.slice(1);
dropdown += `<option value="${name}"${sel}>${title}</option>`;
}
for (const item of items) {
const sel = (item.name === this.model.option[option]) ? ' selected="selected"' : '';
let title = item.title;
if (item.glyph) title = item.glyph + ' ' + title;
dropdown += `<option value="${item.name}"${sel}>${title}</option>`;
}
dropdown += '</select>';
return dropdown;
}
scriptChange(value) {
this.model.option.script = value;
sk.scripts.init();
if (this.model.auto.play) this.autoSwitch('play', 'SK_autoPlay');
}
refresh() {
for (const auto in this.switches) {
const element = this.switches[auto];
$('#'+element).toggleClass('disabled', !this.model.auto[auto]);
}
for (const option in this.model.option) {
const element = this.dropdowns[option];
$('#'+element).val(this.model.option[option]);
}
for (const minor in this.model.minor) {
$('#SK_'+minor).prop('checked', this.model.minor[minor]);
}
for (const menu of ['cathBuildings', 'spaceBuildings', 'timeBuildings']) {
for (const entry in this.model[menu]) {
$('#SK_'+entry).prop('checked', this.model[menu][entry].enabled);
}
}
}
};
/**
* These are the functions which are launched by the runAllAutomation timer
**/
SK.Tasks = class {
constructor(model, scripts) {
this.model = model;
this.scripts = scripts;
/** This governs how frequently tasks are run
* fn: what function to run
* interval: how often to run, in ticks, that's 0.2 seconds
* offset: small value to stagger runs, MUST be less than interval
* override: force run next tick, dynamic, used to take sequences of actions
**/
this.schedule = [
// every tick
{fn:'autoNip', interval:1, offset:0, override:false},
{fn:'autoPraise', interval:1, offset:0, override:false},
{fn:'autoBuild', interval:1, offset:0, override:false},
// every 3 ticks == 0.6 seconds
{fn:'autoCraft', interval:3, offset:0, override:false},
{fn:'autoMinor', interval:3, offset:1, override:false},
{fn:'autoHunt', interval:3, offset:2, override:false},
// every 5 ticks == 1 second
{fn:'autoPlay', interval:5, offset:0, override:false},
// every 2 seconds == every game-day
{fn:'autoSpace', interval:10, offset:2, override:false},
{fn:'autoTime', interval:10, offset:4, override:false},
{fn:'autoParty', interval:10, offset:6, override:false},
{fn:'energyControl',interval:10, offset:8, override:false},
// every 4 seconds; schedule on odd numbers to avoid the interval:10
{fn:'autoFlux', interval:20, offset:1, override:false},
{fn:'autoAssign', interval:20, offset:3, override:false},
{fn:'autoResearch', interval:20, offset:7, override:false},
{fn:'autoWorkshop', interval:20, offset:9, override:false},
{fn:'autoReligion', interval:20, offset:11, override:false},
{fn:'autoTrade', interval:20, offset:13, override:false},
{fn:'autoShatter', interval:20, offset:17, override:false},
{fn:'autoEmbassy', interval:20, offset:19, override:false},
// every minute, schedule == 10%20 to avoid both above
{fn:'autoExplore', interval:300, offset:70, override:false},
{fn:'autoUnicorn', interval:300, offset:130, override:false},
{fn:'autoBCoin', interval:300, offset:230, override:false},
// every 90 seconds, because KG does 80, but that timing bothers me
{fn:'autoSave', interval:450, offset:90, override:false},
];
// This function keeps track of the game's ticks and uses math to execute these functions at set times relative to the game.
// Offsets are staggered to spread out the load. (Not that there is much).
this.runAllAutomation = setInterval(this.taskRunner.bind(this), 200);
}
halt() {
clearInterval(this.runAllAutomation);
}
taskRunner() {
if (game.isPaused) return; // we pause too
const ticks = game.timer.ticksTotal;
for (const task of this.schedule) {
if (task.override || ticks % task.interval === task.offset) {
task.override = this[task.fn](task.interval, task.override);
}
}
}
// Show current kitten efficiency in the in-game log
kittenEfficiency() {
const secondsPlayed = game.calendar.trueYear() * game.calendar.seasonsPerYear * game.calendar.daysPerSeason * game.calendar.ticksPerDay / game.ticksPerSecond;
const numberKittens = game.resPool.get('kittens').value;
const curEfficiency = (numberKittens - 70) / (secondsPlayed / 3600);
game.msg('Your current efficiency is ' + parseFloat(curEfficiency).toFixed(2) + ' Paragon per hour.');
}
energyReport() {
// TODO solar panels
// "solarFarmRatio" -- PV is 0.5
// "summerSolarFarmRatio" -- challenge: 0.05
// "solarFarmSeasonRatio" -- thinFilm:1, qdot:1
// game.bld.getBuildingExt("pasture").get("calculateEnergyProduction")(game, currentSeason)
// - base: 2, 3 with PV
// 0. spring: 1.00 * sFSR:{1,1,1.30}
// 1. summer: 1.33 * (summer)
// 2. autumn: 1.00 * sFSR:{1,1,1.30}
// 3. winter: 0.75 * sFSR:{1, 1.15, 1.30}
// Looks like:
// season 3: no change
//
//
//
const total = {};
for (const effect of ['energyProduction', 'energyConsumption']) {
const sign = effect === 'energyProduction' ? '+' : '-';
total[effect] = 0;
for (const source of [game.bld.buildingsData, game.space.planets, game.time.chronoforgeUpgrades, game.time.voidspaceUpgrades]) {
for (let shim of source) {
shim = shim.buildings ? shim.buildings : [shim];
for (const building of shim) {
const stage = building.stage ? building.stages[building.stage] : building;
if (! stage.effects || building.val === 0) continue;
let eper = stage.effects[effect];
if (building.name === 'pasture' && effect === 'energyProduction') {
// deal with Solar Farms. Peak is in summer(1), Low in winter(3). Report low, mention high.
const cep = building.stages[building.stage].calculateEnergyProduction;
eper = cep(game, 3);
total.summer = (cep(game, 1) - eper) * building.on;
}
if (eper) {
console.log(`${stage.label} (${building.on}/${building.val}): ${sign}${eper * building.on}`);
total[effect] += eper * building.on;
}
}
}
}
}
const energyProdRatio = 1 + game.getEffect("energyProductionRatio");
const energyConsRatio = 1 + game.getLimitedDR(game.getEffect("energyConsumptionRatio"), 1) + game.getEffect("energyConsumptionIncrease");
total.summer *= energyProdRatio;
total.energyProduction *= energyProdRatio;
total.energyConsumption *= energyConsRatio;
total.winterSurplus = total.energyProduction - total.energyConsumption;
console.log(total);
return total;
}
ensureContentExists(tabId) {
// only work for visible tabs
const tab = game.tabs.find((tab) => tab.tabId===tabId);
if (! tab.visible) return false;
let doRender = false;
switch (tabId) {
case 'Village':
doRender = (! tab.festivalBtn || ! tab.huntBtn);
break;
case 'Science':
doRender = (tab.buttons.length === 0 || ! tab.policyPanel);
break;
case 'Workshop':
doRender = (tab.buttons.length === 0);
break;
case 'Trade':
doRender = (tab.racePanels.length === 0 || ! tab.exploreBtn);
break;
case 'Religion':
doRender = (tab.zgUpgradeButtons.length === 0 && game.bld.get('ziggurat').on > 0
|| tab.rUpgradeButtons.length === 0 && !game.challenges.isActive("atheism"));
// ctPanel is set during constructor, if it's not there we're pooched
break;
case 'Space':
doRender = (! tab.planetPanels || ! tab.GCPanel);
if (tab.planetPanels) {
let planetCount = 0;
for (const planet of game.space.planets) {
if (planet.unlocked) planetCount += 1;
}
doRender ||= tab.planetPanels.length < planetCount;
}
break;
case 'Time':
doRender = (! tab.cfPanel.children[0].children[0].model || ! tab.vsPanel.children[0].children[0].model);
// both cfPanel and vsPanel are created in constructor.
break;
default:
console.error(`ensureContentExists(${tab}) isn't handled.`);
break;
}
if (doRender) {
// create and get DOM element
let div = $(`div.tabInner.${tabId}`)[0];
let oldTab = null;
if (! div) {
oldTab = game.ui.activeTabId;
game.ui.activeTabId = tabId;
game.ui.render();
div = $(`div.tabInner.${tabId}`)[0];
}
tab.render(div);
console.log(`[DEBUG] rendering children of ${tabId}`);
if (oldTab) {
game.ui.activeTabId = oldTab;
game.ui.render();
}
}
// For things we need to do post-render()
switch (tabId) {
case 'Time':
// cfPanel only becomes "visible" on an update()
if (!game.timeTab.cfPanel.visible && game.workshop.get('chronoforge').researched) game.timeTab.update();
break;
}
}
buyItem(button, event={}) {
// It is important to know that the callback is normally called
// immediately, but there is no guarantee. I'm not really sure how it
// plays out if it is delayed. However, it's fine if this function
// sometimes returns false when it should have returned true.
let success = false;
button.controller.buyItem(button.model, event, function(result) {
if (result) {
success = true;
button.update();
}
});
return success;
}
makeSpace(resource, amount) {
// Something is going to produce ``amount`` of ``resource``, and
// wants it to not go to waste.
for (const craft of game.workshop.crafts) {
const price = craft.prices.find((p) => p.name === resource.name);
if (! price) continue;
const craftCount = Math.ceil(amount / price.val); // workshops don't reduce prices...
console.log(`pre-trade crafting away ${amount} ${resource.name} into ${craft.name}`); // XXX remove
// over-specify here to prevent infinite loops. Address in the unlikely case it ever matters
if (resource.name=='catnip' && craft.name=='wood') this.makeSpace('wood', craftCount);
game.craft(craft.name, craftCount);
break;
}
}
/*** Individual Auto Scripts start here ***/
/*** These scripts run every tick ***/
// Basic Bootstrapping, automatically gather catnip and refine it to wood.
autoNip(ticksPerCycle) {
if (this.model.auto.build && game.bld.get('field').val < 20) {
$(`.btnContent:contains(${$I('buildings.gatherCatnip.label')})`).trigger('click');
}
if (this.model.auto.craft && game.bld.get('workshop').val < 1 && game.bld.get('hut').val < 5) {
if (sk.bldTabChildren()[1].model.enabled) {
$(`.btnContent:contains(${$I('buildings.refineCatnip.label')})`).trigger('click');
}
}
return false;
}
// Auto praise the sun
autoPraise(ticksPerCycle) {
if (this.model.auto.praise && game.resPool.get("faith").value > 0) {
game.religion.praise();
}
}
// Build buildings automatically
autoBuild(ticksPerCycle) {
let built = false;
if (this.model.auto.build && game.ui.activeTabId === 'Bonfire') {
const cb = this.model.cathBuildings;
for (var button of sk.bldTabChildren()) {
if (! button.model.metadata) continue;
const name = button.model.metadata.name;
if (button.model.enabled && cb[name].enabled
&& (!cb[name].limit || button.model.metadata.val < cb[name].limit)) {
if (this.buyItem(button)) built = true;
}
}
}
// if (built) game.render(); // update tooltip, is kinda slow
return built;
}
/*** These scripts run every three ticks ***/
// Craft primary resources automatically
autoCraft(ticksPerCycle) {
/* Note: In this function, rounding gives us grief.
* If we have enough resource to craft 3.75 of of something, and ask for
* that, the game rounds up to 4 and then fails because we don't have
* enough.
*
* However, we mostly craft "off the top", making space for production,
* so we'll usually have the slack. But when we don't, it effectively turns
* off autoCraft for that resource.
*
* On the other hand, we don't want to always round down, or else we'll be
* wasting resources, and in some cases *cough*eludium*cough*, we'll be
* rounding down to zero.
*
* Note: There are problems with some crafts starving later crafts.
* This is fine for things that use SRS, because percentages, but for
* plates and steel it's a problem. To avoid that we treat "iron" special.
*/
let ironCache = null;
if (this.model.auto.craft && game.workshopTab.visible) {
for (const res of game.workshop.crafts) {
const output = res.name;
const inputs = res.prices;
const outRes = game.resPool.get(output);
if (! res.unlocked) continue;
if (outRes.type !== 'common') continue; // mostly to prevent relic+tc->bloodstone
let craftCount = Infinity;
let minimumReserve = Infinity;
for (const input of inputs) {
const inRes = game.resPool.get(input.name);
const outVal = outRes.value / (1 + game.getCraftRatio(outRes.tag));
const inVal = inRes.value / input.val;
craftCount = Math.min(craftCount, Math.floor(inVal)); // never try to use more than we have
// for when our capacity gets large compared to production
minimumReserve = Math.min(minimumReserve, inVal * (this.model.option.minSecResRatio / 100) - outVal);
if (this.model.books.includes(output) && this.model.option.book !== 'default') {
// secondary resource: fur, parchment, manuscript, compendium
const outputIndex = this.model.books.indexOf(output);
const choiceIndex = this.model.books.indexOf(this.model.option.book);
if (outputIndex > choiceIndex) {
craftCount = 0;
minimumReserve = 0;
break;
}
} else if (inRes.maxValue) {
// primary resource
const resourcePerCycle = game.getResourcePerTick(input.name, 0) * ticksPerCycle;
let surplus = inRes.value + resourcePerCycle - inRes.maxValue;
if (inRes.name === "iron") {
if (ironCache === null) ironCache = surplus;
else surplus = ironCache;
}
if (0 < surplus && surplus < resourcePerCycle * 2) {
craftCount = Math.min(craftCount, surplus / input.val);
} else {
craftCount = 0;
}
} else {
// secondary resource: general
const targetValue = (inVal + outVal) * (this.model.option.maxSecResRatio / 100);
if (outVal >= targetValue) {
craftCount = 0;
} else {
craftCount = Math.min(craftCount, targetValue - outVal);
}
}
}
craftCount = Math.max(craftCount, minimumReserve);
if (craftCount === 0 || craftCount === Infinity) {
// nothing to do, or no reason to act
} else if (this.model.option.book === 'blueprint' && output === 'compedium' && game.resPool.get('compedium').value > 25) {
// save science for making blueprints
} else {
if (res.maxValue) this.makeSpace(res, craftCount);
game.craft(output, craftCount);
}
}
}
return false; // we scale action to need, re-run never required
}
// Collection of Minor Auto Tasks
autoMinor(ticksPerCycle) {
let override = false;
if (this.model.minor.feed) {
const ncorns = game.resPool.get('necrocorn').value;
if (ncorns >= 1 && game.diplomacy.get('leviathans').unlocked) {
const energy = game.diplomacy.get('leviathans').energy || 0;
if (energy < game.diplomacy.getMarkerCap()) {
game.diplomacy.feedElders(ncorns);
override = true;
}
}
}
if (this.model.minor.observe) {
const checkObserveBtn = game.calendar.observeBtn;
if (checkObserveBtn) checkObserveBtn.click();
}
if (this.model.minor.promote) {
const leader = game.village.leader;
if (leader) {
const expToPromote = game.village.getRankExp(leader.rank);
const goldToPromote = 25 * (leader.rank + 1);
if (leader.exp >= expToPromote && game.resPool.get('gold').value >= goldToPromote) {
if (game.village.sim.promote(leader) > 0) {
const census = game.villageTab.censusPanel?.census;
if (census) {
census.renderGovernment(census.container);
census.update();
}
}
}
}
}
return override;
}
// Hunt automatically
autoHunt(ticksPerCycle) {
if (this.model.auto.hunt && game.ui.fastHuntContainer.style.display === 'block') {
const catpower = game.resPool.get('manpower');
const furs = game.resPool.get('furs');
const hunterRatio = game.getEffect("hunterRatio") + game.village.getEffectLeader("manager", 0);
const expectedFurs = (catpower.value / 100) * (40 + 32.5 * hunterRatio);
if (catpower.value > (catpower.maxValue - 1) || expectedFurs > furs.value * 10) {
game.village.huntAll();
}
}
return false; // we huntAll(), should never need to run again
}
/*** These scripts run every game day (2 seconds) ***/
// Build space stuff automatically
autoSpace(ticksPerCycle) {
let built = false;
if (this.model.auto.build && game.spaceTab.visible) {
this.ensureContentExists('Space');
// Build space buildings
const sb = this.model.spaceBuildings;
for (const planet of game.spaceTab.planetPanels) {
for (var spBuild of planet.children) {
if (sb[spBuild.id].enabled && game.space.getBuilding(spBuild.id).unlocked
&& (!sb[spBuild.id].limit || spBuild.model.metadata.val < sb[spBuild.id].limit)) {
// .enabled doesn't update automatically unless the tab is active, force it
if (! spBuild.model.enabled) spBuild.controller.updateEnabled(spBuild.model);
if (spBuild.model.enabled) {
if (this.buyItem(spBuild)) built = true;
}
}
}
}
}
// Build space programs
if (this.model.minor.program && game.spaceTab.visible) {
this.ensureContentExists('Space');
for (var program of game.spaceTab.GCPanel.children) {
if (program.model.metadata.unlocked && program.model.on === 0) {
// hack to allow a limit on how far out to go
if (typeof(this.model.minor.program) === 'number') {
const chart = program.model.metadata.prices.find((p) => p.name === 'starchart');
if (this.model.minor.program < chart.val) continue;
}
// normal path
if (! program.model.enabled) program.controller.updateEnabled(program.model);
if (program.model.enabled) {
if (this.buyItem(program)) built = true;
}
}
}
}
return built;
}
// Build religion/time stuff automatically
autoTime(ticksPerCycle) {
let built = false;
if (this.model.auto.build) {
const buttonGroups = [
game.religionTab?.zgUpgradeButtons,
game.religionTab?.ctPanel?.children[0]?.children,
game.timeTab?.cfPanel?.children[0]?.children,
game.timeTab?.vsPanel?.children[0]?.children,
];
this.ensureContentExists('Religion');
this.ensureContentExists('Time');
// TODO: special case for Markers and Tears -- exists in autoUnicorn
const tb = this.model.timeBuildings;
for (const buttons of buttonGroups) {
if (buttons) {
for (const button of buttons) {
if (tb[button.id]?.enabled && button.model?.metadata?.unlocked
&& (!tb[button.id].limit || button.model.metadata.val < tb[button.id].limit)) {
if (! button.model.enabled) button.controller.updateEnabled(button.model);
if (button.model.enabled) {
if (this.buyItem(button)) built = true;
}
}
}
}
}
}
return built;
}
// Festival automatically
autoParty(ticksPerCycle) {
if (this.model.auto.party && game.science.get('drama').researched && game.villageTab.visible) {
const catpower = game.resPool.get('manpower').value;
const culture = game.resPool.get('culture').value;
const parchment = game.resPool.get('parchment').value;
if (catpower >= 1500 && culture >= 5000 && parchment >= 2500) {
if (game.prestige.getPerk('carnivals').researched && game.calendar.festivalDays <= 400 * (this.model.minor.partyLimit - 1)
|| game.calendar.festivalDays === 0
) {
this.ensureContentExists('Village');
this.buyItem(game.villageTab.festivalBtn);
}
}
}
return false; // there is never a need to re-run
}
// Control Energy Consumption
energyControl(ticksPerCycle) {
if (this.model.auto.energy) {
const proVar = game.resPool.energyProd;
let conVar = game.resPool.energyCons;
// TODO:
// generally when I have to turn things off:
// 1. off go the biolabs
// 2. off go the pumpjack
// 3. off goes the accelerators
// ---
// now we turn something on...
// T. enable thorium reactors
// ---
// now things I care about start going off:
// 4. factory
// 5. calciner
// 6. orbital array
// 7. lunar outposts
// 8. moon bases
// ---
// finals:
// X. Entanglement Station
// X. Chronocontrol
// X. Containment chambers
// Y. Space Stations -- note, never auto enable space stations
// ---
// Xenosage's recommendations
// 1. Trim Energy Containment to either zero, or what's necessary to allow AM growth
// 2. make sure biolabs only turn off if they're consuming power
// 3. turn off many buildings per tick
if (this.model.power.accelerator.val > this.model.power.accelerator.on && proVar > (conVar + 3)) {
this.model.power.accelerator.on++;
conVar++;
} else if (this.model.power.calciner.val > this.model.power.calciner.on && proVar > (conVar + 3)) {
this.model.power.calciner.on++;
conVar++;
} else if (this.model.power.factory.val > this.model.power.factory.on && proVar > (conVar + 3)) {
this.model.power.factory.on++;
conVar++;
} else if (this.model.power.oilWell.val > this.model.power.oilWell.on && proVar > (conVar + 3)) {
// pumpjack is optional, we should reduce wells.on until we'd get more production
// from all on and pumpjack off
this.model.power.oilWell.on++;