-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplanetunknown.js
More file actions
1759 lines (1549 loc) · 66.6 KB
/
Copy pathplanetunknown.js
File metadata and controls
1759 lines (1549 loc) · 66.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* Planet Unknown implementation : © Timothée Pecatte <tim.pecatte@gmail.com>, Emmanuel Albisser <emmanuel.albisser@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.
* -----
*
* planetunknown.js
*
* Planet Unknown user interface script
*
* In this file, you are describing the logic of your user interface, in Javascript language.
*
*/
var isDebug = window.location.host == 'studio.boardgamearena.com' || window.location.hash.indexOf('debug') > -1;
var debug = isDebug ? console.info.bind(window.console) : function () {};
define([
'dojo',
'dojo/_base/declare',
'ebg/core/gamegui',
'ebg/counter',
g_gamethemeurl + 'modules/js/Core/game.js',
g_gamethemeurl + 'modules/js/Core/modal.js',
g_gamethemeurl + 'modules/js/Players.js',
g_gamethemeurl + 'modules/js/Meeples.js',
g_gamethemeurl + 'modules/js/Cards.js',
], function (dojo, declare) {
const CIV = 'civ';
const WATER = 'water';
const ROVER = 'rover';
const TECH = 'tech';
const ENERGY = 'energy';
const BIOMASS = 'biomass';
const ALL_TYPES = [CIV, WATER, BIOMASS, ROVER, TECH];
const FLUX = 2;
return declare('bgagame.planetunknown', [customgame.game, planetunknown.players, planetunknown.meeples, planetunknown.cards], {
constructor() {
this._activeStates = ['chooseRotation'];
this._notifications = [
['chooseSetup', 200],
['confirmSetupObjectives', 1200],
['clearTurn', 200],
['refreshUI', 200],
['setupPlayer', 1200],
['placeTile', null],
['moveTrack', null],
['slideMeeple', null],
['slideMeeples', null],
['newRotation', 1400],
['endOfTurn', 100],
['destroyedMeeples', null],
['receiveBiomassPatch', null],
['takeCivCard', 1400],
['changeFirstPlayer', 1400],
['endOfGameTriggered', 1400],
['revealCards', 1400],
['newEventCard', 3500],
['peekNextEvent', 3500],
['chooseFluxTrack', null],
['midMessage', 1200],
['newCards', 1000],
['emptySlot', 1200],
['destroyCard', 1200],
['newObjectiveCard', 1200],
['scores', 200],
];
// Fix mobile viewport (remove CSS zoom)
this.default_viewport = 'width=740';
this.cardStatuses = {};
},
notif_midMessage(n) {},
notif_scores(n) {},
getSettingsSections() {
return {
layout: _('Layout'),
playerBoard: _('Player Board/Panel'),
gameFlow: _('Game Flow'),
other: _('Other'),
};
},
getSettingsConfig() {
return {
////////////////////
/// LAYOUT ///
playerBoardsLayout: {
default: 0,
name: _('Player boards layout'),
attribute: 'player-boards-layout',
type: 'select',
values: {
0: _('Individual view (tabbed layout)'),
1: _('Multiple view'),
},
section: 'layout',
},
boardSizes: {
default: 100,
name: _('Board size'),
type: 'slider',
sliderConfig: {
step: 3,
padding: 0,
range: {
min: [30],
max: [100],
},
},
section: 'layout',
},
//////////////////////
/// BOARD / PANELS ///
planetOverlay: {
default: 50,
name: _('Buildable cell overlay opacity'),
type: 'slider',
sliderConfig: {
step: 3,
padding: 0,
range: {
min: [30],
max: [90],
},
},
section: 'playerBoard',
},
//////////////////////
///// GAME FLOW //////
confirmMode: { type: 'pref', prefId: 103, section: 'gameFlow' },
confirmUndoableMode: {
type: 'pref',
prefId: 104,
section: 'gameFlow',
},
restartButtons: {
default: 1,
name: _('Restart turn buttons'),
type: 'select',
attribute: 'undoButtons',
values: {
0: _('Only "Restart turn" button'),
1: _('"Restart turn" and "Undo last step" buttons'),
2: _('Only "Undo last step" button'),
},
section: 'gameFlow',
},
//////////////////////
/////// OTHER ////////
depotIndicator: {
default: 1,
name: _('Personal depot indicator'),
type: 'select',
attribute: 'depot-indicator',
values: {
0: _('At the top'),
1: _('At the bottom'),
},
section: 'other',
},
};
},
isFloatingHand() {
return [0, 3].includes(parseInt(this.settings.handLocation));
},
openHand() {
if (this.isFloatingHand()) {
$('floating-hand-wrapper').dataset.open = 'hand';
}
},
openScoringHand() {
if (this.isFloatingHand()) {
$('floating-hand-wrapper').dataset.open = 'scoringHand';
}
},
/**
* Setup:
* This method 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 and when a player refreshes the game page (F5)
*
* Params :
* - mixed gamedatas : contains all datas retrieved by the getAllDatas PHP method.
*/
setup(gamedatas) {
debug('SETUP', gamedatas);
// Create a new div for "subtitle"
dojo.place("<div id='pagesubtitle'></div>", 'maintitlebar_content');
// Attribute to know what asset we are using for max appeal
$('ebd-body').dataset.startingAppeal = gamedatas.startingAppeal;
this.setupInfoPanel();
this.setupScoresModal();
this.setupPlayers();
this.setupCards();
this.setupPlayersScores();
this.setupTiles();
this.setupMeeples();
this.updateLastRoundBanner();
this.updateSusanCounters();
// this.setupTour();
this.inherited(arguments);
// Create a new div for "anytime" buttons
dojo.place("<div id='anytimeActions' style='display:inline-block'></div>", $('customActions'), 'after');
},
onLoadingComplete() {
this.updateLayout();
this.inherited(arguments);
},
onScreenWidthChange() {
if (this.settings) this.updateLayout();
},
onAddingNewUndoableStepToLog(notif) {
if (!$(`log_${notif.logId}`)) return;
let stepId = notif.msg.args.stepId;
$(`log_${notif.logId}`).dataset.step = stepId;
if ($(`dockedlog_${notif.mobileLogId}`)) $(`dockedlog_${notif.mobileLogId}`).dataset.step = stepId;
if (this.gamedatas && this.gamedatas.gamestate) {
let state = this.gamedatas.gamestate;
if (state.private_state) state = state.private_state;
if (state.args && state.args.previousSteps && state.args.previousSteps.includes(parseInt(stepId))) {
this.onClick($(`log_${notif.logId}`), () => this.undoToStep(stepId));
if ($(`dockedlog_${notif.mobileLogId}`))
this.onClick($(`dockedlog_${notif.mobileLogId}`), () => this.undoToStep(stepId));
}
}
},
undoToStep(stepId) {
this.stopActionTimer();
this.checkAction('actRestart');
this.takeAction('actUndoToStep', { stepId }, false);
},
notif_clearTurn(n) {
debug('Notif: restarting turn', n);
this.cancelLogs(n.args.notifIds);
},
notif_refreshUI(n) {
debug('Notif: refreshing UI', n);
this.clearPossible();
['cards', 'meeples', 'players', 'tiles'].forEach((value) => {
this.gamedatas[value] = n.args.datas[value];
});
this.setupMeeples();
this.setupTiles();
this.updatePlayersScores();
this.rotateSusan();
this.updateSusanCounters();
this.updatePlayersCounters();
this.updateHand();
this.updateCivCounters();
// this.forEachPlayer((player) => {
// this._scoreCounters[player.id].toValue(player.newScore);
// this._playerCounters[player.id]['income'].toValue(player.income);
// });
},
notif_endOfGameTriggered() {
debug('Notif: end of game triggered');
this.gamedatas.endOfGameTriggered = true;
this.updateLastRoundBanner();
},
onEnteringStateGameEnd(args) {
if ($('last-round')) $('last-round').remove();
},
updateLastRoundBanner() {
if (this.gamedatas.endOfGameTriggered) {
if (!$('last-round')) {
$('page-title').insertAdjacentHTML(
'beforeend',
`<div id="last-round">${_('This is the last round of the game!')}</div>`
);
}
} else {
if ($('last-round')) {
$('last-round').remove();
}
}
},
onUpdateActionButtons(stateName, args) {
// this.addPrimaryActionButton('test', 'test', () => this.testNotif());
this.inherited(arguments);
},
testNotif() {},
clearPossible() {
dojo.empty('pagesubtitle');
this.onHoverCell = null;
this.onClickCell = null;
let toRemove = ['tile-controls', 'tile-hover', 'btnRotateClockwise', 'btnRotateCClockwise', 'btnFlip'];
toRemove.forEach((eltId) => {
if ($(eltId)) $(eltId).remove();
});
if (this._chooseCardModal) this._chooseCardModal.destroy();
this._susanModal.hide();
$('susan-modal-footer').classList.remove('active');
this.inherited(arguments);
},
onEnteringState(stateName, args) {
debug('Entering state: ' + stateName, args);
if (this.isFastMode() && ![].includes(stateName)) return;
if (this._focusedPlayer != null && this._focusedPlayer != this.player_id && !this.isSpectator) {
this.goToPlayerBoard(this.player_id);
}
if (args.args && args.args.descSuffix) {
this.changePageTitle(args.args.descSuffix);
}
if (args.args && args.args.optionalAction) {
let base = args.args.descSuffix ? args.args.descSuffix : '';
this.changePageTitle(base + 'skippable');
}
if (this._activeStates.includes(stateName) && !this.isCurrentPlayerActive()) return;
if (args.args && args.args.optionalAction && !args.args.automaticAction) {
this.addSecondaryActionButton(
'btnPassAction',
_('Pass'),
() => this.takeAction('actPassOptionalAction'),
'restartAction'
);
}
// Undo last steps
if (args.args && args.args.previousSteps) {
args.args.previousSteps.forEach((stepId) => {
let logEntry = $('logs').querySelector(`.log.notif_newUndoableStep[data-step="${stepId}"]`);
if (logEntry) this.onClick(logEntry, () => this.undoToStep(stepId));
logEntry = document.querySelector(`.chatwindowlogs_zone .log.notif_newUndoableStep[data-step="${stepId}"]`);
if (logEntry) this.onClick(logEntry, () => this.undoToStep(stepId));
});
}
// Restart turn button
if (args.args && args.args.previousEngineChoices && args.args.previousEngineChoices >= 1 && !args.args.automaticAction) {
if (args.args && args.args.previousSteps) {
let lastStep = Math.max(...args.args.previousSteps);
if (lastStep > 0)
this.addDangerActionButton('btnUndoLastStep', _('Undo last step'), () => this.undoToStep(lastStep), 'restartAction');
}
// Restart whole turn
this.addDangerActionButton(
'btnRestartTurn',
_('Restart turn'),
() => {
this.stopActionTimer();
this.takeAction('actRestart');
},
'restartAction'
);
}
if (this.isCurrentPlayerActive() && args.args) {
// Anytime buttons
if (args.args.anytimeActions) {
args.args.anytimeActions.forEach((action, i) => {
let msg = action.desc;
msg = msg.log ? this.fsr(msg.log, msg.args) : _(msg);
msg = this.formatString(msg);
// if (action.source && action.source != '') {
// msg += ' (' + _(action.source) + ')';
// }
this.addPrimaryActionButton(
'btnAnytimeAction' + i,
msg,
() => this.askConfirmation(action.irreversibleAction, () => this.takeAction('actAnytimeAction', { id: i }, false)),
'anytimeActions'
);
});
}
}
// INCONSISTENT STATE
if (args.args && args.args.noNode && this.isCurrentPlayerActive()) {
$('pagemaintitletext').innerHTML = _(
'You are in an inconsistent state, please create a bug report explaining how you got there so we can fix it and then click that button to proceed'
);
this.addDangerActionButton('btnUnstuck', _('Unstuck table'), () => this.takeAction('actUnstuckGame', {}, false));
} else {
// Call appropriate method
var methodName = 'onEnteringState' + stateName.charAt(0).toUpperCase() + stateName.slice(1);
if (this[methodName] !== undefined) this[methodName](args.args);
}
},
//////////////////////////////
// ____ _ _
// / ___|| |_ __ _ _ __| |_
// \___ \| __/ _` | '__| __|
// ___) | || (_| | | | |_
// |____/ \__\__,_|_| \__|
//////////////////////////////
onEnteringStateChooseSetup(args) {
if (!args._private) return;
let selectedPlanet = null;
let selectedCorpo = null;
let selectedObj = null;
let selectedFlux = null;
let possibleObjs = Object.values(args._private.POCards);
// Display button only if all choices are made
let updateSelection = () => {
let canConfirm = false;
if (args._private.choice != undefined) {
let choice = args._private.choice;
canConfirm =
selectedPlanet != choice.planetId ||
selectedCorpo != choice.corporationId ||
selectedObj != choice.rejectedCardId ||
selectedFlux != choice.flux;
} else {
canConfirm = selectedPlanet != null && selectedCorpo != null && (selectedObj != null || possibleObjs.length == 0);
debug(selectedFlux, selectedFlux === null);
if (selectedCorpo == FLUX && selectedFlux === null) canConfirm = false;
}
if (canConfirm) {
// Add confirm button (only if choice is different from potential existing selection)
this.addPrimaryActionButton('btnConfirmChoice', _('Confirm'), () =>
this.takeAction(
'actChooseSetup',
{ planetId: selectedPlanet, corporationId: selectedCorpo, rejectedCardId: selectedObj, flux: selectedFlux },
false
)
);
} else if ($('btnConfirmChoice')) {
$('btnConfirmChoice').remove();
}
};
// PLANET
let selectPlanet = (planetId) => {
if (selectedPlanet !== null && selectedPlanet == planetId) {
$('pagesubtitle').innerHTML = this.formatString(_(PLANETS_DATA[planetId].desc));
return;
}
let container = $(`player-board-planet-${this.player_id}`);
let previousPlanet = container.querySelector('.planet');
if (previousPlanet) previousPlanet.remove();
container.insertAdjacentHTML('beforeend', this.tplPlanet(PLANETS_DATA[planetId], { id: this.player_id }));
$('pagesubtitle').innerHTML = this.formatString(_(PLANETS_DATA[planetId].desc));
this.attachRegisteredTooltips();
// Highlight button
if (selectedPlanet !== null) {
$(`selectPlanet${selectedPlanet}`).classList.remove('selected');
}
selectedPlanet = planetId;
$(`selectPlanet${selectedPlanet}`).classList.add('selected');
updateSelection();
};
let possiblePlanets = args._private.planets;
possiblePlanets.forEach((planetId) => {
this.addPrimaryActionButton(`selectPlanet${planetId}`, _(PLANETS_DATA[planetId].name), () => selectPlanet(planetId));
});
// Already made a selection => allow to change its mind
if (args._private.choice != null) {
selectPlanet(args._private.choice.planetId);
}
// No selection yet => let the user click on any
else {
selectPlanet(args._private.planets[0]);
}
$('customActions').insertAdjacentHTML('beforeend', '<div class="separator">|</div>');
// CORPO
let selectFlux = (type) => {
// Highlight button
if (selectedFlux !== null) {
$(`btn${selectedFlux}`).classList.remove('selected');
}
selectedFlux = type;
$(`btn${selectedFlux}`).classList.add('selected');
updateSelection();
};
let selectCorpo = (corpoId) => {
if (selectedCorpo !== null && selectedCorpo == corpoId) {
$('pagesubtitle').innerHTML = this.formatString(_(CORPOS_DATA[corpoId].desc));
return;
}
let container = $(`player-board-corporation-${this.player_id}`);
let previousCorpo = container.querySelector('.corporation');
if (previousCorpo) previousCorpo.remove();
container.insertAdjacentHTML('beforeend', this.tplCorporation(CORPOS_DATA[corpoId], { id: this.player_id }));
$('pagesubtitle').innerHTML = this.formatString(_(CORPOS_DATA[corpoId].desc));
this.attachRegisteredTooltips();
/////////////
// FLUX
if (corpoId == FLUX && !$('flux-selection')) {
$('customActions').insertAdjacentHTML('beforeend', `<div id="flux-selection">${this.formatIcon('flux')} : </div>`);
ALL_TYPES.forEach((type) => {
this.addSecondaryActionButton(
'btn' + type,
this.fsr('${type}', { type, type_name: type }),
() => selectFlux(type),
'flux-selection'
);
});
$('flux-selection').insertAdjacentHTML('beforeend', '<div class="separator">|</div>');
}
if (corpoId != FLUX && $('flux-selection')) {
$('flux-selection').remove();
}
/////////////
// Highlight button
if (selectedCorpo !== null) {
$(`selectCorpo${selectedCorpo}`).classList.remove('selected');
}
selectedCorpo = corpoId;
$(`selectCorpo${selectedCorpo}`).classList.add('selected');
updateSelection();
};
let possibleCorpos = args._private.corporations;
possibleCorpos.forEach((corpoId) => {
this.addPrimaryActionButton(`selectCorpo${corpoId}`, _(CORPOS_DATA[corpoId].name), () => selectCorpo(corpoId));
});
$('customActions').insertAdjacentHTML('beforeend', '<div class="separator">|</div>');
// Already made a selection => allow to change its mind
if (args._private.choice != null) {
selectCorpo(args._private.choice.corporationId);
if (args._private.choice.flux) selectFlux(args._private.choice.flux);
}
// No selection yet => let the user click on any
else {
selectCorpo(args._private.corporations[0]);
}
// OBJECTIVES
let selectObj = (objId) => {
if (selectedObj !== null) {
$(`card-${selectedObj}`).classList.remove('selected', 'selectedToDiscard');
}
selectedObj = objId;
$(`card-${selectedObj}`).classList.add('selected', 'selectedToDiscard');
updateSelection();
};
possibleObjs.forEach((card) => {
card.pId = this.player_id;
this.addCard(card);
this.onClick(`card-${card.id}`, () => selectObj(card.id));
});
// Already made a selection => allow to change its mind
if (args._private.choice != null && args._private.choice.rejectedCardId != null) {
selectObj(args._private.choice.rejectedCardId);
}
},
notif_chooseSetup(n) {
this.clearPossible();
this.updatePageTitle();
this.onEnteringStateChooseSetup(n.args.args);
},
notif_confirmSetupObjectives(n) {
debug('Notif: confirming objectives at setup', n);
n.args.cardIds.forEach((cardId) => {
this.slide(`card-${cardId}`, `private-objectives-${this.player_id}`);
});
[...$('pending-cards').querySelectorAll('.pocard-wrapper')].forEach((elt) => {
let id = parseInt(elt.id.split('-')[1]);
if (n.args.cardIds.includes(id)) return;
this.slide(elt, this.getVisibleTitleContainer(), {
destroy: true,
});
});
},
notif_setupPlayer(n) {
debug('Notif: finish setup of player', n);
let player = this.gamedatas.players[n.args.player_id];
if (this._focusedPlayer != null && this._focusedPlayer != player.id) {
this.goToPlayerBoard(player.id);
}
// Planet
let container = $(`player-board-planet-${player.id}`);
let previousPlanet = container.querySelector('.planet');
if (previousPlanet) previousPlanet.remove();
container.insertAdjacentHTML('beforeend', this.tplPlanet(PLANETS_DATA[n.args.planetId], player));
// Corpo
container = $(`player-board-corporation-${player.id}`);
let corpo = container.querySelector('.corporation');
corpo.dataset.id = n.args.corpoId;
// Meeples
n.args.meeples.forEach((meeple) => this.addMeeple(meeple));
},
onEnteringStateChooseRotationEngine(args) {
args.atomicAction = true;
this.onEnteringStateChooseRotation(args);
},
onEnteringStateChooseRotation(args) {
if (this.getPlayers().length < 3 && (!args || !args.atomicAction)) {
return;
}
this.addPrimaryActionButton('btnZoomIn', _('Zoom in on S.U.S.A.N.'), () => this._susanModal.show());
this._susanModal.show();
// Enable buttons in modal
$('susan-modal-footer').classList.add('active');
this.onClick('susan-rotate-cclockwise', () => {
this.gamedatas.susan.rotation++;
this.rotateSusan();
});
this.onClick('susan-rotate-clockwise', () => {
this.gamedatas.susan.rotation--;
this.rotateSusan();
});
this.onClick('btnConfirmSusanRotation', () => {
this._susanModal.hide();
if (args && args.atomicAction) this.takeAtomicAction('actChooseRotation', [this.gamedatas.susan.rotation]);
else this.takeAction('actChooseRotation', { rotation: this.gamedatas.susan.rotation });
});
// Add buttons in top bar
this.addSecondaryActionButton('btnSusanRotateCclockwise', '<svg><use href="#rotate-cclockwise-svg" /></svg>', () => {
this.gamedatas.susan.rotation++;
this.rotateSusan();
});
this.addPrimaryActionButton('btnSusanConfirmRotation', _('Confirm'), () => {
if (args && args.atomicAction) this.takeAtomicAction('actChooseRotation', [this.gamedatas.susan.rotation]);
else this.takeAction('actChooseRotation', { rotation: this.gamedatas.susan.rotation });
});
this.addSecondaryActionButton('btnSusanRotateClockwise', '<svg><use href="#rotate-clockwise-svg" /></svg>', () => {
this.gamedatas.susan.rotation--;
this.rotateSusan();
});
console.log(this._baseRotation);
[0, 1, 2, 3, 4, 5].forEach((i) => {
let extTile = $(`top-exterior-${i}`).querySelector('.tile-container');
if (extTile)
this.onClick(extTile, () => {
this.gamedatas.susan.rotation = i + this._baseRotation;
this.rotateSusan();
});
let intTile = $(`top-interior-${i}`).querySelector('.tile-container');
if (intTile)
this.onClick(intTile, () => {
this.gamedatas.susan.rotation = -this.gamedatas.susan.shift + i + this._baseRotation;
this.rotateSusan();
});
});
},
////////////////////////////////////////
// _____ _
// | ____|_ __ __ _(_)_ __ ___
// | _| | '_ \ / _` | | '_ \ / _ \
// | |___| | | | (_| | | | | | __/
// |_____|_| |_|\__, |_|_| |_|\___|
// |___/
////////////////////////////////////////
onEnteringStateSetupEngine(args) {
if (!this.isCurrentPlayerActive() && !this.isSpectator) {
this.addSecondaryActionButton('btnCancel', _('Cancel'), () => this.takeAction('actCancel', {}, false));
}
},
onUpdateActivitySetupEngine(args, status) {
if (status) {
if ($('btnCancel')) $('btnCancel').remove();
} else {
this.clearPossible();
this.addSecondaryActionButton('btnCancel', _('Cancel'), () => this.takeAction('actCancel', {}, false));
}
},
addActionChoiceBtn(choice, disabled = false) {
if ($('btnChoice' + choice.id)) return;
let desc = this.translate(choice.description);
desc = this.formatString(desc);
// Add source if any
let source = _(choice.source ? choice.source : '');
// if (choice.sourceId) {
// let card = { id: choice.sourceId };
// this.loadSaveCard(card);
// source = this.fsr('${card_name}', {
// i18n: ['card_name'],
// card_name: _(card.name),
// card_id: card.id,
// });
// }
if (source != '') {
desc += ` (${source})`;
}
this.addSecondaryActionButton(
'btnChoice' + choice.id,
desc,
disabled
? () => {}
: () => {
this.askConfirmation(choice.irreversibleAction, () => this.takeAction('actChooseAction', { id: choice.id }));
}
);
if (disabled) {
$(`btnChoice${choice.id}`).classList.add('disabled');
}
if (choice.description.args && choice.description.args.bonus_pentagon) {
$(`btnChoice${choice.id}`).classList.add('withbonus');
}
},
onEnteringStateResolveChoice(args) {
Object.values(args.choices).forEach((choice) => this.addActionChoiceBtn(choice, false));
Object.values(args.allChoices).forEach((choice) => this.addActionChoiceBtn(choice, true));
},
onEnteringStateImpossibleAction(args) {
this.addActionChoiceBtn(
{
choiceId: 0,
description: args.desc,
},
true
);
},
addConfirmTurn(args, action) {
this.addPrimaryActionButton('btnConfirmTurn', _('Confirm'), () => {
this.stopActionTimer();
this.takeAction(action);
});
const OPTION_CONFIRM = 103;
let n = args.previousEngineChoices;
let timer = Math.min(10 + 2 * n, 20);
this.startActionTimer('btnConfirmTurn', timer, this.prefs[OPTION_CONFIRM].value);
},
onEnteringStateConfirmTurn(args) {
this.addConfirmTurn(args, 'actConfirmTurn');
},
askConfirmation(warning, callback) {
if (warning === false || this.prefs[104].value == 0) {
callback();
} else {
// let msg = warning === true ? _('drawing card(s) from the deck or the discard') : warning;
let msg =
warning === true
? _(
"If you take this action, you won't be able to undo past this step because you will either draw card(s) from the deck or the discard, or someone else is going to make a choice"
)
: warning;
this.confirmationDialog(
msg,
// this.fsr(
// _("If you take this action, you won't be able to undo past this step because of the following reason: ${msg}"),
// { msg }
// ),
() => {
callback();
}
);
}
},
// Generic call for Atomic Action that encode args as a JSON to be decoded by backend
takeAtomicAction(action, args, warning = false) {
if (!this.checkAction(action)) return false;
this.askConfirmation(warning, () =>
this.takeAction('actTakeAtomicAction', { actionName: action, actionArgs: JSON.stringify(args) }, false)
);
},
///////////////////////////////////////
// _____ __ __ _
// | ____|/ _|/ _| ___ ___| |_ ___
// | _| | |_| |_ / _ \/ __| __/ __|
// | |___| _| _| __/ (__| |_\__ \
// |_____|_| |_| \___|\___|\__|___/
///////////////////////////////////////
onLeavingStatePlaceTile() {
[...$(`planet-${this.player_id}`).querySelectorAll('.planet-grid-cell')].forEach((elt) => {
delete elt.style.removeProperty('cursor');
});
},
onEnteringStatePlaceTile(args) {
// END OF GAME : keep a tile eventhough you cant place it
const impossible = args.descSuffix == 'impossible';
if (impossible) {
$('pagesubtitle').insertAdjacentHTML('beforeend', '<div id="tile-selector"></div>');
let selection = null;
const tiles = Object.keys(args.tiles);
tiles.forEach((tileId) => {
let o = $(`tile-${tileId}`).cloneNode(true);
o.id += '-selector';
$('tile-selector').insertAdjacentElement('beforeend', o);
this.onClick(o, () => {
// Existing placement => keep the same one
if (selection !== null) {
$(`tile-${selection}-selector`).classList.remove('selected');
}
selection = tileId;
$(`tile-${selection}-selector`).classList.add('selected');
this.addPrimaryActionButton('btnConfirm', _('Confirm'), () =>
this.takeAtomicAction('actPlaceTileNoPlacement', [tileId])
);
});
});
return;
}
if (args.descSuffix == 'skippablebiomass') {
this.addSecondaryActionButton('btnKeepIt', _('Keep it for later'), () =>
this.takeAtomicAction('actKeepBiomassPatch', [])
);
}
// REGULAR FLOW
let selection = null;
let rotation = 0;
let flipped = false;
let hoveredCell = null;
let pos = null;
let oPlanet = $(`planet-${this.player_id}`).querySelector('.planet-grid');
let planetId = $(`planet-${this.player_id}`).dataset.id;
// Add a visual representation on hover
oPlanet.insertAdjacentHTML(
'beforeend',
`<div id='tile-controls' class='inactive hovering'>
<div id='tile-controls-circle'>
<div id="tile-rotate-clockwise"><svg><use href="#rotate-clockwise-svg" /></svg></div>
<div id="tile-rotate-cclockwise"><svg><use href="#rotate-cclockwise-svg" /></svg></div>
<div id="tile-flip"><svg><use href="#flip-svg" /></svg></div>
<div id="tile-move-up"><i class="fa fa-long-arrow-up"></i></div>
<div id="tile-move-right"><i class="fa fa-long-arrow-right"></i></div>
<div id="tile-move-down"><i class="fa fa-long-arrow-down"></i></div>
<div id="tile-move-left"><i class="fa fa-long-arrow-left"></i></div>
<div id="tile-confirm-btn" class="action-button bgabutton bgabutton_blue">✓</div>
</div>
</div>`
);
oPlanet.insertAdjacentHTML('beforeend', this.tplTile({ type: '', state: 0 }, 'tile-hover'));
// Move selection to a given position
let moveSelection = (x, y, cell = null) => {
this.placeTile('tile-hover', x, y, this.player_id);
this.placeTile('tile-controls', x, y, this.player_id);
let pos = args.tiles[selection].find((p) => p.pos.x == x && p.pos.y == y);
let r = ((rotation % 4) + 4) % 4;
let valid = pos && pos.r.find((d) => d[0] == r && d[1] == flipped);
$('tile-hover').classList.toggle('invalid', !valid);
$('tile-hover').style.transform =
(this.getSideCell(planetId, x, y) == 1 ? 'translateX(7px)' : '') +
`rotate(${rotation * 90}deg) scaleX(${flipped ? -1 : 1})`;
$('tile-hover').querySelector('.tile-crosshairs').style.transform = `rotate(${-rotation * 90}deg)`;
let bottomCircle = $('tile-controls').offsetTop + $('tile-controls-circle').offsetHeight / 2;
// $('tile-controls-circle').classList.toggle('bottom', bottomCircle > $('tile-controls').parentNode.offsetHeight);
$('tile-controls').classList.toggle('invalid', !valid);
if (cell === null) {
cell = oPlanet.querySelector(`[data-x='${x}'][data-y='${y}']`);
}
if (cell) {
cell.style.cursor = valid ? 'pointer' : 'not-allowed';
}
// Update button status
if ($('btnConfirmBuild')) {
$('btnConfirmBuild').classList.toggle('disabled', !valid);
$('tile-confirm-btn').classList.toggle('disabled', !valid);
}
};
let updateSelection = () => {
if (hoveredCell) {
moveSelection(hoveredCell.dataset.x, hoveredCell.dataset.y, hoveredCell);
} else if (pos.x == 0 && pos.y == 0) {
moveSelection(0, 0);
}
};
// Add tile selectors in pagetitle
$('pagesubtitle').insertAdjacentHTML('beforeend', '<div id="tile-selector"></div>');
let callback = (tileId) => {
// Existing placement => keep the same one
if (selection !== null) {
$(`tile-${selection}-selector`).classList.remove('selected');
selection = tileId;
updateSelection();
}
// Otherwise, set it at (0,0) (not a real cell)
else {
selection = tileId;
pos = { x: 0, y: 0 };
rotation = 0;
flipped = false;
moveSelection(0, 0);
}
let oTile = $(`tile-${tileId}-selector`);
$('tile-hover').dataset.type = oTile.dataset.type;
$('tile-controls').dataset.type = oTile.dataset.type;
$('tile-hover').dataset.shape = oTile.dataset.shape;
$('tile-controls').dataset.shape = oTile.dataset.shape;
$('tile-hover').dataset.sprite = oTile.dataset.sprite;
$('tile-controls').dataset.sprite = oTile.dataset.sprite;
oTile.classList.add('selected');
// Compute new size of circle control
$('tile-controls').classList.remove('inactive');
let w = $('tile-hover').offsetWidth;
let h = $('tile-hover').offsetHeight;
let cross = $('tile-hover').querySelector('.tile-crosshairs');
let offsetW = cross.offsetLeft + cross.offsetWidth / 2;
let offsetH = cross.offsetTop + cross.offsetHeight / 2;
let dx = Math.max(offsetW, w - offsetW);
let dy = Math.max(offsetH, h - offsetH);
let radius = Math.sqrt(dx * dx + dy * dy) + 10;
$('tile-controls-circle').style.width = 2 * radius + 'px';
$('tile-controls-circle').style.height = 2 * radius + 'px';
this.addPrimaryActionButton('btnRotateCClockwise', '<i class="fa fa-undo"></i>', () => incRotation(-1));
this.addPrimaryActionButton('btnFlip', '<i class="fa fa-arrows-h"></i>', () => flipTile());
this.addPrimaryActionButton('btnRotateClockwise', '<i class="fa fa-repeat"></i>', () => incRotation(1));
};
const buildableTiles = Object.keys(args.tiles);
buildableTiles.forEach((tileId) => {
let o = $(`tile-${tileId}`).cloneNode(true);
o.id += '-selector';
$('tile-selector').insertAdjacentElement('beforeend', o);
this.onClick(o, () => callback(tileId));
});
if (buildableTiles.length == 1) {
callback(buildableTiles[0]);
}