forked from nuclear-unicorn/kittensgame
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
6432 lines (5685 loc) · 195 KB
/
Copy pathgame.js
File metadata and controls
6432 lines (5685 loc) · 195 KB
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
// @ts-check
/**
* A class for a game page container
*
* See core.js for the conventions used here. In short: every dojo.declare result
* is captured in a plain global var so the checker can infer the class shape from
* the object literal, while dojo.declare still registers the dotted path
* (classes.game.Timer, com.nuclearunicorn.game.ui.GamePage, ...) exactly as before.
* `new classes.game.X(...)` call sites are deliberately left alone so mods that
* swap out a class on the global namespace keep working; the captured var is used
* only in superclass position and in type annotations.
*/
/**
* One line of a resource breakdown tooltip.
* @typedef {{name: any, type: string, value: any, forceDisplay?: boolean}} ResStackEntry
*/
/**
* A resource breakdown, as consumed by `processResourcePerTickStack`. Entries
* nest: an element that is itself an array is rendered as an indented sub-stack.
* @typedef {(ResStackEntry | ResStack)[]} ResStack
*/
/**
* Display metadata for one effect. Every field is optional - a bare `{title: ...}`
* is a valid meta, and `getEffectMeta` falls back to exactly that.
* @typedef {{title?: string, resName?: string, type?: string, calculation?: string}} EffectMeta
*/
/**
* A parsed save blob. Every manager owns a top level key and is free to put
* whatever it likes under it, so this stays an open record; `saveVersion` is the
* only field game.js itself reads.
* @typedef {{saveVersion?: number} & Record<string, any>} SaveData
*/
/**
* One undoable game action, as recorded by `UndoChange#addEvent`.
* @typedef {{managerId: string, data: any, description: string}} UndoEvent
*/
/**
* A recurring callback registered with `Timer#addEvent`. `phase` counts down once
* per tick; the handler fires and the phase resets when it reaches zero.
* @typedef {{handler: () => void, frequency: number, phase: number}} TimerEvent
*/
/**
* dojo.declare hands back a constructor *value*, not a TypeScript class, so the
* bare name cannot be used in a type position. These aliases give each captured
* class an instance type under the same name - the type and the var live in
* separate declaration spaces, so `Timer` means the constructor in an expression
* and the instance everywhere a type is expected.
*
* These are inferred from the object literals, so a component that types its
* `game` back-reference as `GamePage` may NOT be referenced back from GamePage's
* own props by type: the two inferences would chase each other and TS bails with
* "circularly references itself". The back-reference is the side worth keeping -
* it is what every manager in js/ wants (see the TODO on TabManager#game in
* core.js) - so GamePage's handles to those components stay loose instead.
*
* @typedef {InstanceType<typeof Timer>} Timer
* @typedef {InstanceType<typeof Telemetry>} Telemetry
* @typedef {InstanceType<typeof Server>} Server
* @typedef {InstanceType<typeof UndoChange>} UndoChange
* @typedef {InstanceType<typeof EffectsManager>} EffectsManager
* @typedef {InstanceType<typeof GamePage>} GamePage
*/
/**
* Just a simple timer, js timer sucks
*/
var Timer = dojo.declare("classes.game.Timer", null, {
/** @type {TimerEvent[]} */
handlers: [],
/** @type {(() => void)[]} */
scheduledHandlers: [],
ticksTotal: 0,
/** @type {number} epoch ms captured by beforeUpdate */
timestampStart: null,
/** @type {number} running sum of every tick's duration, in ms */
totalUpdateTime: null,
currentTime: 0,
averageTime: 0,
/**
* Register a handler to be fired every `frequency` ticks.
* @param {() => void} handler
* @param {number} frequency - in ticks
*/
addEvent: function(handler, frequency){
this.handlers.push({
handler: handler,
frequency: frequency,
phase: 0
});
},
update: function(){
for (var i = 0; i < this.handlers.length; i++){
var h = this.handlers[i];
h.phase--;
if (h.phase <= 0){
h.phase = h.frequency;
h.handler();
}
}
},
/**
* Run `handler` once, at the top of the next tick. Used to keep save/load/reset
* from landing in the middle of an update cycle.
* @param {() => void} handler
*/
scheduleEvent: function(handler){
this.scheduledHandlers.push(handler);
},
updateScheduledEvents: function(){
for (var i in this.scheduledHandlers){
this.scheduledHandlers[i]();
}
this.scheduledHandlers = [];
},
beforeUpdate: function(){
this.timestampStart = new Date().getTime();
},
afterUpdate: function(){
this.ticksTotal++;
var timestampEnd = new Date().getTime();
var tsDiff = timestampEnd - this.timestampStart;
this.totalUpdateTime += tsDiff;
this.currentTime = tsDiff;
this.averageTime = Math.round(this.totalUpdateTime / this.ticksTotal);
}
});
var IDataStorageAware = dojo.declare("mixin.IDataStorageAware", null, {
/**
* `save`/`load` are the contract this mixin imposes on whatever class mixes
* it in; they are not defined here.
* @this {{save: (...args: any[]) => any, load: (...args: any[]) => any}}
*/
constructor: function(){
dojo.subscribe("server/save", dojo.hitch(this, this.save));
dojo.subscribe("server/load", dojo.hitch(this, this.load));
}
});
var Telemetry = dojo.declare("classes.game.Telemetry", [IDataStorageAware], {
/** @type {string} rfc4122 v4 id identifying this player across saves */
guid: null,
/** @type {GamePage} */
game: null,
/** @type {string} set by the platform bootstrap from build.version.json */
buildRevision: null,
/** @type {string} */
version: null,
errorCount: 0,
/** @param {GamePage} game */
constructor: function(game) {
this.guid = this.generateGuid();
this.game = game;
},
// See https://www.ietf.org/rfc/rfc4122.txt, section 4.4
/** @returns {string} */
generateGuid: function() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
return (c == "x" ? 16 * Math.random() | 0 : 4 * Math.random() | 8).toString(16);
});
},
/** @param {SaveData} data */
save: function(data) {
data["telemetry"] = {
guid: this.guid
};
},
/** @param {SaveData} data */
load: function(data) {
if (data["telemetry"]) {
this.guid = data["telemetry"].guid || this.generateGuid();
}
var self = this;
// FIXME: This really wants to happen before `window.load` is fired, but
// this script isn't even loaded yet. So the first PageView will not get
// all this data.
if (window.newrelic && !this.game.opts.disableTelemetry){
// Add a "release" so NR can determine which version of the code was loaded
// when a JS error was noticed.
window.newrelic.addRelease('KG', this.version + ".r" + this.buildRevision);
// Log basic information to *all* PageAction and BrowserInteraction events
// that follow such as game build, uid, etc.
window.newrelic.setCustomAttribute('buildRevision', this.version + ".r" + this.buildRevision);
window.newrelic.setCustomAttribute('guid', this.guid);
if (this.game.server.userProfile){
window.newrelic.setCustomAttribute('uid', this.game.server.userProfile.uid);
}
/**
* Known offenders that folks still use
*/
window.newrelic.setErrorHandler(function (err) {
self.game.achievements.unlockBadge("ghostInTheMachine");
if (self.errorCount >= 100){
return true;
}
//ban error reporting from https://rawgit.com/mikiso1024/kitten-master/master/kitten_master.js
if (err.stack.lastIndexOf("mikiso1024") >= 0){
return true;
} else {
self.errorCount++;
return false;
}
});
}
},
// Use this method to create a new PageAction event
/**
* @param {string} eventType
* @param {any} [payload] - decorated with build/uid by the browser agent
*/
logEvent: function(eventType, payload) {
payload = payload || {};
if (this.game.isReadOnly()){
return; //previewing someone else's save, none of this is our telemetry to send
}
if (window.newrelic && !this.game.opts.disableTelemetry){
// This will already be decorated by other common things like game build, uid, etc.
window.newrelic.addPageAction(eventType, payload);
}
},
/** @param {string} name - the tab the player switched to */
logRouteChange: function(name) {
if (window.newrelic && !this.game.opts.disableTelemetry){
// Record the current tab name so the charts look pretty in the NR UI.
// Normally this is inferred by route changes, but we don't do that, so we
// need to give the browser agent some hints
// Set the `browserInteractionName` on BrowserInteraction events
var interaction = window.newrelic.interaction();
window.newrelic.setCurrentRouteName(name);
interaction.save();
// Make a new PageAction event
this.logEvent("routeChange", { 'name': name });
}
}
});
/**
* Server is a mediator between client and KGNet
* It supports fetching data about saves, syncing using info, etc
*
* Please see toolbar.jsx.js#WLogin widget for rendering part
*/
var Server = dojo.declare("classes.game.Server", null, {
// Server datas
//---->
showMotd: true,
/** @type {string} */
motdTitle: null,
/** @type {string} */
motdContent: null,
//<----
/**
* Last known real-world b-coin price, used by hodl mode (game.opts.hodl).
*/
bcoinPrice: 63918,
/** @type {GamePage} */
game: null,
/** @type {string} */
motdContentPrevious: null,
motdFreshMessage: false,
//chiral stuff
/**
* KGNet user profile
* Represents an active session, if not null, all XHR calls will be made
* using session cookies
* @type {{uid: string, id: string} & Record<string, any>}
*/
userProfile: null,
/** @type {string} last chiral client state, kept as pretty-printed JSON for display */
chiral: null,
/**
* When was the last time save was uploaded to the cloud. (Unix timestamp)
* @type {number}
*/
lastBackup: null,
/**
* Current client snapshot of the save data
* All operations with the cloud saves should return the save snapshot?
* @type {any}
*/
saveData: null,
/**
* If KS settings are detected in the save, this will be set to true.
*/
isKSDetected: false,
/** @param {GamePage} game */
constructor: function(game){
this.game = game;
},
/** @param {{uid: string, id: string} & Record<string, any>} userProfile */
setUserProfile: function(userProfile){
this.userProfile = userProfile;
},
/**
* Terminate the current KGNet session and clear local session state.
* Returns the jqXHR so callers can chain UI updates.
*/
logout: function(){
var self = this;
return this._xhr("/user/logout/", "POST", {}).always(function(){
self.userProfile = null;
self.saveData = null;
});
},
getServerUrl: function(){
if (this.game.isMobile()){
return "https://kittensgame.com";
}
var host = window.location.hostname;
var isLocalhost = window.location.protocol == "file:" || host == "localhost" || host == "127.0.0.1";
if (isLocalhost && !this.game.isMobile()){
//if you are running chilar locally you should know what you are doing
return "http://localhost:7780";
}
return "https://kittensgame.com";
},
refresh: function(){
var self = this;
console.log("Loading server settings...");
$.ajax({
cache: false,
url: "server.json",
dataType: "json",
success: function(json) {
self.showMotd = json.showMotd;
self.motdTitle = json.motdTitle;
self.motdContent = json.motdContent;
}
}).done(function() {
if (self.motdContentPrevious != self.motdContent) {
self.motdContentPrevious = self.motdContent;
self.motdFreshMessage = true;
}
}).fail(function(err) {
console.log("Unable to parse server.json configuration:", err);
});
//-- fetch UID from KGNet if HTTP session is established ---
if (!this.userProfile){
this.syncUserProfile();
}
},
/**
* Make an XHR request to KGNet server.
* Callers attach their own .done/.fail/.always to the returned jqXHR.
*
* @param {string} url - relative endpoint URL
* @param {"GET"|"POST"} [method] - defaults to "GET"
* @param {object} [data] - post data
* @returns {any} the jqXHR
*/
_xhr: function(url, method, data){
var self = this;
return $.ajax({
cache: false,
type: method || "GET",
dataType: "JSON",
url: this.getServerUrl() + url,
xhrFields: {
withCredentials: true
},
data: data
}).fail(function(jqXHR, textStatus){
console.error("KGNet request failed:", method || "GET", url, "status:", jqXHR.status, textStatus);
if (jqXHR.status == 403){
//the HTTP session is gone (expired or revoked), the cached profile no longer reflects reality
self.setUserProfile(null);
}
});
},
/**
* Show a failed KGNet operation in the game log with a human-readable reason.
* 403 means the session expired; status 0 means the server could not be reached at all.
*
* @param {string} i18nKey - operation message with a {0} placeholder for the reason
* @param {*} jqXHR
*/
_notifyRequestError: function(i18nKey, jqXHR){
var reason;
if (jqXHR.status == 403){
reason = $I("ui.kgnet.error.auth");
} else if (jqXHR.status > 0){
reason = $I("ui.kgnet.error.status", [jqXHR.status]);
} else {
reason = $I("ui.kgnet.error.network");
}
this.game.msg($I(i18nKey, [reason]), "alert");
},
/**
* Fetch user profile from the chiral server,
* User must be logged in and session cookie should be set beforehead
*/
syncUserProfile: function(){
var self = this;
this._xhr("/user/", "GET", {}).done(function(resp){
if (resp && resp.id){
self.setUserProfile(resp);
self.syncSaveData();
}
});
},
syncSaveData: function(){
var self = this;
return this._xhr("/kgnet/save/", "GET", {}).done(function(resp){
self.saveData = resp;
});
},
pushSave: function(){
var self = this,
game = this.game;
if (game.isReadOnly()){
return;
}
game.lastBackup = new Date().getTime();
var saveData = this.game.save();
this._xhr("/kgnet/save/upload/", "POST",
{
//pre-parsing guid to avoid checking it on the backend side
guid: this.game.telemetry.guid,
saveData: this.game.compressLZData(JSON.stringify(saveData, this.game.JSONreplacer), true),
metadata: {
calendar: {
year: game.calendar.year,
day: game.calendar.day
}
}
}).done(function(resp){
game.lastBackup = new Date().getTime();
self.saveData = resp;
self.game.msg($I("save.export.msg"));
}).fail(function(jqXHR){
self._notifyRequestError("save.export.fail", jqXHR);
});
},
/**
* @param {string} guid - identifies which cloud save to update
* @param {{archived?: boolean, label?: string}} metadata
*/
pushSaveMetadata: function(guid, metadata){
var self = this;
if (this.game.isReadOnly()){
return $.Deferred().reject().promise();
}
return this._xhr("/kgnet/save/update/", "POST",
{
//pre-parsing guid to avoid checking it on the backend side
guid: guid,
metadata: metadata
}).done(function(resp){
self.saveData = resp;
}).fail(function(jqXHR){
self._notifyRequestError("save.update.fail", jqXHR);
});
},
/**
* Fetch your own cloud save without applying it anywhere (see also downloadPreview)
* loadSave() layers the "overwrite my game with it" part on top.
* @param {string} guid
* @returns {any} the jqXHR, resolving to {data: string, metadata?: object}
*/
downloadSave: function(guid){
return this._xhr("/kgnet/save/" + guid + "/download/", "GET", {});
},
/**
* Fetch public save based on its shareId
*
* @param {string} shareId
* @returns {any} the jqXHR, resolving to {data: string, metadata?: object}
*/
downloadPreview: function(shareId){
return this._xhr("/preview/" + shareId + "/save/", "GET", {});
},
/**
* Public sharable URL that goes through KGNET and generates openhost preview card
* @param {string} shareId
*/
getPreviewUrl: function(shareId){
//generate redirect url, backend will verify the host
var returnPath = window.location.pathname.replace(/[^/]*$/, "");
return this.getServerUrl() + "/preview/" + shareId + "?r=" + encodeURIComponent(returnPath);
},
/** @param {string} guid */
loadSave: function(guid){
var self = this;
if (this.game.isReadOnly()){
return;
}
this.downloadSave(guid).done(function(resp){
if (!resp || !resp.data){
console.error("unable to load game data", resp);
self.game.msg($I("save.import.fail", [$I("ui.kgnet.error.nodata")]), "alert");
return;
}
var data = resp.data;
LCstorage["com.nuclearunicorn.kittengame.savedata"] = data;
console.log("load successful?");
self.game.load();
self.game.msg($I("save.import.msg"));
self.game.render();
}).fail(function(jqXHR){
self._notifyRequestError("save.import.fail", jqXHR);
});
},
/**
* "hodl" mode price feed.
* Fetches the current real-world b-coin price and caches it in this.bcoinPrice
* (which is persisted in the save file). On any failure we simply keep the last
* known price, so the feature degrades gracefully when offline or rate-limited.
*
* Plain $.ajax, not _xhr: the latter sends credentials, which a wildcard CORS API rejects.
*
* @param {(price: number) => void} [handler] - optional callback invoked with the fresh price
*/
fetchBcoinPrice: function(handler){
var self = this;
return $.ajax({
cache: false,
type: "GET",
dataType: "json",
url: "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd"
}).done(function(resp){
var price = resp && resp.bitcoin && resp.bitcoin.usd;
if (typeof price === "number" && price > 0){
self.bcoinPrice = price;
if (handler){
handler(price);
}
}
}).fail(function(err){
console.log("Unable to fetch b-coin price, keeping last known value", self.bcoinPrice, err);
});
},
/** @param {SaveData} saveData */
save: function(saveData) {
saveData.server = {
motdContent: this.motdContent,
bcoinPrice: this.bcoinPrice
};
},
//TOOD: separate getting chiral client status and sending command to a separate component
/** @param {string} command */
sendCommand: function(command){
var self = this;
if (this.game.isReadOnly()){
return;
}
this._xhr("/kgnet/chiral/game/command/", "POST", {
command: command
}).done(function(resp){
if (resp.clientState){
self.setChiral(resp);
}
});
},
setChiral: function(data){
this.chiral = JSON.stringify(data, null, 2);
}
});
/**
* Undo Change state. Represents a change in one or multiple managers
*/
var UndoChange = dojo.declare("classes.game.UndoChange", null, {
_static:{
DEFAULT_TTL : 20
},
ttl: 0,
/** @type {UndoEvent[]} */
events: null,
constructor: function(){
this.events = [];
},
/**
* Adds an "event" (game-action) to the list of "things that will un-happen if you push the undo button."
* Note to the dev: We gotta come up with a shorter name for that list.
*
* Usage:
* Call this function whenever the player performs an action that can be undone.
* Supply (as arguments) all the relevant data to reconstruct that action, or, if necessary, undo it.
*
* @param {string} managerId Which manager class will handle the relevant undo operation.
* Typically corresponds to which subsystem of the game is associated with that action.
* @param {any} data Any relevant data to reconstruct the action to be undone.
* For example, if the action is "build 10 Log Houses," then the data would somehow specify
* that Log Houses are involved & that there are 10 of them.
* The UndoChange system doesn't understand the data here--it is specific to the associated manager.
* This allows each different manager to track all the data they care about & nothing more.
* @param {string} description An i18n string containing a general human-language description of this undo action.
* The idea is that this would be displayed somewhere in the UI so the player will know
* what is being undone before they commit to undoing an action.
*/
addEvent: function(managerId, data, description){
var event = {
managerId: managerId,
data: data,
description: description
};
this.events.push(event);
},
/**
* Converts an event object into a short, human-language description of what it is.
* @param {UndoEvent} event An object describing an event, like what would be created from the addEvent function.
* @returns {string} If the event is valid, it's an i18n string which describes said event, ideally using concise language.
* If the event is not valid, it's a debug string which hopefully the devs can make use of.
*/
getEventDescription: function(event) {
if (typeof(event) !== "object" || !event) {
return "Error in getEventDescription: event is invalid.";
}
if (typeof(event.description) !== "string") {
return "Error in getEventDescription: the event has no description defined.\nTell the developers it is from the \"" + event.managerId + "\" manager.";
}
//Else, the event exists & its description is a string.
return event.description;
}
});
/*
* Effects metadata manager
*/
var EffectsManager = dojo.declare("com.nuclearunicorn.game.EffectsManager", null, {
/** @type {GamePage} */
game: null,
/** @param {GamePage} game */
constructor: function(game){
this.game = game;
},
/**
* Derives display metadata for the resource-flavoured effects (`woodPerTick`,
* `catnipMax`, ...) by splitting the effect name into a resource prefix and a
* known suffix.
* @param {string} effectName
* @returns {EffectMeta | 0} 0 when the name matches no resource, which is the
* signal for `getEffectMeta` to fall back to the statics table.
*/
effectMeta: function(effectName) {
var game = this.game;
for (var i = 0; i < game.resPool.resources.length; i++) {
var res = game.resPool.resources[i];
if (effectName.indexOf(res.name) == 0) {
var resname = res.name;
var restitle = res.title || resname;
restitle = restitle.charAt(0).toUpperCase() + restitle.substring(1, restitle.length);
var type = effectName.substring(resname.length, effectName.length);
break;
}
}
switch (true){
/* Worker pseudoeffect */
case type == "":
return {
//title to be displayed for effect, id if not defined
title: restitle,
//effect will be hidden if resource is not unlocked
resName: resname,
//value will be affected by opts.usePerSecondValues
type: "perTick"
};
case type == "PerTick":
return {
title: restitle,
resName: resname,
type: "perTick"
};
case type == "PerTickRatio":
return {
title: $I("effectsMgr.type.resRatio", [restitle]),
resName: resname,
type: "ratio"
};
case type == "ConsumptionAmbassadors":
return {
title: $I("effectsMgr.type.villageConsumption", [restitle]),
resName: resname,
type: "perTick"
};
case type == "Max":
return {
title: $I("effectsMgr.type.resMax", [restitle]),
resName: resname
};
case type == "MaxChallenge": //for when challenges change Max of resources; LDR to all other sources of Max
return {
title: $I("effectsMgr.type.resMax", [restitle]),
resName: resname
};
case type == "Ratio":
return {
title: $I("effectsMgr.type.resRatio", [restitle]),
resName: resname,
type: "ratio"
};
case type == "DemandRatio":
return {
title: $I("effectsMgr.type.resDemandRatio", [restitle]),
resName: resname,
type: "ratio"
};
case (type == "PerTickBase" || type == "PerTickBaseSpace"):
return {
title: $I("effectsMgr.type.resProduction", [restitle]),
resName: resname,
type: "perTick"
};
case (type == "PerTickCon" || type == "PerTickAutoprod" || type == "PerTickProd" || type == "PerTickSpace" || type == "PerTickAutoprodSpace"):
return {
title: $I("effectsMgr.type.resConversion", [restitle]),
resName: resname,
type: "perTick"
};
case type == "CraftRatio":
return {
title: $I("effectsMgr.type.resCraftRatio", [restitle]),
resName: resname,
type: "ratio"
};
case type == "GlobalCraftRatio":
return {
title: $I("effectsMgr.type.resGlobalCraftRatio", [restitle]),
resName: resname,
type: "ratio"
};
case type == "MaxRatio":
return {
title: $I("effectsMgr.type.resMaxRatio", [restitle]),
resName: resname,
type: "ratio"
};
default:
return 0;
}
},
statics: {
//Every effect that `effectMeta` can't derive from a resource name needs an
//entry here, or it falls through to a bare `{title: effectName}`.
/** @type {Record<string, EffectMeta>} */
effectMeta: {
// Specials meta of resources
"catnipJobRatio" : {
title: $I("effectsMgr.statics.catnipJobRatio.title"),
resName: "catnip",
type: "ratio"
},
"catnipDemandWorkerRatioGlobal": {
title: $I("effectsMgr.statics.catnipDemandWorkerRatioGlobal.title"),
resName: "catnip",
type: "ratio"
},
"woodJobRatio" : {
title: $I("effectsMgr.statics.woodJobRatio.title"),
resName: "wood",
type: "ratio"
},
"manpowerJobRatio" : {
title: $I("effectsMgr.statics.manpowerJobRatio.title"),
resName: "manpower",
type: "ratio"
},
"coalRatioGlobal" : {
title: $I("effectsMgr.statics.coalRatioGlobal.title"),
resName: "coal",
type: "ratio",
calculation: "nonProportional"
},
"coalRatioGlobalReduction" : {
title: $I("effectsMgr.statics.coalRatioGlobalReduction.title"),
resName: "coal",
type: "ratio"
},
"oilReductionRatio" : {
title: $I("effectsMgr.statics.oilReductionRatio.title"),
type: "ratio"
},
"catpowerReductionRatio" : {
title: $I("effectsMgr.statics.catpowerReductionRatio.title"),
type: "ratio"
},
"embassiesPerAmbassadorSlot": {
type: "hidden"
},
//kittens
"maxKittens" : {
title: $I("effectsMgr.statics.maxKittens.title")
},
"maxKittensRatio" : {
title: $I("effectsMgr.statics.maxKittensRatio.title"),
type: "ratio"
},
"simScalingRatio" : {
title: $I("effectsMgr.statics.simScalingRatio.title"),
type: "ratio"
},
"antimatterProduction": {
title: $I("effectsMgr.statics.antimatterProduction.title"),
type: "perYear"
},
"temporalFluxProduction": {
title: $I("effectsMgr.statics.temporalFluxProduction.title"),
type: "perYear"
},
"temporalFluxProductionChronosphere": {
title: $I("effectsMgr.statics.temporalFluxProductionChronosphere.title"),
type: "perYear"
},
// Miscellaneous
"observatoryRatio" : {
title: $I("effectsMgr.statics.observatoryRatio.title"),
type: "ratio"
},
"magnetoBoostRatio" : {
title: $I("effectsMgr.statics.magnetoBoostRatio.title"),
resName: "oil", //this is sort of hack to prevent early spoiler on magnetos
type: "ratio"
},
"skillXP" : {
title: $I("effectsMgr.statics.skillXP.title"),
type: "perTick"
},
"refineRatio": {
title: $I("effectsMgr.statics.refineRatio.title"),
type: "ratio"
},
"craftRatio": {
title: $I("effectsMgr.statics.craftRatio.title"),
type: "ratio"
},
"happiness": {
title: $I("effectsMgr.statics.happiness.title")
},
"unhappinessRatio": {
title: $I("effectsMgr.statics.unhappinessRatio.title"),
type: "ratio"
},
"tradeRatio": {
title: $I("effectsMgr.statics.tradeRatio.title"),
type: "ratio"
},
"tradeVolume": {
title: $I("effectsMgr.statics.tradeVolume.title"),
type: "ratio"
},
"standingRatio": {
title: $I("effectsMgr.statics.standingRatio.title"),
type: "ratio"
},
//Ambassador effects
"embassyEffectCap": {
title: $I("effectsMgr.statics.embassyEffectCap.title"),
type: "ratio"
},
"tradeBlueprintChance": {
title: $I("effectsMgr.statics.tradeBlueprintChance.title"),
type: "ratio"
},
"tradeSpiceChance": {
title: $I("effectsMgr.statics.tradeSpiceChance.title"),
type: "ratio"
},
"tradeNormalResChance": {
title: $I("effectsMgr.statics.tradeNormalResChance.title"),
type: "ratio"
},
"ambassadorBoostPerRank": {
title: $I("effectsMgr.statics.jobBoostPerRank.title", [$I("village.job.ambassador")]),
type: "ratio"
},
"resStasisRatio": {
title: $I("effectsMgr.statics.resStasisRatio.title"),
type: "ratio"
},
"beaconRelicsPerDay": {
title: $I("effectsMgr.statics.beaconRelicsPerDay.title"),
type: "perDay"
},
"relicPerDay": {
title: $I("effectsMgr.statics.relicPerDay.title"),
type: "perDay"
},
"routeSpeed": {
title: $I("effectsMgr.statics.routeSpeed.title"),
type: "fixed"
},
"festivalRatio":{
title: $I("effectsMgr.statics.festivalRatio.title"),
type: "ratio"
},
"festivalArrivalRatio":{
title: $I("effectsMgr.statics.festivalArrivalRatio.title"),