-
Notifications
You must be signed in to change notification settings - Fork 14
/
dominion.js
1379 lines (1195 loc) · 40 KB
/
dominion.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
// For players who have spaces in their names, a map from name to name
// rewritten to have underscores instead. Pretty ugly, but it works.
var player_rewrites = new Object();
// Map from player name to Player object.
var players = new Object();
// Regular expression that is an OR of players other than "You".
var player_re = "";
// Count of the number of players in the game.
var player_count = 0;
// Places to print number of cards and points.
var deck_spot;
var points_spot;
var started = false;
var introduced = false;
var i_introduced = false;
var disabled = false;
var had_error = false;
var show_action_count = false;
var show_unique_count = false;
var show_victory_count = false;
var show_duchy_count = false;
var possessed_turn = null;
var announced_error = false;
// Enabled by debugger when analyzing game logs.
var debug_mode = false;
var last_player = null;
var last_reveal_player = null;
var last_reveal_card = null;
// TODO(drheld): Remove this.
// Hack currently needed due to lack of info with embargo + trader.
var turn_gain_cards = [];
var turn_number = 0;
// Queued up events in the first turn only.
var to_process = [];
// Last time a status message was printed.
var last_status_print = 0;
// Track scoping to know currently "active" player.
var scopes = [];
// The version of the extension currently loaded.
var extension_version = 'Unknown';
var restoring_log = false;
var ignore_events = false;
// Quotes a string so it matches literally in a regex.
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
// Returns an html encoded version of a string.
function htmlEncode(value){
return $('<div/>').text(value).html();
}
// Keep a map from plural to singular for cards that need it.
var plural_map = {};
for (var i = 0; i < card_list.length; ++i) {
var card = card_list[i];
if (card['Plural'] != card['Singular']) {
plural_map[card['Plural']] = card['Singular'];
}
}
function debugString(thing) {
return JSON.stringify(thing);
}
function rewriteName(name) {
return name.replace(/ /g, "_").replace(/'/g, "’").replace(/\./g, "۔").
replace(/\|/g, "¦");
}
function handleError(text) {
console.log(text);
if (!had_error) {
had_error = true;
alert("Point counter error. Results may no longer be accurate: " + text);
}
}
function getSayButton() {
var blist = document.getElementsByTagName('button');
for (var button in blist) {
if (blist[button].innerText == "Say") {
return blist[button];
}
}
return null;
}
function writeText(text) {
// Get the fields we need for being able to write text.
var input_box = document.getElementById("entry");
var say_button = getSayButton();
if (input_box == null || input_box == undefined || !say_button) {
handleError("Can't write text -- button or input box is unknown.");
return;
}
var old_input_box_value = input_box.value;
input_box.value = text;
say_button.click();
input_box.value = old_input_box_value;
}
function maybeAnnounceFailure(text) {
if (!disabled && !announced_error) {
console.log("Logging error: " + text);
writeText(text);
}
announced_error = true;
}
function pointsForCard(card_name) {
if (card_name == undefined) {
handleError("Undefined card for points...");
return 0;
}
if (card_name.indexOf("Colony") == 0) return 10;
if (card_name.indexOf("Province") == 0) return 6;
if (card_name.indexOf("Duchy") == 0) return 3;
if (card_name.indexOf("Duchies") == 0) return 3;
if (card_name.indexOf("Estate") == 0) return 1;
if (card_name.indexOf("Curse") == 0) return -1;
if (card_name.indexOf("Island") == 0) return 2;
if (card_name.indexOf("Nobles") == 0) return 2;
if (card_name.indexOf("Harem") == 0) return 2;
if (card_name.indexOf("Great Hall") == 0) return 1;
if (card_name.indexOf("Farmland") == 0) return 2;
if (card_name.indexOf("Tunnel") == 0) return 2;
return 0;
}
function Player(name, original_name) {
this.name = name;
this.original_name = original_name;
this.score = 3;
this.deck_size = 10;
// Map from special counts (such as number of gardens) to count.
this.special_counts = { "Treasure" : 7, "Victory" : 3, "Uniques" : 2 };
this.card_counts = { "Copper" : 7, "Estate" : 3 };
this.getScore = function() {
var score_str = this.score;
var total_score = this.score;
if (this.card_counts["Gardens"] != undefined) {
var gardens = this.card_counts["Gardens"];
var garden_points = Math.floor(this.deck_size / 10);
score_str = score_str + "+" + gardens + "g@" + garden_points;
total_score = total_score + gardens * garden_points;
}
if (this.card_counts["Silk Road"] != undefined) {
var silk_roads = this.card_counts["Silk Road"];
var silk_road_points = 0;
if (this.special_counts["Victory"] != undefined) {
silk_road_points = Math.floor(this.special_counts["Victory"] / 4);
}
score_str = score_str + "+" + silk_roads + "s@" + silk_road_points;
total_score = total_score + silk_roads * silk_road_points;
}
if (this.card_counts["Duke"] != undefined) {
var dukes = this.card_counts["Duke"];
var duke_points = 0;
if (this.card_counts["Duchy"] != undefined) {
duke_points = this.card_counts["Duchy"];
}
score_str = score_str + "+" + dukes + "d@" + duke_points;
total_score = total_score + dukes * duke_points;
}
if (this.card_counts["Vineyard"] != undefined) {
var vineyards = this.card_counts["Vineyard"];
var vineyard_points = 0;
if (this.special_counts["Actions"] != undefined) {
vineyard_points = Math.floor(this.special_counts["Actions"] / 3);
}
score_str = score_str + "+" + vineyards + "v@" + vineyard_points;
total_score = total_score + vineyards * vineyard_points;
}
if (this.card_counts["Fairgrounds"] != undefined) {
var fairgrounds = this.card_counts["Fairgrounds"];
var fairgrounds_points = 0;
if (this.special_counts["Uniques"] != undefined) {
fairgrounds_points = Math.floor(this.special_counts["Uniques"] / 5) * 2;
}
score_str = score_str + "+" + fairgrounds + "f@" + fairgrounds_points;
total_score = total_score + fairgrounds * fairgrounds_points;
}
if (total_score != this.score) {
score_str = score_str + "=" + total_score;
}
return score_str;
}
this.getDeckString = function() {
var str = this.deck_size;
var need_action_string = (show_action_count && this.special_counts["Actions"]);
var need_unique_string = (show_unique_count && this.special_counts["Uniques"]);
var need_victory_string = (show_victory_count && this.special_counts["Victory"]);
var need_duchy_string = (show_duchy_count && this.card_counts["Duchy"]);
if (need_action_string || need_unique_string || need_duchy_string || need_victory_string) {
var special_types = [];
if (need_unique_string) {
special_types.push(this.special_counts["Uniques"] + "u");
}
if (need_action_string) {
special_types.push(this.special_counts["Actions"] + "a");
}
if (need_duchy_string) {
special_types.push(this.card_counts["Duchy"] + "d");
}
if (need_victory_string) {
special_types.push(this.special_counts["Victory"] + "v");
}
str += '(' + special_types.join(", ") + ')';
}
return str;
}
this.changeScore = function(points) {
this.score = this.score + parseInt(points);
}
this.changeSpecialCount = function(name, delta) {
if (this.special_counts[name] == undefined) {
this.special_counts[name] = 0;
}
this.special_counts[name] = this.special_counts[name] + delta;
}
this.recordCards = function(name, count) {
if (this.card_counts[name] == undefined || this.card_counts[name] == 0) {
this.card_counts[name] = count;
this.special_counts["Uniques"] += 1;
} else {
this.card_counts[name] += count;
}
if (this.card_counts[name] <= 0) {
if (this.card_counts[name] < 0) {
handleError("Card count for " + name + " is negative (" + this.card_counts[name] + ")");
}
delete this.card_counts[name];
this.special_counts["Uniques"] -= 1;
}
}
this.recordSpecialCounts = function(singular_card_name, card, count) {
// Hack! Hinterlands adds reactions that are not actions. Currently there
// is no easy way to see this based on the class names. I've made a request
// to change this but for now special case them. :(
if (singular_card_name == "Tunnel") {
this.changeSpecialCount("Victory", count);
return;
}
if (singular_card_name == "Fool's Gold") {
this.changeSpecialCount("Treasure", count);
return;
}
var types = card.className.split("-").slice(1);
for (type_i in types) {
var type = types[type_i];
if (type == "none" || type == "duration" ||
type == "action" || type == "reaction") {
this.changeSpecialCount("Actions", count);
} else if (type == "curse") {
this.changeSpecialCount("Curse", count);
} else if (type == "victory") {
this.changeSpecialCount("Victory", count);
} else if (type == "treasure") {
this.changeSpecialCount("Treasure", count);
} else {
handleError("Unknown card class: " + card.className + " for " + card.innerText);
}
}
}
this.gainCard = function(card, count) {
// Hack: Border Village doesn't print well under possession.
if (possessed_turn &&
possessed_turn != this &&
turn_gain_cards[turn_gain_cards.length - 1] == "Border Village") {
possessed_turn.gainCard(card, count);
}
// You can't gain or trash cards while possessed.
if (possessed_turn && this == last_player) return;
if (debug_mode) {
$('#log').children().eq(-1).before(
'<div class="gain_debug">*** ' + name + " gains " +
count + " " + card.innerText + "</div>");
}
// Last scope should be this player.
scopes[scopes.length - 1] = this;
count = parseInt(count);
this.deck_size = this.deck_size + count;
var singular_card_name = getSingularCardName(card.innerText);
this.changeScore(pointsForCard(singular_card_name) * count);
this.recordSpecialCounts(singular_card_name, card, count);
this.recordCards(singular_card_name, count);
turn_gain_cards.push(singular_card_name);
if (getOption('show_card_counts')) {
if (!setupPerPlayerCardCounts()) {
var id = '#' + cardId(this.id, singular_card_name);
$(id).text(this.card_counts[singular_card_name]);
}
}
}
}
function stateStrings() {
var state = '';
for (var player in players) {
player = players[player];
state += '<b>' + player.name + "</b>: " +
player.getScore() + " points [deck size is " +
player.getDeckString() + "] - " +
JSON.stringify(player.special_counts) + "<br>" +
JSON.stringify(player.card_counts) + "<br>";
}
return state;
}
function getSingularCardName(name) {
if (plural_map[name] == undefined) return name;
return plural_map[name];
}
function getPlayer(name) {
if (players[name] == undefined) return null;
return players[name];
}
function createFullLog() {
// Create the visible log blob and hide the normal log part.
$('#full_log').remove();
$('#log').hide().before($('<pre id="full_log">'));
}
function maybeAddToFullLog(node) {
if (!restoring_log) {
$('#copied_temp_say').remove();
$('#full_log').append($(node).clone());
}
}
function findTrailingPlayer(text) {
var arr = text.match(/ ([^\s.]+)\.[\s]*$/);
if (arr == null) {
handleError("Couldn't find trailing player: '" + text + "'");
return null;
}
if (arr.length == 2) {
return getPlayer(arr[1]);
}
return null;
}
function maybeHandleTurnChange(node) {
var text = node.innerText;
if (text.indexOf("—") != -1) {
var maybe_number = text.match(/([0-9]+) —/);
if (maybe_number) turn_number = maybe_number[1];
var last_player_name = '';
// This must be a turn start.
if (text.match(/— Your (?:extra )?turn/)) {
last_player_name = 'You';
} else {
var arr = text.match(/— (.+)'s .*turn/);
if (arr && arr.length == 2) {
last_player_name = arr[1];
} else {
handleError("Couldn't handle turn change: " + text);
}
}
// First turn for a player. Create them.
if (turn_number == 1) {
player_count++;
// Hack: collect player names with special characters that hurt us. We'll
// rewrite them and then all the text parsing works as normal.
var original_name = last_player_name;
var rewritten = rewriteName(last_player_name);
if (rewritten != last_player_name) {
player_rewrites[htmlEncode(last_player_name)] = htmlEncode(rewritten);
last_player_name = rewritten;
maybeRewriteName(node);
}
// Initialize the player.
players[rewritten] = new Player(last_player_name, original_name);
players[rewritten].id = "player" + player_count;
// Update the regex of all other players.
var other_player_names = [];
for (player in players) {
var player = players[player];
if (player.name != "You") {
other_player_names.push(RegExp.quote(player.name));
}
player_re = '(' + other_player_names.join('|') + ')';
}
setupPerPlayerCardCounts();
}
if (turn_number == 2) {
for (item in to_process) {
processLogEntry(to_process[item]);
}
to_process = [];
}
var previous_player = last_player;
last_player = getPlayer(last_player_name);
if (last_player == null) {
console.log("Failed to get player from: " + last_player_name);
} else {
$('#full_log :last').addClass(last_player.id);
}
var is_possessed_turn = text.match(/\(possessed by .+\)/);
if (is_possessed_turn) {
possessed_turn = previous_player;
} else {
possessed_turn = null;
}
if (debug_mode) {
var details = " (" + getDecks() + " | " + getScores() + ")";
node.innerHTML.replace(" —<br>", " " + details + " —<br>");
}
turn_gain_cards = [];
return true;
}
return false;
}
function handleScoping(text_arr, text) {
// Ignore debug output.
if (text_arr[0] == "***") return;
var depth = 0;
for (var t in text_arr) {
if (text_arr[t] == "...") ++depth;
}
while (depth < scopes.length) {
scopes.pop();
}
scopes.push(getPlayer(text_arr[depth]));
}
function maybeReturnToSupply(text) {
possessed_turn_backup = possessed_turn;
possessed_turn = null;
var ret = false;
if (text.indexOf("it to the supply") != -1) {
last_player.gainCard(last_reveal_card, -1);
ret = true;
} else {
var arr = text.match("([0-9]*) copies to the supply");
if (arr && arr.length == 2) {
last_player.gainCard(last_reveal_card, -arr[1]);
ret = true;
}
}
possessed_turn = possessed_turn_backup;
return false;
}
function maybeHandleExplorer(elems, text) {
if (text.match(/gain(ing)? a (Silver|Gold) in (your )?hand/)) {
last_player.gainCard(elems[elems.length - 1], 1);
return true;
}
return false;
}
function maybeHandleMint(elems, text) {
if (elems.length != 1) return false;
if (text.match("and gain(ing)? another one.")) {
last_player.gainCard(elems[0], 1);
return true;
}
return false;
}
function maybeHandleTradingPost(elems, text) {
if (text.indexOf(", gaining a Silver in hand") == -1) {
return false;
}
if (elems.length != 2 && elems.length != 3) {
handleError("Error on trading post: " + text);
return true;
}
var elem = 0;
last_player.gainCard(elems[0], -1);
if (elems.length == 3) elem++;
last_player.gainCard(elems[elem++], -1);
last_player.gainCard(elems[elem], 1);
return true;
}
function maybeHandleSwindler(elems, text) {
var player = null;
if (text.indexOf("replacing your") != -1) {
player = getPlayer("You");
}
var arr = text.match(new RegExp("You replace " + player_re + "'s"));
if (!arr) arr = text.match(new RegExp("replacing " + player_re + "'s"));
if (arr && arr.length == 2) {
player = getPlayer(arr[1]);
}
if (player) {
if (elems.length == 2) {
// Note: no need to subtract out the swindled card. That was already
// handled by maybeHandleOffensiveTrash.
player.gainCard(elems[1], 1);
} else {
handleError("Replacement has " + elems.length + " elements: " + text);
}
return true;
}
return false;
}
function maybeHandlePirateShip(elems, text_arr, text) {
// Swallow gaining pirate ship tokens.
// It looks like gaining a pirate ship otherwise.
if (text.indexOf("a Pirate Ship token") != -1) return true;
return false;
}
function maybeHandleSeaHag(elems, text_arr, text) {
if (text.indexOf("a Curse on top of") != -1) {
if (elems < 1 || elems[elems.length - 1].innerHTML != "Curse") {
handleError("Weird sea hag: " + text);
return false;
}
getPlayer(text_arr[0]).gainCard(elems[elems.length - 1], 1);
return true;
}
return false;
}
// This can be triggered by Saboteur, Swindler, and Pirate Ship.
function maybeHandleOffensiveTrash(elems, text_arr, text) {
if (elems.length == 1) {
if (text.indexOf("is trashed.") != -1) {
last_reveal_player.gainCard(elems[0], -1);
return true;
}
if (text.indexOf("and trash it.") != -1 ||
text.indexOf("and trashes it.") != -1) {
getPlayer(text_arr[0]).gainCard(elems[0], -1);
return true;
}
if (text.match(/trashes (?:one of )?your/)) {
last_reveal_player.gainCard(elems[0], -1);
return true;
}
var arr = text.match(new RegExp("trash(?:es)? (?:one of )?" + player_re + "'s"));
if (arr && arr.length == 2) {
getPlayer(arr[1]).gainCard(elems[0], -1);
return true;
}
return false;
}
}
function maybeHandleTournament(elems, text_arr, text) {
if (elems.length == 2 && text.match(/and gains? a .+ on (the|your) deck/)) {
getPlayer(text_arr[0]).gainCard(elems[1], 1);
return true;
}
return false;
}
function maybeHandleTrader(elems, text_arr, text) {
if (elems.length == 3 && text.match(/a Trader to gain a Silver/)) {
var instead_of = getSingularCardName(elems[2].innerText);
var found = false;
for (card in turn_gain_cards) {
if (turn_gain_cards[card] == instead_of) found = true;
}
// HACK: There is no message about gaining cards sometimes. If it hasn't
// been gained this turn, assume it wasn't shown so don't lose it.
if (!found) return true;
getPlayer(text_arr[0]).gainCard(elems[2], -1);
return true;
}
return false;
}
function maybeHandleTunnel(elems, text_arr, text) {
if (elems.length == 2 && text.match(/reveals? a Tunnel and gain/)) {
getPlayer(text_arr[0]).gainCard(elems[1], 1);
return true;
}
if (elems.length == 2 && text.match(/revealing a Tunnel and gaining/)) {
last_player.gainCard(elems[1], 1);
return true;
}
return false;
}
function maybeHandleNobleBrigand(elems, text_arr, text) {
if (text.match(/draws? and reveals?.+, trashing a/)) {
getPlayer(text_arr[0]).gainCard(elems[elems.length - 1], -1);
return true;
}
return false;
}
function maybeHandleVp(text) {
var re = new RegExp("[+]([0-9]+) ▼");
var arr = text.match(re);
if (arr && arr.length == 2) {
last_player.changeScore(arr[1]);
}
}
function getCardCount(card, text) {
var count = 1;
var re = new RegExp("([0-9]+) " + card);
var arr = text.match(re);
if (arr && arr.length == 2) {
count = arr[1];
}
return count;
}
function handleGainOrTrash(player, elems, text, multiplier) {
for (elem in elems) {
if (elems[elem].innerText != undefined) {
var card = elems[elem].innerText;
var count = getCardCount(card, text);
player.gainCard(elems[elem], multiplier * count);
}
}
}
function maybeHandleGameStart(node) {
var nodeText = node.innerText;
if (nodeText == null || nodeText.indexOf("Turn order") != 0) {
return false;
}
initialize(node);
maybeAddToFullLog(node);
return true;
}
function handleLogEntry(node) {
if (maybeHandleGameStart(node)) return;
if (!started) return;
maybeAddToFullLog(node);
processLogEntry(node);
}
function processLogEntry(node) {
maybeRewriteName(node);
if (maybeHandleTurnChange(node)) return;
// Make sure this isn't a duplicate possession entry.
if (node.className.indexOf("possessed-log") > 0) return;
var text = node.innerText.split(" ");
// Keep track of what sort of scope we're in for things like watchtower.
handleScoping(text);
// Gaining VP could happen in combination with other stuff.
maybeHandleVp(node.innerText);
elems = node.getElementsByTagName("span");
if (elems.length == 0) {
if (maybeReturnToSupply(node.innerText)) return;
return;
}
// Remove leading stuff from the text.
var i = 0;
for (i = 0; i < text.length; i++) {
if (!text[i].match(/^[. ]*$/)) break;
}
if (i == text.length) return;
text = text.slice(i);
if (maybeHandleMint(elems, node.innerText)) return;
if (maybeHandleTradingPost(elems, node.innerText)) return;
if (maybeHandleExplorer(elems, node.innerText)) return;
if (maybeHandleSwindler(elems, node.innerText)) return;
if (maybeHandlePirateShip(elems, text, node.innerText)) return;
if (maybeHandleSeaHag(elems, text, node.innerText)) return;
if (maybeHandleOffensiveTrash(elems, text, node.innerText)) return;
if (maybeHandleTournament(elems, text, node.innerText)) return;
if (maybeHandleTrader(elems, text, node.innerText)) return;
if (maybeHandleTunnel(elems, text, node.innerText)) return;
if (maybeHandleNobleBrigand(elems, text, node.innerText)) return;
if (text[0] == "trashing") {
var player = last_player;
if (scopes.length >= 2 && scopes[scopes.length - 2] != null) {
player = scopes[scopes.length - 2];
}
return handleGainOrTrash(player, elems, node.innerText, -1);
}
if (text[1].indexOf("trash") == 0) {
return handleGainOrTrash(getPlayer(text[0]), elems, node.innerText, -1);
}
if (text[0] == "gaining") {
var player = last_player;
if (scopes.length >= 2 && scopes[scopes.length - 2] != null) {
player = scopes[scopes.length - 2];
}
return handleGainOrTrash(player, elems, node.innerText, 1);
}
if (text[1].indexOf("gain") == 0) {
var player = getPlayer(text[0]);
// If the player is missing it might be because it's the first turn. Defer.
if (player == null && turn_number == 1) {
to_process.push(node);
return;
}
return handleGainOrTrash(getPlayer(text[0]), elems, node.innerText, 1);
}
// There might be a gain on a player with spaces, etc, so defer this case if
// it's the first turn.
if (turn_number == 1 && node.innerText.indexOf(" gains ") != -1) {
to_process.push(node);
return;
}
var player = getPlayer(text[0]);
var action = text[1];
// Handle revealing cards.
if (action.indexOf("reveal") == 0) {
last_reveal_player = player;
last_reveal_card = elems[elems.length - 1];
}
// Expect one element from here on out.
if (elems.length > 1) return;
// It's a single card action.
var card = elems[0];
var card_text = elems[0].innerText;
if (action.indexOf("buy") == 0) {
var count = getCardCount(card_text, node.innerText);
player.gainCard(card, count);
} else if (action.indexOf("pass") == 0) {
possessed_turn_backup = possessed_turn;
possessed_turn = null;
if (possessed_turn && this == last_player) return;
if (player_count != 2) {
maybeAnnounceFailure(">> Warning: Masquerade with more than 2 players " +
"causes inaccurate score counting.");
}
player.gainCard(card, -1);
var other_player = findTrailingPlayer(node.innerText);
if (other_player == null) {
handleError("Could not find trailing player from: " + node.innerText);
} else {
other_player.gainCard(card, 1);
}
possessed_turn = possessed_turn_backup;
} else if (action.indexOf("receive") == 0) {
possessed_turn_backup = possessed_turn;
possessed_turn = null;
player.gainCard(card, 1);
var other_player = findTrailingPlayer(node.innerText);
if (other_player == null) {
handleError("Could not find trailing player from: " + node.innerText);
} else {
other_player.gainCard(card, -1);
}
possessed_turn = possessed_turn_backup;
}
}
function playerString(player, text) {
return " <span class=" + player.id + ">" +
player.original_name + "=" + text + "</span>";
}
function getScores() {
var scores = "Points: ";
for (var player in players) {
scores += playerString(players[player], players[player].getScore());
}
return scores;
}
function updateScores() {
if (points_spot == undefined) {
var spot = $('a[href="http://dominion.isotropic.org/faq/"]');
if (spot.length != 1) return;
points_spot = spot[0];
return;
}
ignore_events = true;
points_spot.innerHTML = getScores();
ignore_events = false;
}
function getDecks() {
var decks = "Cards: ";
for (var player in players) {
decks += playerString(players[player], players[player].getDeckString());
}
return decks;
}
function updateDeck() {
if (deck_spot == undefined) {
var spot = $('a[href="/signout"]');
if (spot.length != 1) return;
deck_spot = spot[0];
}
ignore_events = true;
deck_spot.innerHTML = getDecks();
ignore_events = false;
}
function initialize(doc) {
started = true;
introduced = false;
i_introduced = false;
disabled = false;
had_error = false;
possessed_turn = null;
announced_error = false;
turn_number = 0;
to_process = [];
scopes = [];
players = new Object();
// Setup the player rewrites. Just add self for now.
player_rewrites = new Object();
var my_name = localStorage["name"];
if (my_name) {
var rewritten = rewriteName(my_name);
if (rewritten != my_name) {
player_rewrites[htmlEncode(my_name)] = htmlEncode(rewritten);
}
}
player_re = "";
player_count = 0;
if (localStorage.getItem("disabled")) {
disabled = true;
}
if (!disabled && getOption("always_display")) {
updateScores();
updateDeck();
}
// Figure out what turn we are. We'll use that to figure out how long to wait
// before announcing the extension.
var self_index = -1;
var arr;
if (doc.innerText == "Turn order is you.") {
arr = [undefined, "you"];
} else {
var p = "(?:([^,]+), )"; // an optional player
var pl = "(?:([^,]+),? )"; // the last player (might not have a comma)
var re = new RegExp("Turn order is "+p+"?"+p+"?"+p+"?"+pl+"and then (.+).");
arr = doc.innerText.match(re);
}
if (arr == null) {
handleError("Couldn't parse: " + doc.innerText);
}
var other_player_names = [];
for (var i = 1; i < arr.length; ++i) {
if (arr[i] == undefined) continue;
if (arr[i] == "you") {
self_index = player_count;
break;
}
}
// Assume it's already introduced if it's rewriting the tree for a reload.
// Otherwise setup to maybe introduce the extension.
if (!restoring_log) {
var wait_time = 200 * Math.floor(Math.random() * 10 + 5);
if (self_index != -1) {
wait_time = 300 * self_index;
}
console.log("Waiting " + wait_time + " to introduce " +
"(index is: " + self_index + ").");
setTimeout("maybeIntroducePlugin()", wait_time);
}
if (getOption('show_card_counts')) {
setupPerPlayerCardCounts();
}
$('#full_log').append('<div style="height: 60em"></div>');
}
function maybeRewriteName(doc) {
if (doc.innerHTML != undefined && doc.innerHTML != null) {
for (player in player_rewrites) {
doc.innerHTML = doc.innerHTML.replace(player, player_rewrites[player]);
}
}
}
function maybeIntroducePlugin() {
if (!introduced && !disabled) {
writeText("★ Cards counted by Dominion Point Counter ★");
writeText("http://goo.gl/iDihS (screenshot: http://goo.gl/G9BTQ)");
writeText("Type !status to see the current score.");
writeText("Type !details to see deck details for each player.");
if (getOption("allow_disable")) {
writeText("Type !disable by turn 5 to disable the point counter.");
}
}
}
function maybeShowStatus(request_time) {
if (last_status_print < request_time) {
last_status_print = new Date().getTime();
// Build up a string to show.
var to_show = " >> Decks: ";
for (var player in players) {
to_show += " " + players[player].name + "=" + players[player].getDeckString();
}
to_show += " | Points: "
for (var player in players) {
to_show += " " + players[player].name + "=" + players[player].getScore();
}
var my_name = localStorage["name"];
if (my_name == undefined || my_name == null) my_name = "Me";
writeText(to_show.replace(/You=/g, my_name + "="));
}
}
function maybeShowDetails(request_time) {
if (last_status_print < request_time) {
last_status_print = new Date().getTime();
var my_name = localStorage["name"];
if (my_name == undefined || my_name == null) my_name = "Me";
for (var player in players) {
player = players[player];
var name = player.name == "You" ? my_name : player.name;
writeText('>> *' + name + '* => ' + player.getScore() +
' points [deck size is ' + player.getDeckString() + '] - ' +