-
Notifications
You must be signed in to change notification settings - Fork 33
/
gwent.js
2681 lines (2359 loc) · 81.7 KB
/
gwent.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
"use strict"
class Controller {}
// Makes decisions for the AI opponent player
class ControllerAI {
constructor(player) {
this.player = player;
}
// Collects data and weighs options before taking a weighted random action
async startTurn(player){
if (player.opponent().passed && (player.winning ||
player.deck.faction === "nilfgaard" && player.total === player.opponent().total) ){
await player.passRound();
return;
}
let data_max = this.getMaximums();
let data_board = this.getBoardData();
let weights = player.hand.cards.map(c =>
({weight: this.weightCard(c, data_max, data_board), action: async () => await this.playCard(c, data_max, data_board)}) );
if (player.leaderAvailable)
weights.push( {weight: this.weightLeader(player.leader, data_max, data_board), action: async () => await player.activateLeader()} );
weights.push( {weight: this.weightPass(), action: async () => await player.passRound()} );
let weightTotal = weights.reduce( (a,c) => a + c.weight, 0);
if (weightTotal === 0){
for (let i=0; i<player.hand.cards.length; ++i) {
let card = player.hand.cards[i];
if (card.row === "weather" && this.weightWeather(card) > -1 || card.abilities.includes("avenger")) {
await weights[i].action();
return;
}
}
await player.passRound();
} else {
let rand = randomInt(weightTotal);
for (var i=0; i < weights.length; ++i) {
rand -= weights[i].weight;
if (rand < 0)
break;
}
await weights[i].action();
}
}
// Collects data about card with the hightest power on the board
getMaximums(){
let rmax = board.row.map(r => ({row: r, cards: r.cards.filter(c => c.isUnit()).reduce( (a,c) =>
(!a.length|| a[0].power < c.power) ? [c] : a[0].power === c.power ? a.concat([c]) : a
, []) }) );
let max = rmax.filter((r,i) => r.cards.length && i < 3).reduce((a,r) => Math.max(a, r.cards[0].power), 0);
let max_me = rmax.filter((r,i) => i < 3 && r.cards.length && r.cards[0].power === max).reduce((a,r) =>
a.concat(r.cards.map(c => ({row:r, card:c})))
, []);
max = rmax.filter((r,i) => r.cards.length && i > 2).reduce((a,r) => Math.max(a, r.cards[0].power), 0);
let max_op = rmax.filter((r,i) => i > 2 && r.cards.length && r.cards[0].power === max).reduce((a,r) =>
a.concat(r.cards.map(c => ({row:r, card:c})))
, []);
return {rmax: rmax, me: max_me, op: max_op};
}
// Collects data about the types of cards on the board and in each player's graves
getBoardData(){
let data = this.countCards(new CardContainer());
Object.keys([0,1,2]).map(i => board.row[i]).forEach(r => this.countCards(r, data));
data.grave_me = this.countCards(this.player.grave);
data.grave_op = this.countCards(this.player.opponent().grave);
return data;
}
// Catalogs the kinds of cards in a given CardContainer
countCards(container, data){
data = data ? data : {spy: [], medic: [], bond: {}, scorch: []};
container.cards.filter(c => c.isUnit()).forEach(c => {
for (let x of c.abilities) {
switch (x) {
case "spy":
case "medic":
data[x].push(c);
break;
case "scorch_r": case "scorch_c": case "scorch_s":
data["scorch"].push(c);
break;
case "bond":
if (!data.bond[c.name])
data.bond[c.name] = 0;
data.bond[c.name]++;
}
}
});
return data;
}
// Swaps a card from the hand with the deck if beneficial
redraw() {
let card = this.discardOrder({holder:this.player}).shift();
if (card && card.power < 15) {
this.player.deck.swap(this.player.hand, this.player.hand.removeCard(card))
}
}
// Orders discardable cards from most to least discardable
discardOrder(card) {
let cards = [];
let groups = {};
let musters = card.holder.hand.cards.filter(c => c.abilities.includes("muster"));
while (musters.length > 0) {
let curr = musters.pop();
let i = curr.name.indexOf('-');
let name = i === -1 ? curr.name : curr.name.substring(0, i).trim();
if (!groups[name])
groups[name] = [];
let group = groups[name];
group.push(curr);
for (let j=musters.length-1; j>=0; j--)
if (musters[j].name.startsWith(name))
group.push( musters.splice(j,1)[0] );
}
for (let group of Object.values(groups)) {
group.sort(Card.compare);
group.pop();
cards.push(...group);
}
let weathers = card.holder.hand.cards.filter(c => c.row === "weather");
if (weathers.length > 1){
weathers.splice(randomInt(weathers.length), 1);
cards.push(...weathers);
}
let normal = card.holder.hand.cards.filter(c => c.abilities.length === 0);
normal.sort(Card.compare);
cards.push(...normal);
return cards;
}
// Tells the Player that this object controls to play a card
async playCard(c, max, data){
if (c.name === "Commander's Horn")
await this.horn(c);
else if (c.name === "Mardroeme")
await this.mardroeme(c);
else if (c.name === "Decoy")
await this.decoy(c, max, data);
else if (c.name === "Scorch")
await this.scorch(c, max, data);
else
await this.player.playCard(c);
}
// Plays a Commander's Horn to the most beneficial row. Assumes at least one viable row.
async horn(card){
let rows = [0,1,2].map(i => board.row[i]).filter(r => r.special === null);
let max_row;
let max = 0;
for (let i=0; i<rows.length; ++i) {
let r = rows[i];
let dif = [0, 0];
this.calcRowPower(r, dif, true);
r.effects.horn++;
this.calcRowPower(r, dif, false);
r.effects.horn--;
let score = dif[1] - dif[0];
if (max < score){
max = score;
max_row = r;
}
}
await this.player.playCardToRow(card, max_row);
}
// Plays a Mardroeme to the most beneficial row. Assumes at least one viable row.
async mardroeme(card){ // TODO skellige
let row, max = 0;
for (let i=1; i<3; i++){
let curr = this.weightMardroemeRow(card, board.row[i]);
if (curr > max){
max = curr;
row = board.row[i];
}
}
await this.player.playCardToRow(card, row);
}
// Selects a card to remove from a Grave. Assumes at least one valid card.
medic(card, grave){
let data = this.countCards(grave);
let targ;
if (data.spy.length){
let min = data.spy.reduce( (a,c) => Math.min(a, c.power), Number.MAX_VALUE);
targ = data.spy.filter(c => c.power === min)[0];
} else if (data.medic.length) {
let max = data.medic.reduce( (a,c) => Math.max(a, c.power), Number.MIN_VALUE);
targ = data.medic.filter(c => c.power === max)[0];
} else if (data.scorch.length) {
targ = data.scorch[randomInt(data.scorch.length)];
} else {
let units = grave.findCards(c => c.isUnit());
targ = units.reduce( (a,c) => a.power < c.power ? c : a, units[0] );
}
return targ;
}
// Selects a card to return to the Hand and replaces it with a Decoy. Assumes at least one valid card.
async decoy(card, max, data) {
let targ, row;
if (data.spy.length){
let min = data.spy.reduce( (a,c) => Math.min(a, c.power), Number.MAX_VALUE);
targ = data.spy.filter(c => c.power === min)[0];
} else if (data.medic.length) {
targ = data.medic[randomInt(data.medic.length)];
} else if (data.scorch.length) {
targ = data.scorch[randomInt(data.scorch.length)];
} else {
let pairs = max.rmax.filter((r,i) => i<3 && r.cards.length).reduce((a,r) =>
r.cards.map(c => ({r:r.row, c:c})).concat(a)
, []);
let pair = pairs[randomInt(pairs.length)];
targ = pair.c;
row = pair.r;
}
for (let i = 0; !row ; ++i){
if (board.row[i].cards.indexOf(targ) !== -1){
row = board.row[i];
break;
}
}
setTimeout(() => board.toHand(targ, row), 1000);
await this.player.playCardToRow(card, row);
}
// Tells the controlled Player to play the Scorch card
async scorch(card, max, data){
await this.player.playScorch(card);
}
// Assigns a weight for how likely the conroller is to Pass the round
weightPass(){
if (this.player.health === 1)
return 0;
let dif = this.player.opponent().total - this.player.total;
if (dif > 30)
return 100;
if (dif < -30 && this.player.opponent().handsize - this.player.handsize > 2)
return 100;
return Math.floor(Math.abs(dif));
}
// Assigns a weight for how likely the controller is to activate its leader ability
weightLeader(card, max, data) {
let w = ability_dict[card.abilities[0]].weight;
if (ability_dict[card.abilities[0]].weight) {
let score = w(card, this, max, data);
return score;
}
return 10 + (game.roundCount-1) * 15;
}
// Assigns a weight for how likely the controller will use a scorch-row card
weightScorchRow(card, max, row_name) {
let index = 3 + (row_name==="close" ? 0 : row_name==="ranged" ? 1 : 2);
if (board.row[index].total < 10)
return 0;
let score = max.rmax[index].cards.reduce((a,c) => a + c.power, 0);
return score;
}
// Calculates a weight for how likely the conroller will use horn on this row
weightHornRow(card, row){
return row.special !== null ? 0 : this.weightRowChange(card, row);
}
// Calculates weight for playing a card on a given row, min 0
weightRowChange(card, row){
return Math.max(0, this.weightRowChangeTrue(card, row));
}
// Calculates weight for playing a card on the given row
weightRowChangeTrue(card, row) {
let dif = [0,0];
this.calcRowPower(row, dif, true);
row.updateState(card, true);
this.calcRowPower(row, dif, false);
if (!card.isSpecial())
dif[0] -= row.calcCardScore(card);
row.updateState(card, false);
return dif[1] - dif[0];
}
// Calculates the weight for playing a weather card
weightWeather(card) {
let rows;
if (card.name === "Clear Weather")
rows = Object.values(weather.types).filter(t => t.count > 0).flatMap(t => t.rows);
else
rows = Object.values(weather.types).filter(t => t.count === 0 && t.name === card.abilities[0]).flatMap(t => t.rows);
if (!rows.length)
return 1;
let dif = [0,0];
rows.forEach( r => {
let state = r.effects.weather;
this.calcRowPower(r, dif, true);
r.effects.weather = !state;
this.calcRowPower(r, dif, false);
r.effects.weather = state;
});
return dif[1] - dif[0];
}
// Calculates the weight for playing a mardroeme card
weightMardroemeRow(card, row){
if (card.name === "Mardroeme" && row.special !== null)
return 0;
let ermion = card.holder.hand.cards.filter(c => c.name === "Ermion").length > 0;
if (ermion && card.name !== "Ermion" && row === board.row[1])
return 0;
let name = row === board.row[1] ? "Young Berserker" : "Berserker";
let n = row.cards.filter(c => c.name === name).length;
let weight = row === board.row[2] ? 10*n : 8*n*n - 2*n
return Math.max(1, weight);
}
// Calculates the weight for cards with the medic ability
weightMedic(data, score, owner){
let units = owner.grave.findCards(c => c.isUnit());
let grave = data["grave_" + owner.opponent().tag];
return !units.length ? Math.min(1,score) : score + (grave.spy.length ? 50 : grave.medic.length ? 15 : grave.scorch.length ? 10 : this.player.health === 1 ? 1 : 0);
}
// Calculates the weight for cards with the berserker ability
weightBerserker(card, row, score){
if (card.holder.hand.cards.filter(c => c.abilities.includes("mardroeme")).length < 1 && !row.effects.mardroeme > 0)
return score;
score -= card.basePower;
if (card.row === "close")
score += 14;
else {
let n = 0;
if (!row.effects.mardroeme)
n = row.cards.filter(c => c.name === "Young Berserker").length;
else
n = row.cards.filter(c => "Transformed Young Vildkaarl").length;
score = 8*((n+1)*(n+1) - n*n) + n*score;
}
return Math.max(1, score);
}
// Calculates the weight for a weather card if played from the deck
weightWeatherFromDeck(card, weather_id) {
if (card.holder.deck.findCard(c => c.abilities.includes(weather_id)) === undefined)
return 0;
return this.weightCard({abilities:[weather_id], row:"weather"});
}
// Assigns a weights for how likely the controller with play a card from its hand
weightCard(card, max, data){
if (card.name === "Decoy")
return data.spy.length ? 50 : data.medic.length ? 15 : data.scorch.length ? 10 : max.me.length ? 1 : 0;
if (card.name === "Commander's Horn") {
let rows = [0,1,2].map(i => board.row[i]).filter(r => r.special === null);
if (!rows.length)
return 0;
rows = rows.map(r => this.weightHornRow(card, r) );
return Math.max(...rows)/2;
}
if (card.abilities) {
if (card.abilities.includes("scorch")) {
let power_op = max.op.length ? max.op[0].card.power : 0;
let power_me = max.me.length ? max.me[0].card.power : 0;
let total_op = power_op * max.op.length;
let total_me = power_me * max.me.length;
return power_me > power_op ? 0 : power_me < power_op ? total_op : Math.max(0, total_op - total_me);
}
if (card.abilities.includes("decoy")) {
return data.spy.length ? 50 : data.medic.length ? 15 : data.scorch.length ? 10 : max.me.length ? 1 : 0;
}
if (card.abilities.includes("mardroeme")) {
let rows = [1,2].map(i => board.row[i]);
return Math.max(...rows.map(r => this.weightMardroemeRow(card, r)) );
}
}
if (card.row === "weather") {
return Math.max(0, this.weightWeather(card));
}
let row = board.getRow(card, card.row === "agile" ? "close" : card.row, this.player);
let score = row.calcCardScore(card);
switch(card.abilities[card.abilities.length -1]) {
case "bond":
case "morale":
case "horn":
score = this.weightRowChange(card, row); break;
case "medic":
score = this.weightMedic(data, score, card.holder); break;
case "spy": score = 15 + score; break;
case "muster": score *= 3; break;
case "scorch_c":
score = Math.max(1, this.weightScorchRow(card, max, "close")); break;
case "scorch_r":
score = Math.max(1, this.weightScorchRow(card, max, "ranged")); break;
case "scorch_s":
score = Math.max(1, this.weightScorchRow(card, max, "siege")); break;
case "berserker":
score = this.weightBerserker(card, row, score); break;
case "avenger": case "avenger_kambi":
return score + ability_dict[card.abilities[card.abilities.length -1]].weight();
}
return score;
}
// Calculates the current power of a row associated with each Player
calcRowPower(r, dif, add){
r.findCards(c => c.isUnit()).forEach(c => {
let p = r.calcCardScore(c);
c.holder === this.player ? (dif[0]+= add ? p : -p) : (dif[1]+= add ? p : -p);
});
}
}
// Can make actions during turns like playing cards that it owns
class Player {
constructor(id, name, deck) {
this.id = id;
this.tag = (id === 0) ? "me" : "op";
this.controller = (id === 0) ? new Controller() : new ControllerAI(this);
this.hand = (id === 0) ? new Hand(document.getElementById("hand-row")) : new HandAI();
this.grave = new Grave( document.getElementById("grave-" + this.tag));
this.deck = new Deck(deck.faction, document.getElementById("deck-" + this.tag));
this.deck_data = deck;
this.leader = new Card(deck.leader, this);
this.elem_leader = document.getElementById("leader-" + this.tag);
this.elem_leader.children[0].appendChild( this.leader.elem );
this.reset();
this.name = name;
document.getElementById("name-" + this.tag).innerHTML = name;
document.getElementById("deck-name-" +this.tag).innerHTML = factions[deck.faction].name;
document.getElementById("stats-" + this.tag).getElementsByClassName("profile-img")[0].children[0].children[0];
let x = document.querySelector("#stats-" +this.tag+ " .profile-img > div > div");
x.style.backgroundImage = iconURL("deck_shield_" + deck.faction);
}
// Sets default values
reset(){
this.grave.reset();
this.hand.reset();
this.deck.reset();
this.deck.initializeFromID(this.deck_data.cards, this);
this.health = 2;
this.total = 0;
this.passed = false;
this.handsize = 10;
this.winning = false;
this.enableLeader();
this.setPassed(false);
document.getElementById("gem1-" +this.tag).classList.add("gem-on");
document.getElementById("gem2-" +this.tag).classList.add("gem-on");
}
// Returns the opponent Player
opponent(){
return board.opponent(this);
}
// Updates the player's total score and notifies the gamee
updateTotal(n){
this.total += n;
document.getElementById("score-total-" + this.tag).children[0].innerHTML = this.total;
board.updateLeader();
}
// Puts the player in the winning state
setWinning(isWinning) {
if (this.winning ^ isWinning)
document.getElementById("score-total-" + this.tag).classList.toggle("score-leader");
this.winning = isWinning;
}
// Puts the player in the passed state
setPassed(hasPassed) {
if (this.passed ^ hasPassed)
document.getElementById("passed-" + this.tag).classList.toggle("passed");
this.passed = hasPassed;
}
// Sets up board for turn
async startTurn(){
document.getElementById("stats-" + this.tag).classList.add("current-turn");
if (this.leaderAvailable)
this.elem_leader.children[1].classList.remove("hide");
if (this === player_me) {
document.getElementById("pass-button").classList.remove("noclick");
}
if (this.controller instanceof ControllerAI) {
await this.controller.startTurn(this);
}
}
// Passes the round and ends the turn
passRound(){
this.setPassed(true);
this.endTurn();
}
// Plays a scorch card
async playScorch(card){
await this.playCardAction(card, async () => await ability_dict["scorch"].activated(card));
}
// Plays a card to a specific row
async playCardToRow(card, row){
await this.playCardAction(card, async () => await board.moveTo(card, row, this.hand));
}
// Plays a card to the board
async playCard(card){
await this.playCardAction(card, async () => await card.autoplay(this.hand));
}
// Shows a preview of the card being played, plays it to the board and ends the turn
async playCardAction(card, action){
ui.showPreviewVisuals(card);
await sleep(1000);
ui.hidePreview(card);
await action();
this.endTurn();
}
// Handles end of turn visuals and behavior the notifies the game
endTurn(){
if (!this.passed && !this.canPlay())
this.setPassed(true);
if (this === player_me){
document.getElementById("pass-button").classList.add("noclick");
}
document.getElementById("stats-" + this.tag).classList.remove("current-turn");
this.elem_leader.children[1].classList.add("hide");
game.endTurn()
}
// Tells the the Player if it won the round. May damage health.
endRound(win){
if (!win) {
if (this.health < 1)
return;
document.getElementById("gem" + this.health + "-" +this.tag).classList.remove("gem-on");
this.health--;
}
this.setPassed(false);
this.setWinning(false);
}
// Returns true if the Player can make any action other than passing
canPlay() {
return this.hand.cards.length > 0 || this.leaderAvailable;
}
// Use a leader's Activate ability, then disable the leader
async activateLeader() {
ui.showPreviewVisuals(this.leader);
await sleep(1500);
ui.hidePreview(this.leader);
await this.leader.activated[0](this.leader, this);
this.disableLeader();
this.endTurn();
}
// Disable access to leader ability and toggles leader visuals to off state
disableLeader(){
this.leaderAvailable = false;
let elem = this.elem_leader.cloneNode(true);
this.elem_leader.parentNode.replaceChild(elem, this.elem_leader);
this.elem_leader = elem;
this.elem_leader.children[0].classList.add("fade");
this.elem_leader.children[1].classList.add("hide");
this.elem_leader.addEventListener("click", async () => await ui.viewCard(this.leader), false);
}
// Enable access to leader ability and toggles leader visuals to on state
enableLeader() {
this.leaderAvailable = this.leader.activated.length > 0;
let elem = this.elem_leader.cloneNode(true);
this.elem_leader.parentNode.replaceChild(elem, this.elem_leader);
this.elem_leader = elem;
this.elem_leader.children[0].classList.remove("fade");
this.elem_leader.children[1].classList.remove("hide");
if (this.id === 0 && this.leader.activated.length > 0){
this.elem_leader.addEventListener("click",
async () => await ui.viewCard(this.leader, async () => await this.activateLeader()),
false);
} else {
this.elem_leader.addEventListener("click", async () => await ui.viewCard(this.leader), false);
}
// TODO set crown color
}
}
// Handles the adding, removing and formatting of cards in a container
class CardContainer {
constructor(elem) {
this.elem = elem;
this.cards = [];
}
// Returns the first card that satisfies the predcicate. Does not modify container.
findCard(predicate){
for (let i=this.cards.length-1; i>=0; --i)
if (predicate(this.cards[i]))
return this.cards[i];
}
// Returns a list of cards that satisfy the predicate. Does not modify container.
findCards(predicate){
return this.cards.filter(predicate);
}
// Returns a list of up to n cards that satisfy the predicate. Does not modify container.
findCardsRandom(predicate, n){
let valid = predicate ? this.cards.filter(predicate) : this.cards;
if (valid.length === 0)
return [];
if (!n || n === 1)
return [valid[randomInt(valid.length)]];
let out = [];
for (let i=Math.min(n, valid.length); i>0 ; --i){
let index = randomInt(valid.length);
out.push( valid.splice(index,1)[0] );
}
return out;
}
// Removes and returns a list of cards that satisy the predicate.
getCards(predicate){
return this.cards.reduce((a,c,i) => ( predicate(c,i)?[i]:[] ).concat(a), []).map( i => this.removeCard(i));
}
// Removes and returns a card that satisfies the predicate.
getCard(predicate) {
for (let i=this.cards.length-1; i>=0; --i)
if (predicate(this.cards[i]))
return this.removeCard(i);
}
// Removes and returns any cards up to n that satisfy the predicate.
getCardsRandom(predicate, n) {
return this.findCardsRandom(predicate, n).map( c => this.removeCard(c) );
}
// Adds a card to the container along with its associated HTML element.
addCard(card, index){
this.cards.push(card);
this.addCardElement(card, index?index:0);
this.resize();
}
// Removes a card from the container along with its associated HTML element.
removeCard(card, index){
if (this.cards.length === 0)
throw "Cannot draw from empty " + this.constructor.name;
card = this.cards.splice( isNumber(card)? card : this.cards.indexOf(card) , 1)[0];
this.removeCardElement(card, index?index:0);
this.resize();
return card;
}
// Adds a card to a pre-sorted CardContainer
addCardSorted(card){
let i = this.getSortedIndex(card);
this.cards.splice(i, 0, card);
return i;
}
// Returns the expected index of a card in a sorted CardContainer
getSortedIndex(card){
for (var i=0; i<this.cards.length; ++i)
if (Card.compare(card, this.cards[i]) < 0)
break;
return i;
}
// Adds a card to a random index of the CardContainer
addCardRandom(card){
this.cards.push(card);
let index = randomInt(this.cards.length);
if (index !== this.cards.length-1) {
let t = this.cards[this.cards.length-1];
this.cards[this.cards.length-1] = this.cards[index];
this.cards[index] = t;
}
return index;
}
// Removes the HTML elemenet associated with the card from this CardContainer
removeCardElement(card, index){
if (this.elem)
this.elem.removeChild(card.elem);
}
// Adds the HTML elemenet associated with the card to this CardContainer
addCardElement(card, index){
if (this.elem){
if (index === this.cards.length)
thise.elem.appendChild(card.elem);
else
this.elem.insertBefore(card.elem, this.elem.children[index]);
}
}
// Empty function to be overried by subclasses that resize their content
resize(){}
// Modifies the margin of card elements inside a row-like container to stack properly
resizeCardContainer(overlap_count, gap, coef) {
let n = this.elem.children.length;
let param = (n < overlap_count) ? "" + gap+"vw" : defineCardRowMargin(n, coef);
let children = this.elem.getElementsByClassName("card");
for (let x of children)
x.style.marginLeft = x.style.marginRight = param;
function defineCardRowMargin(n, coef = 0){
return "calc((100% - (4.45vw * " + n + ")) / (2*" +n+ ") - (" +coef+ "vw * " +n+ "))";
}
}
// Allows the row to be clicked
setSelectable(){
this.elem.classList.add("row-selectable");
}
// Disallows teh row to be clicked
clearSelectable() {
this.elem.classList.remove("row-selectable");
for (card in this.cards)
card.elem.classList.add("noclick");
}
// Returns the container to its default, empty state
reset() {
while(this.cards.length)
this.removeCard(0);
if (this.elem)
while(this.elem.firstChild)
this.elem.removeChild(this.elem.firstChild);
this.cards = [];
}
}
// Contians all used cards in the order that they were discarded
class Grave extends CardContainer {
constructor(elem) {
super(elem)
elem.addEventListener("click", () => ui.viewCardsInContainer(this), false);
}
// Override
addCard(card){
this.setCardOffset(card, this.cards.length);
super.addCard(card, this.cards.length);
}
// Override
removeCard(card){
let n = isNumber(card) ? card : this.cards.indexOf(card);
return super.removeCard(card, n);
}
// Override
removeCardElement(card, index){
card.elem.style.left = "";
super.removeCardElement(card, index);
for (let i=index; i<this.cards.length; ++i){
// if (!this.cards[i])
// console.log(i, index, card, this.cards[i]);
this.setCardOffset(this.cards[i], i);
}
}
// Offsets the card element in the deck
setCardOffset(card, n){
card.elem.style.left = -0.03 * n +"vw";
}
}
// Contains a randomized set of cards to be drawn from
class Deck extends CardContainer {
constructor(faction, elem){
super(elem);
this.faction = faction;
this.counter = document.createElement("div");
this.counter.classList = "deck-counter center";
this.counter.appendChild( document.createTextNode(this.cards.length) );
this.elem.appendChild(this.counter);
}
// Creates duplicates of cards with a count of more than one, then initializes deck
initializeFromID(card_id_list, player){
this.initialize( card_id_list.reduce((a,c) => a.concat(clone(c.count, card_dict[c.index])), []), player);
function clone(n ,elem) { for (var i=0, a=[]; i<n; ++i) a.push(elem); return a; }
}
// Populates a this deck with a list of card data and associated those cards with the owner of this deck.
initialize(card_data_list, player){
for (let i=0; i<card_data_list.length; ++i) {
let card = new Card(card_data_list[i], player);
card.holder = player;
this.addCardRandom(card);
this.addCardElement();
}
this.resize();
}
// Override
addCard(card){
this.addCardRandom(card);
this.addCardElement();
this.resize();
}
// Sends the top card to the passed hand
async draw(hand){
if (hand === player_op.hand)
hand.addCard(this.removeCard(0));
else
await board.toHand(this.cards[0], this);
}
// Draws a card and sends it to the container before adding a card from the container back to the deck.
swap(container, card){
container.addCard(this.removeCard(0));
this.addCard(card);
}
// Override
addCardElement() {
let elem = document.createElement("div");
elem.classList.add("deck-card");
elem.style.backgroundImage = iconURL("deck_back_" + this.faction, "jpg");
this.setCardOffset(elem, this.cards.length-1);
this.elem.insertBefore(elem, this.counter);
}
// Override
removeCardElement(){
this.elem.removeChild(this.elem.children[this.cards.length]).style.left = "";
}
// Offsets the card element in the deck
setCardOffset(elem, n){
elem.style.left = -0.03 * n +"vw";
}
// Override
resize(){
this.counter.innerHTML = this.cards.length;
this.setCardOffset(this.counter, this.cards.length);
}
// Override
reset() {
super.reset();
this.elem.appendChild(this.counter);
}
}
// Hand used by computer AI. Has an offscreen HTML element for card transitions.
class HandAI extends CardContainer {
constructor() {
super(undefined);
this.counter = document.getElementById("hand-count-op");
this.hidden_elem = document.getElementById("hand-op");
}
resize() {this.counter.innerHTML = this.cards.length; }
}
// Hand used by current player
class Hand extends CardContainer {
constructor(elem){
super(elem);
this.counter = document.getElementById("hand-count-me");
}
// Override
addCard(card){
let i = this.addCardSorted(card);
this.addCardElement(card, i);
this.resize();
}
// Override
resize() {
this.counter.innerHTML = this.cards.length;
this.resizeCardContainer(11, 0.075, .00225);
}
}
// Contains active cards and effects. Calculates the current score of each card and the row.
class Row extends CardContainer {
constructor(elem) {
super(elem.getElementsByClassName("row-cards")[0]);
this.elem_parent = elem;
this.elem_special = elem.getElementsByClassName("row-special")[0];
this.special = null;
this.total = 0;
this.effects = {weather:false, bond: {}, morale: 0, horn: 0, mardroeme: 0};
this.elem.addEventListener("click", () => ui.selectRow(this), true);
this.elem_special.addEventListener("click", () => ui.selectRow(this), false, true);
}
// Override
async addCard(card) {
if (card.isSpecial()) {
this.special = card;
this.elem_special.appendChild(card.elem);
} else {
let index = this.addCardSorted(card);
this.addCardElement(card, index);
this.resize();
}
this.updateState(card, true);
for (let x of card.placed)
await x(card, this);
card.elem.classList.add("noclick");
await sleep(600);
this.updateScore();
}
// Override
removeCard(card) {
card = isNumber(card) ? card === -1 ? this.special : this.cards[card] : card;
if (card.isSpecial()) {
this.special = null;
this.elem_special.removeChild(card.elem);
} else {
super.removeCard(card);
card.resetPower();
}
this.updateState(card, false);
for (let x of card.removed)
x(card);
this.updateScore();
return card;
}
// Override
removeCardElement(card, index) {
super.removeCardElement(card, index);
let x = card.elem;
x.style.marginLeft = x.style.marginRight = "";
x.classList.remove("noclick");
}
// Updates a card's effect on the row
updateState(card, activate){
for (let x of card.abilities){
switch (x) {
case "morale":
case "horn":
case "mardroeme": this.effects[x]+= activate ? 1 : -1; break;
case "bond":
if (!this.effects.bond[card.id()])
this.effects.bond[card.id()] = 0;
this.effects.bond[card.id()] += activate ? 1 : -1;
break;
}
}
}
// Activates weather effect and visuals
addOverlay(overlay){
this.effects.weather = true;
this.elem_parent.getElementsByClassName("row-weather")[0].classList.add(overlay);
this.updateScore();
}
// Deactivates weather effect and visuals
removeOverlay(overlay){
this.effects.weather = false;
this.elem_parent.getElementsByClassName("row-weather")[0].classList.remove(overlay);