-
Notifications
You must be signed in to change notification settings - Fork 0
/
perikles.js
4338 lines (4002 loc) · 179 KB
/
perikles.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
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* Perikles implementation : © <David Edelstein> <david.edelstein@gmail.com>
*
* This code has been produced on the BGA studio platform for use on http://boardgamearena.com.
* See http://en.boardgamearena.com/#!doc/Studio for more information.
* -----
*
* perikles.js
*
* Perikles user interface script
*
* In this file, you are describing the logic of your user interface, in Javascript language.
*
*/
const BOARD_SCALE = 2;
const INFLUENCE_SCALE = 0.5;
const CITIES = ['athens', 'sparta', 'argos', 'corinth', 'thebes', 'megara'];
const INFLUENCE_ROW = {'athens' : 0, 'sparta' : 1, 'argos' : 2, 'corinth' : 3, 'thebes' : 4, 'megara' : 5, 'any' : 6};
const INFLUENCE_COL = {'influence' : 0, 'candidate' : 1, 'assassin' : 2};
const INFLUENCE_PILE = "influence_slot_0";
const COMMIT_INFLUENCE_CUBES = "commit_influence_cubes";
// player preferences
const PREF_AUTO_PASS = 100;
const PREF_LOG_FONT = 101;
const PREF_CONFIRM_DIALOG = 102;
const PREF_COLORBLIND = 103;
const SCORING_ANIMATION = 2000;
// permission buttons get displayed here
const MILITARY_DISPLAY_STATES = ['spartanChoice', 'nextPlayerCommit', 'commitForces', 'deadPool', 'takeDead', 'resolveTile', 'battle', 'rollcombat', 'specialBattleTile', 'takeLoss'];
const CANDIDATES = {
"\u{003B1}" : "a",
"\u{003B2}" : "b"
}
const WHITE_OUTLINE = 'text-shadow: 1px 1px 0 #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;';
const DEAD_POOL = "deadpool";
const LEFT_ARROW = '<span style="font-size:2em;">⇦</span>';
const RIGHT_ARROW = '<span style="font-size:2em;">⇨</span>';
define([
"dojo","dojo/_base/declare",
"ebg/core/gamegui",
"ebg/counter",
g_gamethemeurl + "modules/specialtile.js",
g_gamethemeurl + "modules/alkibiades.js",
g_gamethemeurl + "modules/slaverevolt.js",
g_gamethemeurl + "modules/stack.js",
g_gamethemeurl + "modules/counter.js",
g_gamethemeurl + "modules/locationtile.js",
g_gamethemeurl + "modules/decorator.js",
g_gamethemeurl + "modules/rolldice.js",
],
function (dojo, declare) {
return declare("bgagame.perikles", [ebg.core.gamegui, perikles.alkibiades, perikles.slaverevolt, perikles.stack, perikles.counter, perikles.decorator, perikles.dice], {
constructor: function(){
this.influence_h = 199;
this.influence_w = 128;
this.stacks = new perikles.stack();
this.slaverevolt = new perikles.slaverevolt();
// this.currentState = null;
},
/* @Override */
showMessage: function (msg, type) {
if (type == "error") {
// invalid commit, clear commits
if (this.currentState == "commitForces") {
this.onCancelCommit();
}
}
this.inherited(arguments);
},
/*
setup:
This method must set up the game user interface according to current game situation specified
in parameters.
The method is called each time the game interface is displayed to a player, ie:
_ when the game starts
_ when a player refreshes the game page (F5)
"gamedatas" argument contains all datas retrieved by your "getAllDatas" PHP method.
*/
setup: function( gamedatas ) {
if (!this._notif_uid_to_log_id) {
this._notif_uid_to_log_id = {};
}
this.decorator = new perikles.decorator(gamedatas.players);
this.dice = new perikles.dice();
this.setupSpecialTiles(gamedatas.players, gamedatas.specialtiles);
this.setupInfluenceTiles(gamedatas.influencetiles, parseInt(gamedatas.decksize));
this.setupInfluenceCubes(gamedatas.influencecubes);
this.setupLocationTiles(gamedatas.locationtiles);
this.setupCandidates(gamedatas.candidates);
this.setupLeaders(gamedatas.leaders);
this.setupStatues(gamedatas.statues);
this.setupMilitary(gamedatas.military, gamedatas.persianleaders);
this.setupTokens(gamedatas.battletokens);
this.setupDefeats(gamedatas.defeats);
this.setupCities();
// Setup game notifications to handle (see "setupNotifications" method below)
this.setupNotifications();
if (!this.isReadOnly()) {
this.setupPlayerOptions(gamedatas.specialtiles[this.player_id]);
}
this.setupPreference();
},
/**
* Allow setting autopass for Special Tile if it hasn't been used yet.
* @param {Object} myspecialtile
*/
setupPlayerOptions: function(myspecialtile) {
if (!myspecialtile['used']) {
const panel_html = this.format_block('jstpl_player_options', {text: _('Special Tile: Automatically pass')});
dojo.place(panel_html, $('player_board_'+this.player_id));
const pass_pref = this.prefs[PREF_AUTO_PASS].value;
const check = $("autopass_special");
if (pass_pref == 1) {
check.setAttribute("checked", "checked");
}
dojo.connect(check, 'onchange', this, 'changePreference');
const msg = _("If not checked, the game will pause whenever you are eligible to play your Special Tile. This might reveal information to other players about which Special Tile you have.");
const tthtml = '<span class="prk_help">'+msg+'</span>';
this.addTooltipHtml('autopass_help', tthtml, '');
}
},
/**
* Initialize preference values.
*/
setupPreference: function() {
// when refreshed, make sure doesn't change
this.changeLogFontSize(this.prefs[PREF_LOG_FONT].value);
// set preference for autoplay
this.onPreferenceChanged(PREF_AUTO_PASS, this.prefs[PREF_AUTO_PASS].value);
dojo.query('.preference_control').on('change', (e) => {
const match = e.target.id.match(/^preference_control_(\d+)$/);
if (match) {
const pref = toint(match[1]);
if ([PREF_AUTO_PASS, PREF_LOG_FONT, PREF_CONFIRM_DIALOG].includes(pref)) {
const newValue = e.target.value;
this.prefs[pref].value = newValue;
this.onPreferenceChanged(pref, newValue);
}
}
});
},
/**
* Called by clicking preference checkboxes, sets player pref.
* @param {Object} check
*/
changePreference: function(check) {
const newpref = check.target.checked ? 1 : 0;
this.setPreferenceValue(PREF_AUTO_PASS, newpref);
},
/*
* Preference polyfill. Called by both checkbox and the player preference menu.
*/
setPreferenceValue: function(number, newValue) {
var optionSel = 'option[value="' + newValue + '"]';
dojo.query('#preference_control_' + number + ' > ' + optionSel + ', #preference_fontrol_' + number + ' > ' + optionSel).attr('selected', true);
var select = $('preference_control_' + number);
if (dojo.isIE) {
select.fireEvent('onchange');
} else {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', false, true);
select.dispatchEvent(event);
}
},
/**
* Set up special tiles
* @param {Array} players
* @param {Array} specialtiles
*/
setupSpecialTiles: function(players, specialtiles) {
const special_scale = 0.2;
for (const player_id in players) {
const spec = specialtiles[player_id];
// add flex row for cards
const player_cards = this.format_block('jstpl_influence_cards', {id: player_id, scale: special_scale});
const player_cards_div = dojo.place(player_cards, $('player_board_'+player_id));
const specname = spec['name']; // null for other players' unused tiles
const used = !!spec['used'];
const specialtile = new perikles.specialtile(player_id, specname, used);
const specialhtml = specialtile.getDiv();
const tile = dojo.place(specialhtml, player_cards_div);
let ttext = "";
if (specialtile.isFaceup()) {
ttext = specialtile.createSpecialTileTooltip();
} else {
ttext = _("${player_name}'s Special tile");
const player_name = this.decorator.spanPlayerName(player_id, this.isColorblind());
ttext = ttext.replace('${player_name}', player_name);
}
this.addTooltip(tile.id, ttext, '');
}
},
/**
* Put influence tiles on board, create deck
* @param {Array} influence
* @param {int} decksize
*/
setupInfluenceTiles: function(influence, decksize) {
// tiles in slots
for (const tile of influence) {
const loc = tile['location'];
if (loc == "board") {
this.placeInfluenceTileBoard(tile);
} else {
this.placeInfluenceTilePlayerBoard(tile);
}
}
// deck
this.createInfluencePile(decksize);
},
/**
*
* @param {Object} tile
*/
placeInfluenceTileBoard: function(tile) {
const city = tile['city'];
const s = tile['slot'];
const card_div = this.createInfluenceCard(tile);
const card = dojo.place(card_div, $("influence_slot_"+s));
this.decorateInfluenceCard(card, city, tile['type']);
},
/**
*
* @param {Object} tile
*/
placeInfluenceTilePlayerBoard: function(tile) {
const loc = tile['location'];
const player_cards = loc+'_player_cards';
const card_div = this.createInfluenceCard(tile);
dojo.place(card_div, $(player_cards));
},
/**
*
* @param {Object} tile
* @returns Div string
*/
createInfluenceCard: function(tile) {
const id = tile['id'];
const city = tile['city'];
const xoff = -1 * INFLUENCE_COL[tile['type']] * INFLUENCE_SCALE * this.influence_w;
const yoff = -1 * INFLUENCE_ROW[city] * INFLUENCE_SCALE * this.influence_h;
const card_div = this.format_block('jstpl_influence_tile', {id: id, city: city, x: xoff, y: yoff});
return card_div;
},
/**
* Deck pile of decksize cardbacks
* @param {int} decksize
*/
createInfluencePile: function(decksize) {
for (let c = 1; c <= decksize; c++) {
const cardback = this.format_block('jstpl_influence_back', {id: c, x: -1 * INFLUENCE_SCALE * this.influence_w, y: -6 * INFLUENCE_SCALE * this.influence_h, m: c-1});
dojo.place(cardback, $(INFLUENCE_PILE));
}
var pile_tt = _("Influence Deck: ${num} cards remaining");
pile_tt = pile_tt.replace('${num}', decksize);
this.addTooltip(INFLUENCE_PILE, pile_tt, '');
},
/**
* Return translatable city name text
* @param {string} city
* @returns translatable string
*/
getCityNameTr: function(city) {
const citynames = {
"argos" : _("Argos"),
"athens": _("Athens"),
"corinth": _("Corinth"),
"megara": _("Megara"),
"sparta": _("Sparta"),
"thebes": _("Thebes"),
"any": _("Any City"),
"persia": _("Persia"),
};
return citynames[city];
},
/**
* Get the translation string for a special tile
* @param {string} special
*/
getSpecialTileTr: function(special) {
const special_names = {
'perikles': _("Perikles"),
'persianfleet': _("Persian Fleet"),
'slaverevolt': _("Slave Revolt"),
'brasidas': _("Brasidas"),
'thessalanianallies': _("Thessalanian Allies"),
'alkibiades': _("Alkibiades"),
'phormio': _("Phormio"),
'plague': _("Plague")
};
return special_names[special];
},
/**
* For Influence cards on display, add Event listeners.
* @param {Object} card
* @param {string} city
* @param {string} type
*/
decorateInfluenceCard: function(card, city, type) {
const helplbl = {
"influence": "",
"candidate": _("Candidate"),
"assassin": _("Assassin"),
"any": "",
};
const helptext = {
"influence": _("Add 2 Influence cubes to ${city}"),
"candidate": _("Add 1 Influence cube to ${city}, and propose a candidate in any city"),
"assassin": _("Add 1 Influence cube to ${city}, and remove 1 cube from any city"),
"any": _("Add 1 Influence cube to any city"),
};
const cityname = this.getCityNameTr(city);
let ttext = "";
if (city == "any") {
ttext = helptext["any"];
} else {
ttext = helptext[type];
}
ttext = ttext.replace('${city}', cityname);
const xoff = -1 * INFLUENCE_COL[type] * INFLUENCE_SCALE * this.influence_w;
const yoff = -1 * INFLUENCE_ROW[city] * INFLUENCE_SCALE * this.influence_h;
const tooltip = this.format_block('jstpl_influence_tt', {city: cityname, label: helplbl[type], text: ttext, x: xoff, y: yoff});
this.addTooltipHtml(card.id, tooltip, '');
card.addEventListener('click', () => {
this.onInfluenceCardSelected(card.id);
});
card.addEventListener('mouseenter', () => {
this.onInfluenceCardHover(card.id, true);
});
card.addEventListener('mouseleave', () => {
this.onInfluenceCardHover(card.id, false);
});
},
/**
* Place influence cubes on cities.
* @param {Object} influencecubes
*/
setupInfluenceCubes: function(influencecubes) {
for (const player_id of Object.keys(influencecubes)) {
for (const [city, cubes] of Object.entries(influencecubes[player_id])) {
const num = parseInt(cubes);
for (let n = 0; n < num; n++) {
const cube = this.createInfluenceCube(player_id, city, n);
const column = $(city+"_cubes_"+player_id);
const cube_div = dojo.place(cube, column);
cube_div.addEventListener('click', (event) => this.onSelectCube(event));
}
this.decorateInfluenceCubes(city, player_id);
}
}
},
/**
* Add event listeners to the cubes areas for each player.
* @param {string} city
* @param {string} player_id
*/
decorateInfluenceCubes: function(city, player_id) {
const id = city+"_cubes_"+player_id;
const cubes_div = $(id);
cubes_div.addEventListener('mouseenter', (event) => {
this.onInfluenceCubesHover(event, city, true);
});
cubes_div.addEventListener('mouseleave', (event) => {
this.onInfluenceCubesHover(event, city, false);
});
cubes_div.addEventListener('click', (event) => {
this.onInfluenceCubesClick(event, city, player_id);
});
},
/**
* Put all the Location tiles in their slots.
* @param {array} players
* @param {rray} locationtiles
*/
setupLocationTiles: function(locationtiles) {
const tile_scale = 0.2;
// create player area for victory tiles
for (const player_id in this.gamedatas.players) {
const player_tiles = this.format_block('jstpl_victory_tiles', {id: player_id, scale: tile_scale});
dojo.place(player_tiles, $('player_board_'+player_id));
}
for (let loc of locationtiles) {
const slot = loc['slot'];
const location = loc['location'];
const tile = new perikles.locationtile(location);
const place = loc['loc'];
const tile_div = tile.createTile();
if (place == "board") {
const tileObj = dojo.place(tile_div, $("location_"+slot));
const lochtml = tile.createTooltip(this.getCityNameTr(tile.getCity()));
this.addTooltipHtml(tileObj.id, lochtml, '');
} else if (place == "unclaimed") {
this.createUnclaimedTilesBox();
const tileObj = dojo.place(tile_div, $("unclaimed_tiles"));
tileObj.style.margin = null;
const tt = tile.createVictoryTileTooltip();
this.addTooltipHtml(tileObj.id, tt, '');
} else if (place.startsWith("persia")) {
// this is the special case where a tile was claimed by multiple players sharing Persian control
const n = toint(place.slice(-1));
for (let i = 1; i <= n; i++) {
const persian_player = loc['persia'+i];
let tileObj = dojo.place(tile_div, $(persian_player+'_player_tiles'));
tileObj = this.makePersianVictoryTile(tileObj, i);
const tt = tile.createVictoryTileTooltip();
this.addTooltipHtml(tileObj.id, tt, '');
}
} else {
// player claimed
const victoryTile = dojo.place(tile_div, $(place+'_player_tiles'));
const tt = tile.createVictoryTileTooltip();
this.addTooltipHtml(victoryTile.id, tt, '');
}
}
this.displayPlayerVictoryTiles();
},
/**
* Put cubes in candidate spaces.
* @param {Object} candidates
*/
setupCandidates: function(candidates) {
for (const [cand, player_id] of Object.entries(candidates)) {
const cid = cand.split('_');
const city = cid[0];
const cube = this.createInfluenceCube(player_id, city, cid[1]);
const candidate = dojo.place(cube, $(cand));
candidate.addEventListener('click', (event) => this.onSelectCube(event));
}
},
/**
* Place Leader tokens on cities.
* @param {Object} leaders
*/
setupLeaders: function(leaders) {
for (const [city, player_id] of Object.entries(leaders)) {
this.createLeaderCounter(player_id, city, "leader");
}
},
/**
* Place all statues in city statue areas.
* @param {Object} statues
*/
setupStatues: function(statues) {
for (const [player_id, civs] of Object.entries(statues)) {
for (const [city, num] of Object.entries(civs)) {
for (let i = 0; i < toint(num); i++) {
this.createLeaderCounter(player_id, city, "statue");
}
}
}
},
/**
* For creating Leader and Statue counters.
* Places it in the zone.
* @param {int} player_id
* @param {string} city
* @param {string} type "leader" or "statue"
*/
createLeaderCounter: function(player_id, city, type) {
let counter_zone = $(city+"_leader");
let s = 0;
let tt = _("${player_name} is Leader of ${city_name}");
if (type == "statue") {
counter_zone = $(city+"_statues");
s = counter_zone.childElementCount;
tt = _("Statue of ${player_name} in ${city_name}");
}
const leaderhtml = this.format_block('jstpl_leader', {city: city, type: type, num: s});
const leader = dojo.place(leaderhtml, counter_zone);
leader.dataset.color = this.decorator.playerColor(player_id);
tt = tt.replace('${player_name}', this.decorator.spanPlayerName(player_id, this.isColorblind()));
tt = tt.replace('${city_name}', this.getCityNameTr(city));
this.addTooltip(leader.id, tt, '');
},
/**
* Create a cube div in player's color.
* @param {int} player_id
* @param {string} city
* @param {string} tag
* @returns html for colored influence cube
*/
createInfluenceCube: function(player_id, city, tag) {
const color = this.getPlayerColor(player_id);
const id = player_id+"_"+city+"_"+tag;
const cube = this.format_block('jstpl_cube', {id: id, color: color});
return cube;
},
/**
* Set up battle tokens in their boxes given current state.
* @param {Object} tokens {box id => num tokens}
*/
setupTokens: function(tokens) {
let i = 0;
for (let [box, count] of Object.entries(tokens)) {
for (let n = 0; n < count; n++) {
const token = this.format_block('jstpl_battle_token', {id: i++});
dojo.place(token, $(box));
}
}
},
/**
* For start of a combat. If tokens are not already present, place four new tokens in the center battle_tokens box.
*/
initializeBattleTokens: function() {
const tokens = $('perikles_map').getElementsByClassName("prk_battle_token");
if (tokens.length == 0) {
for (let i = 0; i < 4; i++) {
const token = this.format_block('jstpl_battle_token', {id: i});
dojo.place(token, $('battle_tokens'));
}
}
},
/**
* Move tokens from attacker/defender boxes back to center. Keep one if we have a victory from previous round.
* @param {string} (optional) winner "attacker" or "defender" or null
*/
returnBattleTokens(winner=null) {
let keep1 = null;
if (winner != null) {
keep1 = winner;
}
const attacker_tokens = $('attacker_battle_tokens').getElementsByClassName("prk_battle_token");
if (attacker_tokens.length == 0 && keep1 == "attacker") {
// attacker gets a starting token but there isn't one already in the attacker box
this.moveTokenToBattleSide(keep1);
} else {
[...attacker_tokens].forEach(t => {
if (keep1 == "attacker") {
keep1 = null;
} else {
this.slideToObjectRelative( t.id, 'battle_tokens', 1000, 500, null, "last" );
}
});
}
const defender_tokens = $('defender_battle_tokens').getElementsByClassName("prk_battle_token");
if (defender_tokens.length == 0 && keep1 == "defender") {
// defender gets a starting token but there isn't one already in the attacker box
this.moveTokenToBattleSide(keep1);
} else {
[...defender_tokens].forEach(t => {
if (keep1 == "defender") {
keep1 = null;
} else {
this.slideToObjectRelative( t.id, 'battle_tokens', 1000, 500, null, "last" );
}
});
}
},
/**
* Move one Battle Token from center box to attacker or defender.
* @param {string} side attacker or defender
*/
moveTokenToBattleSide: function(side) {
const token = $('battle_tokens').lastChild;
this.slideToObjectRelative(token.id, side+'_battle_tokens', 1000, 500, null, "last");
},
/**
* Place all military counters
* @param {Object} military
*/
setupMilitary: function(military, persianleaders) {
// first add Persia
this.createStack("persia");
// stack for each city
for (const city of CITIES) {
this.createStack(city);
}
for(const mil of military) {
const counter = this.militaryToCounter(mil);
if (counter.getLocation() == counter.getCity() && counter.getPosition() == 0) {
// in a city stack
counter.addToStack();
} else if (counter.getLocation() == DEAD_POOL) {
// in the dead pool
this.createMilitaryArea(DEAD_POOL, counter.getCity());
const counterObj = counter.placeCounterInContainer(DEAD_POOL);
counterObj.setAttribute("title", this.counterText(counter));
} else if (Object.keys(LOCATION_TILES).includes(counter.getLocation())) {
// sent to a battle
counter.placeBattle();
} else {
// it's in a player pool
const player_id = counter.getLocation();
// "_persia_" is special flag for controlled persian units
if (player_id == this.player_id || (player_id == "_persia_" && persianleaders.includes(String(this.player_id)))) {
this.createMilitaryArea(player_id, counter.getCity());
const counterObj = counter.placeCounterInContainer(player_id);
counterObj.setAttribute("title", this.counterText(counter));
}
}
}
// reinitialize tooltips
this.setCityStackTooltip("persia");
for (const city of CITIES) {
this.setCityStackTooltip(city);
}
},
/**
* Factory method: create a counter from the PHP object in datas.
* @param {Object} military
* @returns perikles.counter
*/
militaryToCounter: function(military) {
const city = military['city'];
const unit = military['type'];
const strength = military['strength'];
const id = military['id'];
const location = military['location'];
const position = military['battlepos'];
const counter = new perikles.counter(city, unit, strength, id, location, position);
return counter;
},
/**
* Create a military stack, add a tooltip.
* @param {string} city
*/
createStack: function(city) {
const stack = city+"_military";
this.stacks.decorateMilitaryStack(stack);
},
/**
* set tooltip for a city stack, depending on whether there is a stack there or not.
* @param {string} city
*/
setCityStackTooltip: function(city) {
const stack = city+"_military";
// get rid of previous tooltip
this.removeTooltip(stack);
tt = this.stacks.showStartingForces(city, this.spanCityName(city));
if ($(stack).childElementCount != 0) {
tt += '<div style="margin-top: 0.5em;">';
tt += _("Click to inspect stack");
tt += '<div>'
}
this.addTooltip(stack, tt, '');
},
/**
* Place Defeat counters on cities.
* @param {Object} defeats
*/
setupDefeats: function(defeats) {
for (let [city, num] of Object.entries(defeats)) {
for (let d = 1; d <= num; d++) {
this.addDefeatCounter(city, d);
}
}
},
/**
* Add event listeners to city divs.
*/
setupCities: function() {
for (const city of CITIES) {
$(city).addEventListener('mouseenter', () => {
this.onCityTouch(city, true);
});
$(city).addEventListener('mouseleave', () => {
this.onCityTouch(city, false);
});
$(city).addEventListener('click', () => {
this.onCityClick(city);
});
}
},
/**
* Show or hide the player board areas holding victory tiles.
*/
displayPlayerVictoryTiles: function() {
tilezones = document.getElementsByClassName("prk_player_tiles");
[...tilezones].forEach(z => {
z.style.display = (z.childElementCount == 0) ? 'none' : 'flex';
});
},
///////////////////////////////////////////////////
//// Display methods
/* @Override */
format_string_recursive : function(log, args) {
try {
if (log && args && !args.processed) {
args.processed = true;
if (args.player_name && args.player_id && this.gamedatas.players[args.player_id]) {
args.player_name = this.decorator.spanPlayerName(args.player_id, this.isColorblind());
}
if (args.actplayer) {
args.actplayer = args.actplayer.replace('color:#FFF;', 'color:#FFF;'+WHITE_OUTLINE);
}
if (args.candidate_name && args.candidate_id) {
args.candidate_name = this.decorator.spanPlayerName(args.candidate_id, this.isColorblind());
}
if (args.city_name && args.city) {
args.city_name = this.spanCityName(args.city);
}
if (args.city_name2 && args.city2) {
args.city_name2 = this.spanCityName(args.city2);
}
if (args.special_tile && args.icon) {
const specialtile = new perikles.specialtile(args.player_id, args.tile, false);
const specialhtml = specialtile.getLogDiv();
args.special_tile = '<span class="prk_special_log">'+args.special_tile+'</span>';
args.icon = specialhtml;
}
if (args.cubes && args.icon && !args.leader) {
let cubeicon = "";
for (let i = 0; i < args.cubes; i++) {
const cube = this.createInfluenceCube(args.player_id, args.city, "log");
cubeicon += cube;
}
args.icon = cubeicon;
}
if (args.token && args.icon) {
const token = this.format_block('jstpl_battle_token', {id: "log"});
args.icon = token;
}
if (args.location && args.icon && !args.casualty_log) {
const tile = new perikles.locationtile(args.location);
const tile_div = tile.createIcon();
let loc_msg = tile_div;
if (args.battlepos && args.type) {
loc_msg = '<div style="display: flex; flex-direction: row; align-items: center;">';
const counter = new perikles.counter(args.city, args.type, 0);
const mil_div = counter.toLogIcon();
if (toint(args.battlepos) > 2) {
// defender
loc_msg += tile_div + LEFT_ARROW + mil_div;
} else {
// attacker
loc_msg += mil_div + RIGHT_ARROW + tile_div;
}
loc_msg += '</div>';
}
args.icon = loc_msg;
}
// a battle
if (args.crt) {
args.att = '<span class="prk_special_log">'+args.att+'</span>';
args.def = '<span class="prk_special_log">'+args.def+'</span>';
}
if (args.crtroll) {
args.crtroll = '<br/>';
const hit = '<span class="prk_hit">'+_("Success")+'</span>';
const miss = '<span class="prk_miss">'+_("Failure")+'</span>';
args.attd1 = this.diceIcon(args.attd1, "attacker");
args.attd2 = this.diceIcon(args.attd2, "attacker");
args.defd1 = this.diceIcon(args.defd1, "defender");
args.defd2 = this.diceIcon(args.defd2, "defender");
args.atttotal = '<span class="prk_dicetotal">'+args.atttotal+'</span>';
args.deftotal = '<span class="prk_dicetotal">'+args.deftotal+'</span>';
args.atttarget = '<span class="prk_dicetotal">'+args.atttarget+'</span>';
args.deftarget = '<span class="prk_dicetotal">'+args.deftarget+'</span>';
args.atttotal = '<span>'+args.atttotal+'</span>';
args.atthit = args.atthit ? hit : miss;
args.defhit = args.defhit ? hit : miss;
}
// for slave revolt, show Hoplite counter
if (args.return_from && args.icon) {
const strength = args.strength;
counter = new perikles.counter("sparta", HOPLITE, strength, "slaverevolt_log");
const mil_html = counter.toRelativeDiv("inline-block");
args.icon = mil_html;
}
// choose unit from deadpool
if (args.deadpool) {
// for log message showing unit was chosen
if (args.deadpool === true && args.icon) {
const type = args.type;
const strength = args.strength;
const city = args.city;
counter = new perikles.counter(city, type, strength, "deadpool_log");
const mil_html = counter.toRelativeDiv("inline-block");
args.icon = mil_html;
} else {
// here it's displaying in the titlebar units to be chosen
log += '<br>';
for (const [id, unit] of Object.entries(args.deadpool)) {
const counter = new perikles.counter(unit.city, unit.type, unit.strength, "deadpool_select");
const mil_div = counter.toRelativeDiv("inline-block");
log += mil_div;
}
}
}
// assign casualties
if (args.casualty) {
const type = args.type;
const strength = args.strength;
const cities = args.cities;
log += '<br/>';
for (let c of cities) {
counter = new perikles.counter(c, type, strength, "casualty_select");
let mil_html = counter.toRelativeDiv("inline-block");
log += mil_html;
}
}
if (args.casualty_log && args.icon) {
const type = args.type;
const strength = args.strength;
const city = args.city;
counter = new perikles.counter(city, type, strength, "casualty_log");
const mil_html = counter.toRelativeDiv("inline-block");
args.icon = mil_html;
}
// defeat counter
if (args.defeats && args.icon) {
const city = args.city;
const def_ctr = this.createDefeatCounter(city, args.defeats+'_log');
args.icon = def_ctr;
}
// leader/statue counters
if (args.leader && args.icon) {
const leader = args.leader;
const player_id = args.player_id;
const city = args.city;
const color = this.decorator.playerColor(player_id);
const ldr_ctr = this.format_block('jstpl_leader_log', {city: city, type: leader, color: color});
args.icon = ldr_ctr;
}
if (!this.isSpectator) {
log = log.replace("You", this.decorator.spanYou(this.player_id), this.isColorblind());
if (args.committed) {
const commit_log = this.createCommittedUnits(args.committed);
log = log.replace('committed_forces', commit_log);
}
if (args.plague) {
const plague_btns = this.createPlagueButtons();
log += plague_btns;
}
if (args.alkibiades) {
const alkibiades_btns = this.createAlkibiadesButtons();
log += alkibiades_btns;
}
if (args.slaverevolt) {
const slaverevolt_btns = this.createSlaveRevoltButtons();
log += slaverevolt_btns;
}
}
}
} catch (e) {
console.error(log, args, "Exception thrown", e.stack);
}
return this.inherited(arguments);
},
/**
* Show all the units that have been assigned to send to battles and display in commit dialog.
* @param {Object} committed Object from args
* @returns html div
*/
createCommittedUnits: function(committed) {
let commit_log = "";
const attack_str = _("Send ${unit} to attack ${location}");
const defend_str = _("Send ${unit} to defend ${location}");
let counters = 0;
// if spent cube from city for extra units
const commit_city = committed.cube;
let extra_forces = "";
for (const[id, selected] of Object.entries(committed)) {
if (id != "cube") {
let commit_str = (selected.side == "attack" ? attack_str : defend_str);
const counter = new perikles.counter(selected.city, selected.unit, selected.strength, id+"_dlg");
let mil_html = counter.toRelativeDiv("inline-block");
commit_str = commit_str.replace('${unit}', mil_html);
const tile = new perikles.locationtile(selected.location);
let loc_html = tile.createTile(0, "commit_"+counter.getId());
loc_html = this.decorator.prependStyle(loc_html, 'display: inline-block');
commit_str = commit_str.replace('${location}', loc_html);
if (selected.cube) {
extra_forces += commit_str+'<br/>';
} else {
commit_log += commit_str+'<br/>';
}
counters++;
}
}
if (counters < 2) {
let commit_string = _("${num}/2 units assigned");
commit_string = commit_string.replace('${num}', counters);
commit_log = commit_string+'<br/>'+commit_log;
} else {
// option to spend Influence cube
commit_log += '<hr/>';
if (commit_city) {
let city_commit = _("Additional unit(s) committed from ${city}");
city_commit = city_commit.replace('${city}', this.spanCityName(commit_city));
commit_log += city_commit + '<br/>';
commit_log += extra_forces;
} else {
let spend_cubes_div = this.createSpendInfluenceDiv();
if (spend_cubes_div != null) {
let cubehtml = this.createInfluenceCube(this.player_id, 'commit', '');
cubehtml = this.decorator.prependStyle(cubehtml, "display: inline-block; margin-left: 5px;");
let msg = _("You may spend an Influence cube to send an additional 1 or 2 units from that city");
if (this.isPersianLeader(this.player_id)) {
msg = _("You may spend an Influence cube from any city to send an additional 1 or 2 units");
}
spend_cubes_div = msg+cubehtml+'<br/>'+spend_cubes_div;
commit_log += spend_cubes_div;
}
}
}
commit_log += '<br/>';
return commit_log;
},
/**
* Create die icon.
* @param {string} val
* @param {string} side "attacker" or "defender"
* @returns html icon
*/
diceIcon: function(val, side) {
const roll = toint(val);
const xoff = -33 * (roll-1);
const die_icon = this.format_block('jstpl_die', {x: xoff, side: side});
return die_icon;
},
/**
* Take a city name and put it in colored text and translate the name.
* @param {string} city