Repository navigation
Expand file tree
/
Copy pathutility.js
More file actions
3344 lines (3202 loc) · 120 KB
/
Copy pathutility.js
File metadata and controls
3344 lines (3202 loc) · 120 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
//UTILITY FUNCTIONS
logDisabled = false;
logDebugDisabled = true; //there is too much in the debug log at the moment - enabling this willprobably freeze up the game!
logSubtleDisabled = true;
//capture log for debugging purposes
//modified from source: https://stackoverflow.com/questions/11403107/capturing-javascript-console-log
//note we have modified stringify to be filtered to prevent cyclic object value errors
(function () {
var oldStringify = JSON.stringify;
JSON.stringify = function (message, setNumbers=false) { //if setNumbers is true, the card's set number will be output instead of title
return oldStringify(message, function (key, val) {
//capture undefined
if (typeof val == "undefined") return "undefined";
//capture errors
if (val instanceof Error) {
return {
// Pull all enumerable properties, supporting properties on custom Errors
...val,
// Explicitly pull Error's non-enumerable properties
name: val.name,
message: val.message,
stack: val.stack,
};
}
//don't try to inspect nulls
if (val === null) return "null";
//prevent cyclic by representing rather than fully outputting card
if (setNumbers && typeof val.setNumber !== "undefined") {
return val.setNumber;
}
else if (typeof val.title !== "undefined") {
return val.title;
} else if (val == runner) return "Runner";
else if (val == corp) return "Corp";
else return val;
});
};
})();
//the stringify is necessary to snapshot the objects as they are right now, and this function increases readability
function Readablify(message) {
return JSON.stringify(message).replaceAll("\\\"",'').replaceAll("\"",'') + "\n";
}
var capturedLog = [];
(function () {
var oldLog = console.log;
console.log = function (message) {
capturedLog.push(Readablify(message));
oldLog.apply(console, arguments);
};
})();
var debugging = false;
(function () {
var oldLog = console.error;
console.error = function (message) {
capturedLog.push("ERROR: "+Readablify(message));
oldLog.apply(console, arguments);
if (debugging) debugger; //pause execution if debugging
};
})();
// Functions used to save card locations
// currently only handles a few specific locations
function ServerAddress(server) {
if (server == corp.HQ) return "corp.HQ";
if (server == corp.RnD) return "corp.RnD";
if (server == corp.archives) return "corp.archives";
for (var i=0; i<corp.remoteServers.length; i++) {
if (server == corp.remoteServers[i]) return "corp.remoteServers["+i+"]";
}
return "";
}
//returns either the location string or src (optional extra parameter for debugging)
function LocationStringIfRelevant(src,cardprop="") {
if (src.cardLocation)
{
var idx = -1;
//check host
if (src.host) {
idx = src.host.hostedCards.indexOf(src);
if (idx > -1) return LocationStringIfRelevant(src.host)+".hostedCards["+idx+"]";
}
//list of locations:
var locations = [
{ ary: removedFromGame, str:"removedFromGame" },
{ ary: runner.rig.programs, str:"runner.rig.programs" },
{ ary: runner.rig.hardware, str:"runner.rig.hardware" },
{ ary: runner.rig.resources, str:"runner.rig.resources" },
{ ary: runner.grip, str:"runner.grip" },
{ ary: runner.heap, str:"runner.heap" },
{ ary: runner.stack, str:"runner.stack" },
{ ary: runner.scoreArea, str:"runner.scoreArea" },
{ ary: corp.scoreArea, str:"corp.scoreArea" },
{ ary: corp.archives.cards, str:"corp.archives.cards" },
{ ary: corp.archives.root, str:"corp.archives.root" },
{ ary: corp.archives.ice, str:"corp.archives.ice" },
{ ary: corp.HQ.cards, str:"corp.HQ.cards" },
{ ary: corp.HQ.root, str:"corp.HQ.root" },
{ ary: corp.HQ.ice, str:"corp.HQ.ice" },
{ ary: corp.RnD.cards, str:"corp.RnD.cards" },
{ ary: corp.RnD.root, str:"corp.RnD.root" },
{ ary: corp.RnD.ice, str:"corp.RnD.ice" },
];
//add remote servers to list
for (var i=0; i<corp.remoteServers.length; i++) {
locations.push({ ary: corp.remoteServers[i].root, str:"corp.remoteServers["+i+"].root" });
locations.push({ ary: corp.remoteServers[i].ice, str:"corp.remoteServers["+i+"].ice" });
}
//check all and return if found
for (var i=0; i<locations.length; i++) {
if (src.cardLocation == locations[i].ary) {
idx = src.cardLocation.indexOf(src);
if (idx > -1) return locations[i].str+"["+idx+"]";;
}
}
}
if (src.isCard) {
//report unsupported
if (cardprop != "") console.error("Converting "+cardprop+"="+src.title+" to string not supported");
else console.error("Converting property="+src.title+" to string not supported");
}
return src;
}
//non-save properties (engine properties)
const replicationCodeBlacklist = [
"isCard",
"frontTexture",
"renderer",
"cardLocation",
"setNumber",
"canBeAdvanced", //this is automatically set on install for agendas
"subTypes", //this should not change at runtime (blacklist is quicker than a full elementwise check)
//on-card properties to ignore (this assumes they will be constant...)
"abilities",
"subroutines",
];
//will return value as string, or return "" (and optionally throw an error)
//optional cardprop parameter for debugging
function ValueToString(val,reportErrors=false,prop="",cardprop="") {
if (typeof val == "object") {
//currently only accepted objects are null, player, card, server, array
if (val === null) {
return "null";
}
else if (val == runner) {
return "runner";
}
else if (val == corp) {
return "corp";
}
else if (val.isCard) {
return LocationStringIfRelevant(val,cardprop);
}
else if (val.isServer) {
return ServerAddress(val);
}
else if (Array.isArray(val)) {
//currently only specific things are saved in arrays
//could allow more by using some of this code recursively
var ret = "[";
val.forEach(function(item) {
ret += ValueToString(item, true, prop, cardprop); //report errors
ret += ",";
});
ret += "]";
return ret;
}
}
else {
if (typeof val == "boolean") return val==true?"true":"false";
else if (typeof val == "number") return ""+val;
else if (typeof val == "string") return '"'+val.replace(/"/g,'\\"')+'"';
}
if (reportErrors) {
console.log(val);
var propstr = "";
if (prop) propstr=" (."+prop+")";
console.error("Value above"+propstr+" is unsupported in ValueToString.");
}
return "";
}
//will return card property as string, or ""
function CardPropertyToString(card, prop, blacklist) {
var ret = "";
//no need to save functions
if (typeof card[prop] != "function") {
//no need to save values that are same as card definition
if (typeof card.cardDefinition[prop] != 'undefined') {
if (card[prop] === card.cardDefinition[prop]) return ret;
}
//no need to save certain properties
if (!blacklist.includes(prop)) {
return ValueToString(card[prop],false,prop,card.title+"."+prop);
}
}
return ret;
}
// Function used to automatically create replication code (src is an array, str is the string of its location array)
function ReplicationCode(src,str) {
var ret = "";
for (var j=0; j<src.length; j++) {
var card = src[j];
var addr = str+'['+j+']';
var handledProps = [];
//corp information-related properties
if (card.player == corp && !runner.scoreArea.includes(card)) {
if (card.rezzed) {
card.knownToRunner = false; //no need for both to be set
ret += addr+".rezzed=true;\n";
}
else if (card.faceUp) {
card.knownToRunner = false; //no need for both to be set
ret += addr+".faceUp=true;\n";
}
else if (card.knownToRunner) ret += addr+".knownToRunner=true;\n";
//don't autoprop save these properties
handledProps.push("rezzed");
handledProps.push("faceUp");
handledProps.push("knownToRunner");
}
//runner special handled properties
else if (card.player == runner || runner.scoreArea.includes(card)) {
if (card.faceUp) {
//assumed face up already
if (!runner.rig.programs.includes(card)
&& !runner.rig.hardware.includes(card)
&& !runner.rig.resources.includes(card)
&& !runner.scoreArea.includes(card)
&& !runner.heap.includes(card))
ret += addr+".faceUp=true;\n";
handledProps.push("knownToRunner");
}
//don't autoprop save it
handledProps.push("faceUp");
}
//counters
for (var i = 0; i < counterList.length; i++) {
if (!handledProps.includes(counterList[i])) {
if (typeof card[counterList[i]] !== "undefined") {
if (card[counterList[i]] != 0) ret += addr+"."+counterList[i]+"="+card[counterList[i]]+";\n";
}
//don't autoprop save counters
handledProps.push(counterList[i]);
}
}
//resettable properties
for (var i = 0; i < cardPropertyResets.length; i++) {
var propName = cardPropertyResets[i].propertyName;
if (!handledProps.includes(propName)) {
if (typeof card[propName] !== "undefined") {
if (card[propName] != cardPropertyResets[i].defaultValue) ret += addr+"."+propName+"="+LocationStringIfRelevant(card[propName],card.title+"."+propName)+";\n";
}
//don't autoprop save resettables
handledProps.push(propName);
}
}
//hosted cards
if (card.hostedCards && !handledProps.includes("hostedCards")) {
ret += addr+".hostedCards = [];\n";
for (var i=0; i<card.hostedCards.length; i++) {
ret += "InstanceCardsPush("+card.hostedCards[i].setNumber+","+addr+".hostedCards,1,cardBackTextures"+PlayerName(card.hostedCards[i].player)+",glowTextures,strengthTextures)[0].host = "+addr+";\n";
}
ret += ReplicationCode(card.hostedCards,addr+".hostedCards");
//don't autoprop save hostedCards
handledProps.push("hostedCards");
}
//autoprop saving
var blacklist = replicationCodeBlacklist.concat(handledProps);
if (card.isCard) {
for (prop in card) {
var pts = CardPropertyToString(card, prop, blacklist);
if (pts != "") {
ret += addr+"."+prop+"="+pts+";\n";
}
}
}
else {
console.log(card);
console.error("trying to autoprop save non-card above");
}
}
return ret;
}
//make board state fairly easy to reproduce (not comprehensive yet, just a starting point)
function ReproductionCode(full=false) {
var ret = "";
//Runner:
var runnerHeap = JSON.stringify(runner.heap,true);
var runnerStack = JSON.stringify(runner.stack,true);
var runnerGrip = JSON.stringify(runner.grip,true);
var runnerInstalled = JSON.stringify(runner.rig.resources.concat(runner.rig.hardware).concat(runner.rig.programs),true);
var runnerStolen = JSON.stringify(runner.scoreArea,true);
ret += "RunnerTestField("+runner.identityCard.setNumber+", "+[runnerHeap,runnerStack,runnerGrip,runnerInstalled,runnerStolen].join(', ')+", cardBackTexturesRunner,glowTextures,strengthTextures);\n";
//for Ayla, set aside cards
if (runner.identityCard.setAsideCards) {
var card = runner.identityCard;
var addr = "runner.identityCard";
ret += addr+".setAsideCards = [];\n";
for (var i=0; i<card.setAsideCards.length; i++) {
ret += "InstanceCardsPush("+card.setAsideCards[i].setNumber+","+addr+".setAsideCards,1,cardBackTextures"+PlayerName(card.setAsideCards[i].player)+",glowTextures,strengthTextures)[0].host = "+addr+";\n";
}
ret += ReplicationCode(card.setAsideCards,addr+".setAsideCards");
}
//now Corp:
var corpArchivesCards = JSON.stringify(corp.archives.cards,true);
var corpRndCards = JSON.stringify(corp.RnD.cards,true);
var corpHQCards = JSON.stringify(corp.HQ.cards,true);
var corpArchivesInstalled = JSON.stringify(corp.archives.root.concat(corp.archives.ice),true);
var corpRnDInstalled = JSON.stringify(corp.RnD.root.concat(corp.RnD.ice),true);
var corpHQInstalled = JSON.stringify(corp.HQ.root.concat(corp.HQ.ice),true);
var corpRemotesEach = [];
for (var i=0; i<corp.remoteServers.length; i++) {
corpRemotesEach.push(JSON.parse(JSON.stringify(corp.remoteServers[i].root.concat(corp.remoteServers[i].ice),true)));
}
var corpRemotes = JSON.stringify(corpRemotesEach,true); //the true isn't needed here but will keep it for visual consistency
var corpScored = JSON.stringify(corp.scoreArea,true);
ret += "CorpTestField("+corp.identityCard.setNumber+", "+[corpArchivesCards,corpRndCards,corpHQCards,corpArchivesInstalled,corpRnDInstalled,corpHQInstalled,corpRemotes,corpScored].join(', ')+", cardBackTexturesCorp,glowTextures,strengthTextures);\n";
//now that all the cards have been created, we can set properties
//runner arrays
ret += ReplicationCode(runner.scoreArea,'runner.scoreArea');
ret += ReplicationCode(runner.grip,'runner.grip');
ret += ReplicationCode(runner.stack,'runner.stack');
ret += ReplicationCode(runner.heap,'runner.heap');
ret += ReplicationCode(runner.rig.resources,'runner.rig.resources');
ret += ReplicationCode(runner.rig.hardware,'runner.rig.hardware');
ret += ReplicationCode(runner.rig.programs,'runner.rig.programs');
if (runner.identityCard.setAsideCards) ret += ReplicationCode(runner.identityCard.setAsideCards,'runner.identityCard.setAsideCards');
//corp arrays
ret += ReplicationCode(corp.scoreArea,'corp.scoreArea');
ret += ReplicationCode(corp.archives.root,'corp.archives.root');
ret += ReplicationCode(corp.archives.ice,'corp.archives.ice');
ret += ReplicationCode(corp.archives.cards,'corp.archives.cards');
ret += ReplicationCode(corp.RnD.root,'corp.RnD.root');
ret += ReplicationCode(corp.RnD.ice,'corp.RnD.ice');
ret += ReplicationCode(corp.RnD.cards,'corp.RnD.cards');
ret += ReplicationCode(corp.HQ.root,'corp.HQ.root');
ret += ReplicationCode(corp.HQ.ice,'corp.HQ.ice');
ret += ReplicationCode(corp.HQ.cards,'corp.HQ.cards');
for (var i=0; i<corp.remoteServers.length; i++) {
ret += ReplicationCode(corp.remoteServers[i].root,'corp.remoteServers['+i+'].root');
ret += ReplicationCode(corp.remoteServers[i].ice,'corp.remoteServers['+i+'].ice');
if (typeof corp.remoteServers[i].AISuccessfulRuns !== 'undefined') ret += "corp.remoteServers["+i+"].AISuccessfulRuns="+corp.remoteServers[i].AISuccessfulRuns+";\n";
}
//and now other properties
if (typeof corp.archives.AISuccessfulRuns !== 'undefined') ret += "corp.archives.AISuccessfulRuns="+corp.archives.AISuccessfulRuns+";\n";
if (typeof corp.RnD.AISuccessfulRuns !== 'undefined') ret += "corp.RnD.AISuccessfulRuns="+corp.RnD.AISuccessfulRuns+";\n";
if (typeof corp.HQ.AISuccessfulRuns !== 'undefined') ret += "corp.HQ.AISuccessfulRuns="+corp.HQ.AISuccessfulRuns+";\n";
if (runner.AI && typeof runner.AI.suspectedHQCards !== 'undefined') {
ret += "if (runner.AI) runner.AI.suspectedHQCards = [";
for (var i=0; i<runner.AI.suspectedHQCards.length; i++) {
ret += "{title:'"+runner.AI.suspectedHQCards[i].title+"',cardType:'"+runner.AI.suspectedHQCards[i].cardType+"',copies:"+runner.AI.suspectedHQCards[i].copies+",uncertainty:"+runner.AI.suspectedHQCards[i].uncertainty+"},";
}
ret += "];\n";
}
if (full || corp.badPublicity > 0) ret += "corp.badPublicity = "+corp.badPublicity+";\n";
if (full || runner.tags > 0) ret += "runner.tags = "+runner.tags+";\n";
if (full || runner.coreDamage > 0) ret += "runner.coreDamage = "+runner.coreDamage+";\n";
if (full) {
if (playerTurn == corp) ret += "playerTurn = corp;\n";
else ret += "playerTurn = runner;\n";
ret += "runner.creditPool = "+runner.creditPool+";\n";
ret += "corp.creditPool = "+corp.creditPool+";\n";
ret += "runner.clickTracker = "+runner.clickTracker+";\n";
ret += "corp.clickTracker = "+corp.clickTracker+";\n";
var phasesKeys = Object.keys(phases);
for (var i=0; i< phasesKeys.length; i++) {
if (phases[phasesKeys[i]] == currentPhase) ret += "ChangePhase(phases."+phasesKeys[i]+"); ";
}
ret += "//"+currentPhase.title+"\n";
}
return ret;
}
//Helper for rendering auto-continue button
function AutoContinueButtonStr() {
var boxChar = "☑";
if (!autoContinue) boxChar = "☐";
return "Auto skip "+boxChar;
}
function AutoContinueButtonHTML(showEvenIfOff=false) {
if ( (!autoContinue && !showEvenIfOff) || (runner.AI && corp.AI) || (specifiedMentor != "") ) return "";
return '<button style="font-size:80%; position:fixed; left:100%; top:-6px; height:67px;" id="autocontinue" title="Automatically continue" class="button autocontinue" onclick="autoContinue = !autoContinue; autoContinueTimer=0.0; $(\'#autocontinue\').html(AutoContinueButtonStr());">'+AutoContinueButtonStr()+'</button>';
}
// Function to download capturedlog to a file
//source: https://stackoverflow.com/questions/13405129/javascript-create-and-save-file
function DownloadCapturedLog() {
//reveal hidden information
var extraOutput = "\nSPOILER: Contents of remote servers:\n";
for (var i=0; i<corp.remoteServers.length; i++) {
extraOutput += "SPOILER: "+ServerName(corp.remoteServers[i])+": "+Readablify(corp.remoteServers[i].root);
}
extraOutput += "\n"+ReproductionCode(debugging);
var verdate = new Date(versionReference * 1000);
extraOutput += "\nVersion reference: "+verdate.toString();
//send extra output and log
var logOutput = capturedLog.concat(extraOutput);
var file = new Blob(logOutput, { type: "" }); //blank string means text/plain
var d = new Date();
var n = d.toISOString();
var filename = "chiriboga-log-" + n + ".txt";
if (window.navigator.msSaveOrOpenBlob)
// IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else {
// Others
var a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
}
//function to narrate the stackedLog and then, if specified, call a function
//returns false if stacked log is empty or narration is off
let stackedLog = [];
function Narrate() {
if ( ($('#narration').prop('checked')) && (stackedLog.length > 0) ) {
let src = stackedLog.join(', ');
stackedLog = [];
//parse stacked log for more natural language
//Corp
src = src.replace(/Corp spent(.*?), Corp spent (\S*)/gm, function(match, p1, p2, offset, string) {
return "Corp spent"+p1+" and "+p2;
});
src = src.replace(/Corp spent(.*?), Played/gm, function(match, p1, offset, string) {
return "Corp spent"+p1+" to play";
});
src = src.replace(/Corp spent(.*?), Card advanced/gm, function(match, p1, offset, string) {
return "Corp spent"+p1+" to advance a card";
});
src = src.replace(/Corp spent(.*?), Corp (\S*)/gm, function(match, p1, p2, offset, string) {
let output = "Corp spent"+p1+" to ";
if (p2=='gained') output+='gain';
else if (p2=='drew') output+='draw';
else if (p2=='installed') output+='install';
else if (p2=='rezzed') output+='rez';
else return match; //unknown, return unmodified
return output;
});
src = src.replace(/^Corp(.*?), Corp/gm, function(match, p1, offset, string) {
return "Corp"+p1+" and";
});
//Runner
src = src.replace(/Runner spent(.*?), Runner spent (\S*)/gm, function(match, p1, p2, offset, string) {
return "Runner spent"+p1+" and "+p2;
});
src = src.replace(/Runner spent(.*?), Played/gm, function(match, p1, offset, string) {
return "Runner spent"+p1+" to play";
});
src = src.replace(/Runner spent(.*?), Runner (\S*)/gm, function(match, p1, p2, offset, string) {
let output = "Runner spent"+p1+" to ";
if (p2=='gained') output+='gain';
else if (p2=='drew') output+='draw';
else if (p2=='installed') output+='install';
return output;
});
src = src.replace(/Runner spent(.*?), Run initiated attacking/gm, function(match, p1, offset, string) {
return "Runner spent"+p1+" to run";
});
src = src.replace(/^Runner(.*?), Runner/gm, function(match, p1, offset, string) {
return "Runner"+p1+" and";
});
//Both corp and runner
src = src.replace(/ to(.*?) to/gm, function(match, p1, offset, string) {
return " to"+p1+" and";
});
src = src.replace(/Remote [0-9]/gm, function(match, offset, string) {
return "remote server";
});
src = src.replace(/([0]|[2-9])\[c\]/gm, function(match, p1, offset, string) {
return p1+" credits";
});
src = src.replace(/1\[c\]/gm, function(match, offset, string) {
return "one credit";
});
src = src.replace(/spent(.*), ([0-9]*) (credit|credits) taken/gm, function(match, p1, p2, p3, offset, string) {
return "spent"+p1+" to take "+p2+" "+p3;
});
src = src.replace(/spent(.*), ([0-9]*) (credit|credits) placed/gm, function(match, p1, p2, p3, offset, string) {
return "spent"+p1+" to place "+p2+" "+p3;
});
//replace words that don't sound right
src = src.replaceAll('rezzed','rezd');
src = src.replaceAll('Whitespace','white space');
src = src.replaceAll('Esâ Afontov','essa ahfontuf');
src = src.replaceAll('Begemot','beggemott');
src = src.replaceAll('Avgustina Ivanovskaya','avgusteena eevahnoffskahya');
//replace unspeakable characters with unaccented letters
src = src.normalize('NFD');
//now speak
let utterance = new SpeechSynthesisUtterance(src);
utterance.lang = 'en-US';
utterance.onend = Main;
speechSynthesis.speak(utterance);
return true;
}
return false;
}
/**
* Outputs a standard style message to the console and ends with carriage return.
*
* @method Log
* @param {String} src text to output
*/
function Log(src) {
if (logDisabled) return;
//$("#output").append(src+"<br/>");
//window.scrollTo(0,Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight ) - window.innerHeight);
console.log(src);
$("#history")
.children()
.first()
.children("pre")
.first()
.append("<br/>" + Iconify(src));
if (activePlayer) {
if ( $('#narration').prop('checked') && ( activePlayer.AI || accessibilityMode == "text" ) ) stackedLog.push(src); //only narrate AI player
}
}
/**
* Convert specific strings into icons in the given text.
*
* @method Iconify
* @param {String} src text to iconify
* @param [Boolean] black true for black (otherwise white)
* @returns {String} html output
*/
function Iconify(src, black = false) {
var colorStr = "";
if (black) colorStr = "_black";
var ret = (" " + src).slice(1); //deep copy (don't modify original string)
ret = ret.replace(
/temporary credits/g,
'temporary <img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/\[c\]/g,
'<img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/five credits/g,
'5<img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/ credits/g,
'<img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/one credit/g,
'1<img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/ credit/g,
'<img src="images/NISEI_CREDIT' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/\[click\]/g,
'<img src="images/NISEI_CLICK' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/1 click/g,
'<img src="images/NISEI_CLICK' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/one click/g,
'<img src="images/NISEI_CLICK' +
colorStr +
'.png" class="icon" height="16"/>'
);
ret = ret.replace(
/\[trash\]/g,
'<img src="images/NISEI_TRASH' +
colorStr +
'.png" class="icon" height="16"/>'
);
return ret;
}
/**
* Outputs a error message to the console and ends with carriage return.
*
* @method LogError
* @param {String} src error text to output
*/
function LogError(src) {
//Log('<span class="error">Error: '+src+'</span>');
console.error(src);
}
/**
* Get the title of a card. Use this instead of .title directly.<br/>If hideHidden is true, returns [hidden card] if not known to viewingPlayer.
*
* @method GetTitle
* @param {Card} card card to get title of
* @param {Boolean} card card to get title of
* @returns {String} the title
*/
function GetTitle(card, hideHidden) {
var hideTitle = false;
if (hideHidden) {
if (!PlayerCanLook(viewingPlayer, card)) hideTitle = true;
}
//text mode behaviour
if (accessibilityMode == "text") {
var ret = "";
if (hideTitle) ret += "hidden card";
else ret += card.title;
if (CheckInstalled(card)) {
var serv = GetServer(card);
if (CheckCardType(card, ["ice"])) ret += " protecting "+ServerName(serv)+" at position "+serv.ice.indexOf(card);
}
return ret;
}
//default behaviour below
if (hideTitle) return "[hidden card]";
return card.title; //the only time in code that card.title should be found (otherwise use GetTitle(card,true) or GetTitle(card)
}
/**
* Get the distinct cards in an option list (ignoring items which have .card undefined or null)
*
* @method CardsInOptionList
* @param {Params[]} src option list to get cards from
* @returns {Card[]} list of cards from the list
*/
function CardsInOptionList(src) {
var ret=[];
src.forEach(function(item){
if (item.card) {
if (!ret.includes(item.card)) ret.push(item.card);
}
});
return ret;
}
/**
* Create a new server object.<br/>Used during initialisation and for creating remote servers.
*
* @method NewServer
* @param {String} nameStr used when printing log messages
* @param {Boolean} isCentral determines whether the server should have a .cards array
* @returns {Server} the new server
*/
function NewServer(nameStr, isCentral) {
var newServer = {};
newServer.isServer = true;
if (isCentral) {
newServer.cards = [];
}
newServer.root = [];
newServer.ice = [];
newServer.serverName = nameStr;
return newServer;
}
/**
* Get the name of a server.<br/>If ignoreRemoteNumbers is true, returns "a remote server" for remotes.<br/>Returns "a new remote server" if server is null.
*
* @method ServerName
* @param {Server} server to get name of
* @param {Boolean} ignoreRemoteNumbers set false to include remote number
* @param {Boolean} definite set false to write remotes as "a remote server"
* @returns {String} the server name
*/
function ServerName(server, ignoreRemoteNumbers = false, definite = false) {
if (server !== null) {
if (typeof server.cards == "undefined") {
//i.e. is remote
if (ignoreRemoteNumbers) {
if (definite) return "Remote";
else return "a remote server";
}
}
return server.serverName;
}
if (definite) return "New Remote";
return "a new remote server";
}
/**
* Get the name of a card's server.<br/>If ignoreRemoteNumbers is true, returns "a remote server" for remotes.<br/>Returns "a new remote server" if server is null.
*
* @method CardServerName
* @param {Card} card card to get name of
* @param {Boolean} ignoreRemoteNumbers set false to include remote number
* @returns {String} the server name
*/
function CardServerName(card, ignoreRemoteNumbers = false) {
return ServerName(GetServer(card), ignoreRemoteNumbers);
}
/**
* Check if a card is in an array.<br/>Returns true if found there, false otherwise.
*
* @method CardIsInArray
* @param {Card} card card to check
* @param {Card[]} array array of cards to check
* @returns {Boolean} true if found there, false otherwise
*/
function CardIsInArray(card, array) {
for (var i = 0; i < array.length; i++) {
if (array[i] == card) return true;
}
return false;
}
/**
* Get the server a card is installed in/in front of.<br/>Returns null if not found in a server, or is in R&D/HQ/Archives.cards (i.e. not installed).
*
* @method GetServer
* @param {Card} card card to find server of
* @returns {Server} the server or null
*/
function GetServer(card) {
//warning: in theory it's possible for cardLocation value to not match actual location (if card moved by method other than MoveCard)
var prop = "root";
if (card.cardType == "ice") prop = "ice";
var serverArrays = [];
serverArrays.push({server:corp.archives, array:corp.archives[prop]});
serverArrays.push({server:corp.HQ, array:corp.HQ[prop]});
serverArrays.push({server:corp.RnD, array:corp.RnD[prop]});
for (var i=0; i<corp.remoteServers.length; i++) {
serverArrays.push({server:corp.remoteServers[i], array:corp.remoteServers[i][prop]});
}
for (var i=0; i<serverArrays.length; i++) {
if (card.cardLocation == serverArrays[i].array) return serverArrays[i].server;
}
return null;
}
/**
* Get the server an array belongs to.<br/>Returns null if does not belong to a server (or server is destroyed).
*
* @method GetServerByArray
* @param {Card[]} array array to find server of
* @returns {Server} the server or null
*/
function GetServerByArray(src) {
//check roots
for (var i = 0; i < corp.remoteServers.length; i++) {
if (src == corp.remoteServers[i].root) return corp.remoteServers[i];
}
if (src == corp.RnD.root) return corp.RnD;
if (src == corp.HQ.root) return corp.HQ;
if (src == corp.archives.root) return corp.archives;
//and ice
if (src == corp.RnD.ice) return corp.RnD;
if (src == corp.HQ.ice) return corp.HQ;
if (src == corp.archives.ice) return corp.archives;
for (var i = 0; i < corp.remoteServers.length; i++) {
if (src == corp.remoteServers[i].ice) return corp.remoteServers[i];
}
//and cards
if (src == corp.RnD.cards) return corp.RnD;
if (src == corp.HQ.cards) return corp.HQ;
if (src == corp.archives.cards) return corp.archives;
return null;
}
/**
* Get either the ice being encountered/approached or, if different, an ice having subroutines chosen
*
* @method GetMostRelevantIce()
* @returns {Card} card or null
*/
function GetMostRelevantIce() {
for (var i = 0; i < validOptions.length; i++) {
//ignore options rendered as a button
if (typeof validOptions[i].button === "undefined") {
if (typeof validOptions[i].subroutine !== "undefined") {
if (validOptions[i].card) return validOptions[i].card; //just return the first found
}
}
}
//no ice having subroutines chosen, look for approach/encounter ice
return GetApproachEncounterIce();
}
/**
* Get the currently approached/encountered ice, or if in movement phase from it.<br/>Returns card or null.
*
* @method GetApproachEncounterIce
* @returns {Card} card or null
*/
function GetApproachEncounterIce() {
if (approachIce < 0) return null;
if (attackedServer == null) return null;
if (approachIce > attackedServer.ice.length - 1) return null;
return attackedServer.ice[approachIce];
}
/**
* Check whether the available options are a list of unique servers.<br/>Returns true or false.
*
* @method OptionsAreOnlyUniqueServers
* @returns {Boolean} true or false
*/
function OptionsAreOnlyUniqueServers() {
if (validOptions.length < 1) return false;
//maybe we can use click-to-choose servers - to do so all must have server set and each be unique
var uniqueServers = [];
var numButtons = 0;
for (var i = 0; i < validOptions.length; i++) {
if (typeof validOptions[i].button !== "undefined") {
//not relevant, rendered as a button
numButtons++;
continue;
}
if (typeof validOptions[i].server === "undefined") return false;
if (uniqueServers.includes(validOptions[i].server)) return false;
uniqueServers.push(validOptions[i].server);
}
//don't use click-to-choose-server if all options are buttons (the buttons are there for a reason!)
if (numButtons == validOptions.length) return false;
return true;
}
/**
* Check whether the available options are a list of unique subroutines.<br/>Returns true or false.
*
* @method OptionsAreOnlyUniqueSubroutines
* @returns {Boolean} true or false
*/
function OptionsAreOnlyUniqueSubroutines() {
if (validOptions.length < 1) return false;
//maybe we can use click-to-choose subroutines - to do so all must have .subroutine set and each be unique and on the same card
var cardSpecified = null;
var uniqueSubroutines = [];
for (var i = 0; i < validOptions.length; i++) {
if (typeof validOptions[i].button !== "undefined") continue; //not relevant, rendered as a button
if (typeof validOptions[i].subroutine === "undefined") return false;
if (typeof validOptions[i].card) {
if (!cardSpecified) cardSpecified = validOptions[i].card;
else if (cardSpecified != validOptions[i].card) return false; //more than one card specified
}
if (uniqueSubroutines.includes(validOptions[i].subroutine)) return false;
uniqueSubroutines.push(validOptions[i].subroutine);
}
if (uniqueSubroutines.length > 0) return true;
return false; //no unique subroutines
}
/**
* Check whether the mouse is over a given server.<br/>Returns true or false.
*
* @method MouseIsOverServer
* @param {Server} server the server to check
* @returns {Boolean} true or false
*/
function MouseIsOverServer(server) {
var mousePos = cardRenderer.MousePosition();
var y = mousePos.y;
if (y < pixi_playY) return false;
var x = mousePos.x;
if (x == 0) {
if (y == 0) return false; //prevent glitch on touch devices
}
if (server == null) {
//install in new remote - only valid if not hovering past the other servers > remoteServers[highest].xEnd
var largestServerX = corp.HQ.xEnd;
if (corp.remoteServers.length > 0)
largestServerX = corp.remoteServers[corp.remoteServers.length - 1].xEnd;
if (x > largestServerX && x < largestServerX + 300) return true;
} else if (server == corp.archives) {
if (x < corp.RnD.xStart) return true;
} //other specific server - must hover over it
else {
if (x > server.xStart && x < server.xEnd) return true;
}
return false;
}
/**
* Check whether the server is in validOptions.<br/>Returns true or false.
*
* @method ServerIsValidOption
* @param {Server} server the server to check
* @returns {Boolean} true or false
*/
function ServerIsValidOption(server) {
for (var i = 0; i < validOptions.length; i++) {
if (typeof validOptions[i].server !== "undefined") {
if (validOptions[i].server == server) {
//a card may be required too
if (typeof validOptions[i].card !== "undefined") {
if (validOptions[i].card.renderer.sprite.dragging) return true;
} else return true; //no card requirement, go for it!
}
}
}
return false;
}
/**
* Check whether the card is a host in validOptions.<br/>Returns true or false.
*
* @method CardIsValidHostOption
* @param {card} card the card to check
* @returns {Boolean} true or false
*/
function CardIsValidHostOption(card) {
for (var i = 0; i < validOptions.length; i++) {
if (typeof validOptions[i].host !== "undefined") {
if (validOptions[i].host == card) {
//a card is required too (the one being dragged must be one this card can host)
if (typeof validOptions[i].card !== "undefined") {
if (validOptions[i].card.renderer.sprite.dragging) return true;
}
}
}
}
return false;
}
/**
* Get active player name.
*
* @method PlayerName
* @param {Player} player either corp or runner
* @returns {String} "Corp", "Runner", or "ERROR"
*/
function PlayerName(player) {
var plstr = "ERROR";
if (player == corp) plstr = "Corp";
else if (player == runner) plstr = "Runner";
return plstr;
}
/**
* Player wins the game (the game ends).<br/>Logs a message and disables command prompt.
*
* @method PlayerWin
* @param {Player} player either corp or runner
* @param {String} msgstr reason for win
*/
function PlayerWin(player, msgstr) {
//old code from before there was a decisionphase
/*
$("#cmdform").hide();
window.clearTimeout(mainLoop);
*/
var winner = player;
var winnerMessage = "";
if (winner == corp) winnerMessage = "Corp wins";
else winnerMessage = "Runner wins";
var winPhase = {
Enumerate: {},
Resolve: {},
player: viewingPlayer,
title: winnerMessage,
instruction: "Game Over",
historyBreak: { title: "Game Over", style: "small" },
requireHumanInput: true,
};
winPhase.Enumerate["play again"] = function () {
if (debugging && runner.AI && corp.AI) alert("Game completed");
return [{}];