-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvektorace.js
2820 lines (2129 loc) · 128 KB
/
vektorace.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>
* Vektorace implementation : © <Pietro Luigi Porcedda> <pietro.l.porcedda@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.
* -----
*/
define([
"dojo","dojo/_base/declare",
"ebg/core/gamegui",
"ebg/counter",
"ebg/scrollmap"],
function(dojo, declare, other) {
return declare("bgagame.vektorace", ebg.core.gamegui, {
//++++++++++++++++++++++++//
// SETUP AND GLOBALS INIT //
//++++++++++++++++++++++++//
//#region setup
constructor: function() {
//console.log('vektorace constructor');
// GLOBAL VARIABLES INIT
// useful measures to rescale octagons and calculate distances between them. actually they should be never used, all geometric calculation should be done by server.
// these measure should be set always using setOctagonSize(size), which given a certain octagon size (length of one side of the square box that contains the octagon), it calculates all deriving measures
this.octSize; // length of the side of the square box containing the octagon
this.octSide; // length of each side of the octagon
this.octRad; // radius of the circle that inscribe the octagon. or distance between octagon center and any of its vertecies
this.octSeg; // segment measuring half of the remaining length of box size, minus the length of the octagon side. or the cathetus of the right triangle formed on the diagonal sides of the octagon.
// keeps track of the current scale of the interface
this.interfaceScale;
this.zoomLimit;
// init counters object
this.counters = {};
this.previewsLocked = false;
},
// setup: method called each time interface loads. should set up game sistuation according to db.
// argument 'gamedatas' cointains data extracted with getAllDatas() game.php method. it is also kept as a global variable as this.gamedatas (function to update it should exist but it should also be unnecessary)
setup: function(gamedatas) {
//console.log("Starting game setup");
// -- EXTRACT OCTAGON REFERENCE MEASURES --
// actually permanent since all rescaling is done with css transform
this.octSize = parseInt(gamedatas.octagon_ref['size']);
this.octSide = parseInt(gamedatas.octagon_ref['side']);
this.octSeg = parseInt(gamedatas.octagon_ref['corner_segment']);
this.octRad = parseInt(gamedatas.octagon_ref['radius']);
// -- SETUP PLAYER BOARDS --
this.counters.playerBoard = {};
for (let player_id in gamedatas.players) {
let player = gamedatas.players[player_id];
this.counters.playerBoard[player_id] = {};
// create all icon elements
let player_board_div = $('player_board_'+player_id);
dojo.place( this.format_block('jstpl_player_board', {
id: player_id,
gear: this.format_block('jstpl_current_gear', { id: player_id, n: player['currGear']}),
lap: this.format_block('jstpl_lap_counter', { id: player_id, tot: gamedatas.game_info['laps']}),
standings: this.format_block('jstpl_standings_position', { id: player_id}),
tire: this.format_block('jstpl_tokens_counter', { id: player_id, type: 'tire'}),
nitro: this.format_block('jstpl_tokens_counter', { id: player_id, type: 'nitro'})
} ), player_board_div );
// create and initiate counter for each counting icon
document.querySelectorAll(`#itemsBoard_${player_id} .pbCounter`).forEach( el => {
let counter = new ebg.counter();
counter.create(el);
let propertyName = el.id.substring(0,el.id.indexOf('_'));
counter.setValue(player[propertyName]);
this.counters.playerBoard[player_id][propertyName] = counter; // store counter in global object
});
this.addTooltip('pb_tireTokens_p'+player_id,_("Tire token reserve. Tire tokens are used to decellerate and perform extreme maneuvers"), '');
this.addTooltip('pb_nitroTokens_p'+player_id,_("Nitro token reserve. Nitro tokens are used to accelerate, use boost vectors and perform the slingshot pass"), '');
this.addTooltip('pb_turnPos_p'+player_id,_("Player's car race position, which also determines the turn order"), '');
this.addTooltip('pb_lapNum_p'+player_id,_("Player's current lap"), '');
this.addTooltip('pb_gearInd_p'+player_id,_("Player's current gear"), '');
}
// to properly render icon on screen, iconize it
document.querySelectorAll('.pbIcon').forEach( (el) => { this.iconize(el, 30) });
document.querySelectorAll('.standingsIcon,.lapIcon').forEach( (el) => { el.parentElement.style.filter = 'drop-shadow(0px 0px 0px rgb(0,0,0,0))'; }); // remove shadow from some icons (not pretty)
// -- SET INITIAL INTERFACE SCALE --
this.interfaceScale = 3
this.zoomLimit = true;
this.scaleInterface();
// -- SET VIEWPORT
/* this.default_viewport = "width=" + this.interface_min_width;
this.onScreenWidthChange(); */
// -- SCROLLMAP INIT --
// (copied from doc)
this.scrollmap = new ebg.scrollmap(); // object declaration (can also go in constructor)
// make map scrollable
this.scrollmap.create( $('map_container'),$('map_scrollable'),$('map_surface'),$('map_scrollable_oversurface') );
// -- SET MAP IMG --
if (gamedatas.game_info['map'] == 2) {
document.querySelector('#track_img #top_left').classList.add('indianottolis');
document.querySelector('#track_img #top_right').classList.add('indianottolis');
document.querySelector('#track_img #bottom_left').classList.add('indianottolis');
document.querySelector('#track_img #bottom_right').classList.add('indianottolis');
this.displayTrackGuides(gamedatas.game_info['circuit_layout']);
$('game_elements').classList.add('nocurves');
} else {
document.querySelector('#track_img #top_left').classList.add('default');
document.querySelector('#track_img #top_right').classList.add('default');
document.querySelector('#track_img #bottom_left').classList.add('default');
document.querySelector('#track_img #bottom_right').classList.add('default');
}
// made a custom handler for map buttons. bottom button is broken anyway
// this.scrollmap.setupOnScreenArrows( 150 ); // this will hook buttons to onclick functions with 150px scroll step
document.querySelectorAll('.map_button').forEach( el => {
el.addEventListener('click', evt => {
let scrollStep = 300 * Math.pow(0.8,this.interfaceScale);
let scroll = {
dx: 0,
dy: 0
};
if (el.className.includes('top'))
scroll.dy = scrollStep;
else if (el.className.includes('down'))
scroll.dy = -scrollStep;
else if (el.className.includes('left'))
scroll.dx = scrollStep;
else if (el.className.includes('right'))
scroll.dx = -scrollStep;
this.scrollmap.scroll(scroll.dx, scroll.dy);
});
});
this.addTooltip('button_zoomIn',_('Zoom in map'),'');
$("button_zoomIn").addEventListener('click', evt => {
dojo.stopEvent(evt);
let map = $("map_surface");
this.zoomMap(0.5,map.offsetWidth/2,map.offsetHeight/2);
});
this.addTooltip('button_zoomOut',_('Zoom out map'),'');
$("button_zoomOut").addEventListener('click', evt => {
dojo.stopEvent(evt);
let map = $("map_surface");
this.zoomMap(-0.5,map.offsetWidth/2,map.offsetHeight/2);
});
this.addTooltip('button_fitMap',_('Fit map to view'),'');
$("button_fitMap").addEventListener('click', evt => {
dojo.stopEvent(evt);
let map = $("map_surface");
this.interfaceScale = 11 - (Math.round((map.offsetHeight/100)*2)/2) + 0.5;
let x = 550 * Math.pow(0.8,this.interfaceScale);
let y = 700 * Math.pow(0.8,this.interfaceScale);
this.scrollmap.scrollto(-x,y);
this.scaleInterface();
});
this.addTooltip('button_scrollToCar',_('Center map to your car'),'');
$("button_scrollToCar").addEventListener('click', evt => {
dojo.stopEvent(evt);
this.interfaceScale = 2;
let car = this.getPlayerCarElement(this.getCurrentPlayerId());
let x = parseInt(car.style.left) * Math.pow(0.8,this.interfaceScale);
let y = -parseInt(car.style.top) * Math.pow(0.8,this.interfaceScale);
this.scrollmap.scrollto(-x,y);
this.scaleInterface();
})
// -- DIALOG WINDOW INIT --
// (copied from doc)
this.gearSelDW = new ebg.popindialog();
this.gearSelDW.create( 'GearSelectionDialogWindow' );
this.gearSelDW.setTitle( _("Select a gear vector to declare") );
this.gearSelDW.setMaxWidth( 600 );
// -- PLACE TABLE ELEMENTS ACCORDING TO DB --
for (let i in gamedatas.game_element) {
let el = gamedatas.game_element[i];
switch (el.entity) {
case 'pitwall':
let pw = this.createGameElement('pitwall');
this.placeOnTrack(pw, el.pos_x, el.pos_y, el.orientation);
//pw.style.transform += 'scale(0.75)';
break;
case 'curve':
let cur = this.createGameElement('curve', {n: el.id});
this.placeOnTrack(cur, el.pos_x, el.pos_y, el.orientation);
$('delimiters').insertAdjacentHTML('beforeend',this.format_block('jstpl_curveDelimiter',{left: +el.pos_x, top: -el.pos_y, rot: el.orientation*-45}));
break;
case 'car':
let car = this.createGameElement('car', {color: gamedatas.players[el.id].color});
if (el.pos_x && el.pos_y) this.placeOnTrack(car, el.pos_x, el.pos_y, el.orientation);
else {
this.placeOnTrack(car, 0, 0, el.orientation);
car.style.display = 'none';
}
let penAndMod = gamedatas.penalities_and_modifiers[el.id];
for (const pm in penAndMod) {
if (penAndMod[pm]==1 && pm!='player') {
if (pm == 'stop') {
document.querySelectorAll('.marker').forEach(el=>el.remove());
}
this.addMarker(el.id,pm);
}
}
break;
case 'gearVector':
let gv = this.createGameElement('gearVector', {n: el.id});
this.placeOnTrack(gv, el.pos_x, el.pos_y, el.orientation);
break;
case 'boostVector':
let bv = this.createGameElement('boostVector', {n: el.id});
this.placeOnTrack(bv, el.pos_x, el.pos_y, el.orientation);
break;
// curves and curbs not displayed
}
}
// -- CONNECT USER INPUT --
document.querySelector('#map_surface').addEventListener('wheel',(evt) => {
// format input wheel delta and calls method to scale interface accordingly
// ! MAY VARY ON LAPTOPS AND TOUCH DEVICES !
dojo.stopEvent(evt);
this.zoomMap((evt.wheelDelta / 120)/2, evt.offsetX, evt.offsetY);
}); // zoom wheel
// -- DEBUG INPUT --
/* document.querySelector('#map_container').addEventListener('click',(evt) => {
dojo.stopEvent(evt);
//console.log(this.mapOffsetToCoords(evt.offsetX, evt.offsetY));
}); */
// -- SETUP ALL NOTIFICATION --
this.setupNotifications();
this.setupPreference();
// -- add iOS rule
if (/iPad|iPhone|iPod/.test(navigator.userAgent)) {
document.documentElement.classList.add('ios-user');
}
// set game shadows to no for ios and safari devices
/* if (document.documentElement.className.includes('dj_safari') || document.documentElement.className.includes('ios-user'))
this.updatePreference(103,2); */
// set move confirmation to yes for touch devices
/* if ($('ebd-body').className.includes(' touch-device'))
this.updatePreference(101,1); */
$("button_fitMap").click();
//console.log( "Ending game setup" );
// Load production bug report handler
/* dojo.subscribe("loadBug", this, function loadBug(n) {
function fetchNextUrl() {
var url = n.args.urls.shift();
console.log("Fetching URL", url);
dojo.xhrGet({
url: url,
load: function (success) {
console.log("Success for URL", url, success);
if (n.args.urls.length > 0) {
fetchNextUrl();
} else {
console.log("Done, reloading page");
window.location.reload();
}
},
});
}
console.log("Notif: load bug", n.args);
fetchNextUrl();
}); */
},
// imported from doc
setupPreference: function () {
// Extract the ID and value from the UI control
var _this = this;
function onchange(e) {
var match = e.target.id.match(/^preference_[cf]ontrol_(\d+)$/);
if (!match) {
return;
}
var prefId = +match[1];
var prefValue = +e.target.value;
_this.prefs[prefId].value = prefValue;
_this.onPreferenceChange(prefId, prefValue);
}
// Call onPreferenceChange() when any value changes
dojo.query(".preference_control").connect("onchange", onchange);
// Call onPreferenceChange() now
dojo.forEach(
dojo.query("#ingame_menu_content .preference_control"),
function (el) {
onchange({ target: el });
}
);
},
updatePreference: function(prefId, newValue) {
// Select preference value in control:
dojo.query('#preference_control_' + prefId + ' > option[value="' + newValue
// Also select fontrol to fix a BGA framework bug:
+ '"], #preference_fontrol_' + prefId + ' > option[value="' + newValue
+ '"]').forEach((value) => dojo.attr(value, 'selected', true));
// Generate change event on control to trigger callbacks:
const newEvt = new CustomEvent('change', {bubbles: false, cancelable: true});
$('preference_control_' + prefId).dispatchEvent(newEvt);
},
onPreferenceChange: function (prefId, prefValue) {
//console.log("Preference changed", prefId, prefValue);
switch (prefId) {
// display guides
case 102:
if (prefValue == 1) {
$('delimiters').style.setProperty('--visibility', 'unset');
} else {
$('delimiters').style.setProperty('--visibility', 'hidden');
}
break;
// display shadow
case 103:
if (prefValue == 1) {
document.documentElement.style.setProperty('--game-element-shadow', `drop-shadow(1px 1px 0px rgb(0,0,0,0.7))drop-shadow(1px 1px 0px rgb(0,0,0,0.7))drop-shadow(1px 1px 0px rgb(0,0,0,0.7))drop-shadow(0px 0px 2px rgb(0,0,0,0.7))drop-shadow(0px 0px 0px rgb(0,0,0,0.7))`);
} else {
document.documentElement.style.setProperty('--game-element-shadow', 'unset');
}
break;
// display illegal pos
case 104:
if (prefValue == 1) {
document.documentElement.style.setProperty('--display-illegal', 'unset');
} else {
document.documentElement.style.setProperty('--display-illegal', 'none');
}
break;
default:
break;
}
},
/* // To be overrided by games
onScreenWidthChange: function () {
// Remove broken "zoom" property added by BGA framework
this.gameinterface_zoomFactor = 1;
$("page-content").style.removeProperty("zoom");
console.log($("page-content").style.zoom);
$("page-title").style.removeProperty("zoom");
$("right-side-first-part").style.removeProperty("zoom");
},
*/
//#endregion
//+++++++++++++++++++++++//
// STATE CHANGE HANDLERS //
//+++++++++++++++++++++++//
//#region states
// [methods that apply changes to the interface (and regulates action buttons) depending on game state]
// onEnteringState: method called each time game enters a new game state.
// used to perform UI changes at beginning of a new game state.
// arguments are symbolic state name (needed for internal mega switch) and state arguments extracted by the corresponding php methods (as stated in states.php)
onEnteringState: function(stateName,args) {
//console.log('Entering state: '+stateName);
//console.log('State args: ',args.args);
$('previews').style.display = (this.isCurrentPlayerActive())? '' : 'none';
switch(stateName) {
case 'assignTurnOrder':
if (!this.isCurrentPlayerActive()) return;
dojo.place(this.format_block('jstpl_orderSelWindow', {playersNum: args.args['num']}),'game_play_area','first');
args.args.players.forEach(p => {
$('orderSelContainer').innerHTML += this.format_block('jstpl_orderSelPlayer',{
id: p.id,
name: p.nick,
color: p.col,
curr: p.curr,
playersNum: args.args['num']
});
});
// handler on input value change. sets min and max value and color number red if duplicate
document.querySelectorAll('.orderSelPlayer input').forEach(orderIn => {
orderIn.addEventListener('change', (evt) => {
orderIn.value = Math.min(Math.max(orderIn.value, orderIn.min), orderIn.max);
document.querySelectorAll('.orderSelPlayer input').forEach(in1 => {
in1.style.color = 'black';
document.querySelectorAll('.orderSelPlayer input').forEach(in2 => {
if (in1.value == in2.value && in1 != in2) {
in1.style.color = 'red';
}
});
});
});
});
if (!args.args.ranking) $('orderSelOrderBy').style.display = 'none';
$('orderSelOrderBy').addEventListener('click', (evt) => {
if (!args.args.ranking) {
this.showMessage(_("You cannot sort by ELO on a training game"),"error");
return;
}
let orderedPlayers = args.args.players;
orderedPlayers.sort((p1, p2) => $('player_elo_'+p1.id).innerHTML - $('player_elo_'+p2.id).innerHTML);
orderedPlayers.forEach((p,i) => {
document.querySelector(`#orderSelPlayer_${p.id} input`).value = i+1;
});
})
this.addActionButton('confirmInitOrder_button',_('Confirm'),() => {
var BreakException = {};
try {
document.querySelectorAll('.orderSelPlayer input').forEach(in1 => {
document.querySelectorAll('.orderSelPlayer input').forEach(in2 => {
if (in1.value == in2.value && in1 != in2) {
this.showMessage(_("Two players cannot have the same position"),"error");
throw BreakException;
}
});
});
} catch (e) {
return;
}
let retPlayers = [];
document.querySelectorAll('.orderSelPlayer').forEach(sp => {
retPlayers[document.querySelector(`#${sp.id} input`).value-1] = sp.id.split('_').pop();
})
this.ajaxcallwrapper('assignInitialOrder',{order: retPlayers.join(',')});
});
break;
case 'firstPlayerPositioning':
//debug
/* document.querySelector('#map_container').addEventListener('click',(evt) => {
dojo.stopEvent(evt);
this.ajaxcallwrapper('testCollision', this.mapOffsetToCoords(evt.offsetX, evt.offsetY));
console.log(this.mapOffsetToCoords(evt.offsetX, evt.offsetY));
}); */
// OLD VERSION, POSITION OF AREA RELATIVE TO PITWALL
// place positioning area as continuation of pitlane line
/* dojo.place( this.format_block('jstpl_posArea'), 'pos_highlights' );
this.placeOnTrack('start_positioning_area',args.args.anchorPos.x,args.args.anchorPos.y,0);
$('start_positioning_area').style.transformOrigin = 'bottom left'
$('start_positioning_area').style.transform = `translate(0,-100%) rotate(${args.args.rotation*45}deg)`; */
// NEW VERSION, POSITION OF AREA FIXED ON MAP COORDINATES
dojo.place( this.format_block('jstpl_posArea'), 'pos_highlights' );
this.placeOnTrack('start_positioning_area',args.args.center.x,args.args.center.y,0);
$('start_positioning_area').style.transform = "translate(-50%,-50%)";
// connect it to input handlers
if(!this.isCurrentPlayerActive()) return;
$('start_positioning_area').addEventListener('click', evt => {
dojo.stopEvent(evt);
if (this.prefs[101].value == 1) {
if (!this.isCurrentPlayerActive()) {
this.showMessage(_("It is not your turn"),"error");
return;
}
this.previewsLocked = true;
this.previewStartCarPos(evt,false);
$('previews').style.filter = 'drop-shadow( 0px 0px 4px red)';
if (!$('confirmFirstPositioning_button'))
this.addActionButton('confirmFirstPositioning_button',_('Confirm'), () => {
this.ajaxcallwrapper('placeFirstCar', {
x: parseInt($('car_preview').style.left),
y: -(parseInt($('car_preview').style.top))
}, null, true);
});
} else {
this.ajaxcallwrapper('placeFirstCar', {
x: parseInt($('car_preview').style.left),
y: -(parseInt($('car_preview').style.top))
}, null, true);
}
})
dojo.query('#start_positioning_area').connect('mousemove',this,'previewStartCarPos');
$('start_positioning_area').addEventListener('mouseleave', evt => {
dojo.stopEvent(evt);
if (!this.previewsLocked)
dojo.empty('previews')
});
break;
case 'flyingStartPositioning':
let askForRef = args.descriptionmyturn; // original descritipion asks to click on reference car
let askForPos = _('${you} must choose a starting position');
// set anchor elements on reference cars
args.args.positions.forEach(refcar => {
if (refcar.hasValid) {
let player = refcar.carId;
let pos = refcar.coordinates;
dojo.place(
this.format_block('jstpl_refCarAnchor',{ car: player }),
'car_highlights'
);
this.placeOnTrack('refCar_'+player, pos.x, pos.y);
}
});
this.gamedatas.gamestate.args.refCar = '';
// connect each anchor to handler
document.querySelectorAll('.refCarAnchor').forEach(el => el.addEventListener('click', evt => {
dojo.stopEvent(evt);
let refId = evt.target.id.split('_').pop(); // extract car id from anchor id
// clean interface from previously elements added by this handler
$('pos_highlights').innerHTML = '';
$('previews').innerHTML = '';
document.querySelectorAll('.fsOctagon').forEach( el => el.remove());
// if clicked ref is same as before, clear stored refCar id and return
if (refId == this.gamedatas.gamestate.args.refCar) this.gamedatas.gamestate.args.refCar = '';
else { // display all fs pos
this.gamedatas.gamestate.args.refCar = refId; // set new current reference
// find refCar object inside args
let refCar = args.args.positions.filter(ref => ref.carId == refId).pop();
// make array with all selOct pos and call method to display them
let positions = [];
refCar.positions.forEach(element => {
positions.push(element.coordinates);
});
this.displaySelectionOctagons(positions);
document.querySelectorAll(`.selectionOctagon`).forEach( el => {
if (!refCar.positions[el.dataset.posIndex].valid) {
el.className = el.className.replace('standardPos','illegalPos');
}
});
// display fs octagon too
refCar.FS_octagons.forEach((oct,i) => {
dojo.place(this.format_block('jstpl_FS_octagon'),'track');
el = $('track').lastElementChild;
el.style.left = oct.x +'px';
el.style.top = -oct.y +'px';
el.style.transform = this.getPlayerCarElement(this.getActivePlayerId()).style.transform;
el.style.transform += `rotate(${(i+1)*-45}deg)`;
if (i==1) el.style.zIndex = 1;
});
// finally connect all pos to handlers
this.connectPosHighlights(
evt => {
if (this.prefs[101].value == 1) {
if (!this.isCurrentPlayerActive()) {
this.showMessage(_("It is not your turn"),"error");
return;
}
let pos = args.args.positions.filter(ref => ref.carId == this.gamedatas.gamestate.args.refCar).pop();
pos = pos.positions[evt.target.dataset.posIndex];
if (!pos.valid) {
this.showMessage(_('Illegal car position'),'error');
return;
}
this.gamedatas.gamestate.args.chosePos = {
ref: this.gamedatas.gamestate.args.refCar,
pos: evt.target.dataset.posIndex,
};
this.previewsLocked = true;
$('previews').innerHTML = '';
this.previewCarPos(evt,false);
document.querySelectorAll('.selectionOctagon').forEach(el => el.style.filter = '');
evt.target.style.filter = 'drop-shadow( 0px 0px 10px red)';
if (!$('confirmFSposition_button'))
this.addActionButton('confirmFSposition_button',_('Confirm'), () => {
this.ajaxcallwrapper('placeCarFS', this.gamedatas.gamestate.args.chosePos, null, true);
});
}
else {
this.ajaxcallwrapper('placeCarFS', {
ref: this.gamedatas.gamestate.args.refCar,
pos: evt.target.dataset.posIndex},
null, true);
}
},
this.previewCarPos
);
}
// update page title depending on action (choose ref car or choose car pos )
if (this.gamedatas.gamestate.args.refCar == '') {
this.gamedatas.gamestate.descriptionmyturn = askForRef;
this.updatePageTitle();
} else {
this.gamedatas.gamestate.descriptionmyturn = askForPos;
this.updatePageTitle();
}
}));
// if there's only one reference car, pre-click on it
if (document.querySelectorAll('.refCarAnchor').length == 1) document.querySelector('.refCarAnchor').click();
break;
case 'tokenAmountChoice':
if(!this.isCurrentPlayerActive()) return;
let baseTire = parseInt(args.args.tire);
let baseNitro = parseInt(args.args.nitro);
// func that creates and displays window to select token amount
this.displayTokenSelection(baseTire,baseNitro, args.args.amount);
this.addActionButton('confirmTokenAmount', _('Confirm'), () => {
this.ajaxcallwrapper('chooseTokensAmount',{ tire: this.gamedatas.gamestate.args.tire, nitro: this.gamedatas.gamestate.args.nitro});
}, null, false, 'blue');
if (baseTire == 0 && baseNitro == 0) {
document.querySelectorAll('.tokenIncrementer > input').forEach( el => el.value = 4);
this.gamedatas.gamestate.args.tire = 4;
this.gamedatas.gamestate.args.nitro = 4;
}
break;
case 'greenLight':
if(!this.isCurrentPlayerActive()) return;
// add putton that displays vector selection in 'green light' mode
this.addActionButton('showGearSelDialogButton', _('Show selection'), () => {
this.displayGearSelDialog(args.args.gears);
}, null, false, 'blue');
if (this.prefs[100].value == 1 && !this.isReadOnly())
setTimeout(() => { $('showGearSelDialogButton').click();}, 10);
break;
case 'gearVectorPlacement':
// push all positions coordinates to array and pass it to method to display selection octagons for each pos
let vecAllPos = [];
args.args.positions.forEach(pos => {
vecAllPos.push(pos.anchorCoordinates);
});
this.displaySelectionOctagons(vecAllPos); // display vector attachment position in front of the car
this.connectPosHighlights(
// click handler
evt => {
dojo.stopEvent(evt);
this.gamedatas.gamestate.args.chosenPos = args.args.positions[parseInt(evt.target.dataset.posIndex)];
if (this.prefs[101].value == 1) {
if (!this.isCurrentPlayerActive()) {
this.showMessage(_("It is not your turn"),"error");
return;
}
if (this.gamedatas.gamestate.args.chosenPos.denied) {
this.showMessage(_("Gear vector position denied for the shunting you previously suffered"),"error");
return;
}
if (!this.gamedatas.gamestate.args.chosenPos.legal) {
this.showMessage(_("Illegal gear vector position"),"error");
return;
}
if (this.gamedatas.gamestate.args.chosenPos.offTrack) {
this.showMessage(_("You cannot pass a curve from behind"),"error");
return;
}
if (!this.gamedatas.gamestate.args.chosenPos.carPosAvail) {
this.showMessage(_("This gear vector position doesn't allow any vaild car positioning"),"error");
return;
}
this.previewsLocked = true;
document.querySelectorAll('.selectionOctagon').forEach(el => el.style.filter = '');
evt.target.style.filter = 'drop-shadow( 0px 0px 10px red)';
if (!$('confirmGearvecPos'))
this.addActionButton('confirmGearvecPos',_('Confirm'),() => {
this.previewsLocked = false;
this.ajaxcallwrapper('placeGearVector', {
pos: this.gamedatas.gamestate.args.chosenPos['position']
}, null, true);
});
else {
$('previews').innerHTML = '';
let currGear = args.args.gear;
let gv = this.createGameElement('gearVector', {n: currGear}, 'previews');
let pos = args.args.positions[parseInt(evt.target.dataset.posIndex)]['vectorCoordinates'];
this.placeOnTrack(gv, pos.x, pos.y, args.args.direction);
}
} else {
this.ajaxcallwrapper('placeGearVector', {
pos: this.gamedatas.gamestate.args.chosenPos['position']
}, null, true);
}
},
// mouseover handler
evt => {
dojo.stopEvent(evt);
let currGear = args.args.gear;
let gv = this.createGameElement('gearVector', {n: currGear}, 'previews');
let pos = args.args.positions[parseInt(evt.target.dataset.posIndex)]['vectorCoordinates'];
this.placeOnTrack(gv, pos.x, pos.y, args.args.direction);
}
);
// add special properties to selection octagons
document.querySelectorAll('#pos_highlights > .selectionOctagon').forEach((selOct) => {
let i = selOct.dataset.posIndex;
let pos = args.args.positions[i];
if (pos.denied) {
selOct.className = selOct.className.replace('standardPos','deniedPos');
} else {
if (!pos.legal || !pos.carPosAvail || pos.offTrack) {
selOct.className = selOct.className.replace('standardPos','illegalPos');
} else if (pos.tireCost) {
selOct.className = selOct.className.replace('standardPos','tirePos');
};
}
});
// if no pos is available, show brake button
if (!args.args.hasValid && this.isCurrentPlayerActive()) {
this.addActionButton(
'emergencyBrake_button', _('Emergency Brake'), () => { this.ajaxcallwrapper('brakeCar') },
null, false, 'red'
);
this.addTooltip(
'emergencyBrake_button',
_("This action is available when you cannot position your gear vector in any legal way"),
_("By performing an emergency brake, you downshift gear until its vector can be placed in a legal position, spending 1 Tire Token for each shifted gear. \
If no gear can fit in the space available, you will be forced to stop your car, ending your current turn. You may choose to rotate your car by 45 degrees after this action. Next turn, will restart the car using the 1st gear")
);
if (args.args.canGiveWay) {
this.addActionButton(
'giveWay_button', _('Give way'), () => { this.ajaxcallwrapper('giveWay') },
null, false, 'blue'
);
this.addTooltip(
'giveWay_button',
_("This action is available when an opponent that has not fully overtook you is blocking your path, preventing any legal gear vector position"),
_("By giving way, you will temporarily pause your turn and let your opponent move first. You won't be able to perform any attack maneuver after resuming your turn.")
);
/* When cannot position you gear vector in any legal way because an opponent is obstructing the passage and hasn\'t moved yet */
/* an opponent has not overtaken you in the turn order but it is somehow in front of you and obstructing your passage */
}
}
if (args.args.canConcede && this.isCurrentPlayerActive()) {
this.addActionButton(
'concede_button', _('Concede the race'), () => {
this.confirmationDialog(_('You are about to concede this game. Are you sure?'), () => {
this.ajaxcallwrapper('concede');
});
},
null, false, 'red'
);
this.addTooltip(
'concede_button',
_("This action is available when you are too far behind in the race"),
_("By conceding, you will get the lowest score and will be eliminated from the race, but won't get any penality for leaving the game before the end")
);
}
break;
case 'emergencyBrake':
document.querySelectorAll('.marker').forEach( el => {
el.style.display = 'none';
});
this.addMarker(this.getActivePlayerId(),'stop');
if(!this.isCurrentPlayerActive()) return;
this.displayDirectionArrows(args.args.directionArrows, args.args.direction);
document.querySelectorAll('#pos_highlights > *').forEach (el => {
el.addEventListener('click', evt => {
dojo.stopEvent(evt);
if (this.prefs[101].value == 1) {
if (!this.isCurrentPlayerActive()) {
this.showMessage(_("It is not your turn"),"error");
return;
}
this.gamedatas.gamestate.args.chosenDir = evt.target.dataset.posIndex;
// color selected move
document.querySelectorAll('.directionArrow').forEach(el => el.style.filter = '');
$(this.gamedatas.gamestate.args.directionArrows[this.gamedatas.gamestate.args.chosenDir]['direction']+'Arrow').style.filter = 'drop-shadow( 0px 0px 10px red)';
// display move triggering button if not present
if (!$('confirmEBRot')) {
this.addActionButton('confirmEBRot',_('Confirm'),()=>{
this.ajaxcallwrapper('rotateAfterBrake',{dir:this.gamedatas.gamestate.args.chosenDir}, null, true);
});
}
} else this.ajaxcallwrapper('rotateAfterBrake',{dir:evt.target.dataset.posIndex}, null, true);
});
/* el.addEventListener('mouseenter', evt => {
dojo.stopEvent(evt);
let car = this.getPlayerCarElement(this.getActivePlayerId());
let rot = evt.target.dataset.posIndex-1
car.style.transform += `rotate(${rot*-45}deg)`;
});
el.addEventListener('mouseleave', evt => {
dojo.stopEvent(evt);
let car = this.getPlayerCarElement(this.getActivePlayerId());
let rot = evt.target.dataset.posIndex-1
car.style.transform += `rotate(${rot*45}deg)`;
}); */
});
break;
case 'boostPrompt':
if (!this.isCurrentPlayerActive()) return;
// use button
this.addActionButton(
'useBoost_button',
_('Use Boost')+' -1 '+this.format_block('jstpl_token',{type:'nitro'}),
() => this.ajaxcallwrapper('useBoost', {use: true}),
null, false, 'red'
);
// style button in a cool way
$('useBoost_button').style.cssText = `color: #eb6b0c;
background: #fed20c;
borderColor: #f7aa16`;
// iconize nitro token element to properly display it
this.iconize(document.querySelector('#useBoost_button > .token'),20);
// skip button
this.addActionButton(
'skipBoost_button',
_("Skip"),
() => this.ajaxcallwrapper('useBoost', {use: false}),
null, false, 'gray');
break;
case 'boostVectorPlacement':
// works similarly to gearVectorPlacement
const prevArgs = JSON.parse(JSON.stringify(this.gamedatas.gamestate));
let boostAllPos = [];
args.args.positions.forEach(pos => {
boostAllPos.push(pos.vecTopCoordinates);
});
let createBoostPreview = (evt) => {
let n = args.args.positions[parseInt(evt.target.dataset.posIndex)]['length'];
let pos = args.args.positions[parseInt(evt.target.dataset.posIndex)]['vecCenterCoordinates'];
let bv = this.createGameElement('boostVector', {n: n}, 'previews');
this.placeOnTrack(bv, pos.x, pos.y, args.args.direction);
}
this.displaySelectionOctagons(boostAllPos);
this.connectPosHighlights(