-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewton.ts
654 lines (499 loc) · 21.3 KB
/
newton.ts
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
/**
*------
* BGA framework: © Gregory Isabelli <gisabelli@boardgamearena.com> & Emmanuel Colin <ecolin@boardgamearena.com>
* newton 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.
* ----- *
*/
// GameGui declaration copyed from elaskavaia bga-dojoless project https://github.com/elaskavaia/bga-dojoless
// not sure what it does, except it makes program assume "this" as GameGui object, whitch grants access to its properties and methods without needing to use (this as any) to escape TypeScript constraints
// @ts-ignore
GameGui = /** @class */ (function () {
function GameGui() {}
return GameGui;
})();
const isDebug = window.location.host == 'studio.boardgamearena.com' || window.location.hash.indexOf('debug') > -1;
const log = isDebug ? console.log.bind(window.console) : function () { };
class Newton extends GameGui {
// GLOBALS DEF
private defaultSlideAnimation: SlideAnimationConfig = {
duration: 500,
delay: 0,
pos: {x:0, y:0},
append: true,
beforeSibling: null,
phantomIn: true,
phantomOut: true,
slideSurface: 'default',
className: 'moving',
adaptScale: false
}
private defaultSlidingSurface = 'game_play_area';
private animationsSpeed = 1;
private timedConfirmInterval: number;
/// -- SETUP -- ///
//#region
constructor() {
super();
console.log('newton constructed!');
}
public setup(gamedatas: newtonGamedatas) {
console.log( "Starting game setup" );
// Setting up player boards
for (let player_id in gamedatas.players ) {
const player = gamedatas.players[player_id];
// TODO: Setting up players boards if needed
}
// TODO: Set up your game interface here, according to "gamedatas"
// Setup game notifications to handle (see "setupNotifications" method below)
this.setupNotifications();
this.setupPreferencePanel();
this.initPreferenceObserver();
if (this.instantaneousMode) this.animationsSpeed = 0;
console.log( "Ending game setup" );
}
//#endregion
/// -- MISC UTILITY -- ///
//#region
private takeAction(action: string, data?: any, confirm: boolean = true, confirmConfig?: TimedConfirmConfiguration) {
if (!gameui.checkAction(action)) return;
if (confirm) {
let secs;
switch (this.prefs[100].value) {
case 1: secs = 0; break; // none
case 2: secs = 5; break; // timed
case 3: secs = 300; break; // active (infinite time -> 5 minutes)
}
document.querySelectorAll(`.${confirmConfig.selectedClass}`).forEach(el => {
el.classList.remove(confirmConfig.selectedClass);
});
if (secs == 0) {
this.takeAction(action,data,false);
}
confirmConfig.selectedElement.classList.add(confirmConfig.selectedClass);
if ($('timedConfirm_button')) $('timedConfirm_button').remove();
if ($('reset_button')) $('reset_button').remove();
clearInterval(this.timedConfirmInterval);
this.addActionButton('timedConfirm_button',_('Confirm') + ((secs<=10)? ` (${secs})` : ''), evt => {
clearInterval(this.timedConfirmInterval);
confirmConfig.selectedElement.classList.remove(confirmConfig.selectedClass);
});
this.addActionButton('reset_button',_('Reset'),evt => {
confirmConfig.selectedElement.classList.remove(confirmConfig.selectedClass);
clearInterval(this.timedConfirmInterval);
$('timedConfirm_button').remove();
$('reset_button').remove();
}, null, false, 'gray');
this.timedConfirmInterval = setInterval(() => {
secs--;
$('timedConfirm_button').innerHTML = `${_('Confirm')}` + ((secs<=10)? ` (${secs})` : '');
if (secs == 0) {
clearInterval(this.timedConfirmInterval);
confirmConfig.selectedElement.classList.remove(confirmConfig.selectedClass);
this.takeAction(action,data,false);
}
}, 1000);
} else {
data = data || {};
data.lock = true;
return new Promise((resolve, reject) => {
gameui.ajaxcall(
"/" + gameui.game_name + "/" + gameui.game_name + "/" + action + ".html",
data, //
gameui,
(data) => resolve(data),
(isError) => {
if (isError) reject(data);
}
);
});
}
}
// -- BGA framework overrides -- //
/* @Override */
public onScreenWidthChange() {
}
/* @Override */
public updatePlayerOrdering() {
this.inherited(arguments);
console.log("Updating Player ordering");
$('player_boards').insertAdjacentElement('afterbegin',$('preferences_panel'));
}
/* @Override */
public format_string_recursive(log: string, args: any) {
try {
if (log && args && !args.processed) {
}
} catch (e) {
console.error(log,args,"Exception thrown", e.stack);
}
return this.inherited(arguments);
}
// -- preferences handling -- //
private initPreferenceObserver() {
// DEFINE LISTENER FOR PREFERENCES CHANGES
document.querySelectorAll('.preference_control').forEach((prefControl: any) => {
prefControl.onchange = (evt: any) => {
const match = evt.target.id.match(/^preference_[cf]ontrol_(\d+)$/);
if (!match) {
return;
}
const pref = match[1];
let newValue;
if (typeof evt.target.checked !== 'undefined') {
newValue = evt.target.checked? '1':'2';
} else {
newValue = evt.target.value;
}
this.prefs[pref].value = newValue;
this.onPreferenceChange(pref, newValue);
}
});
// FIRE EVENTS TO TRIGGER CHANGES A FIRST TIME
document.querySelectorAll("#ingame_menu_content .preference_control").forEach((el: HTMLElement) => {
// Create a new 'change' event
let event = new CustomEvent('change');
// Dispatch it.
el.dispatchEvent(event);
});
}
private onPreferenceChange(prefId: string, prefValue: string) {
if (parseInt(prefId) >= 200 || parseInt(prefId) < 100) return;
console.log("Preference changed", prefId, prefValue);
let prefEl = $(`preference_option_${prefId}`);
let prefInput: any = document.querySelector(`#preference_option_${prefId} .preference_input`);
if (prefEl.classList.contains('preference_toggle')) {
prefInput.checked = prefValue == '1';
} else {
prefInput.value = prefValue;
}
switch (prefId) {
default:
break;
}
}
private updatePreference(prefId: string, newValue: string) {
console.log("Updating preference", prefId, newValue);
// Select preference value in control:
document.querySelectorAll('#preference_control_' + prefId + ' > option[value="' + newValue + '"], #preference_fontrol_' + prefId + ' > option[value="' + newValue + '"]')
.forEach((el: any) => el.selected = true);
// Generate change event on control to trigger callbacks:
const newEvt = new Event('change');
$('preference_control_' + prefId).dispatchEvent(newEvt);
}
private setupPreferencePanel() {
// set handler for preference menu arrow
let settings_panel : HTMLElement = $('preferences_panel');
let menu_arrow : HTMLElement = $('menu_arrow');
let settings_options : HTMLElement = $('preferences_panel_options');
menu_arrow.onclick = () => {
settings_panel.style.height = 'auto';
if (menu_arrow.classList.contains('open')) {
//debug
console.log('Closing preference panel');
menu_arrow.classList.remove('open');
settings_options.style.height = '0px';
} else {
//debug
console.log('Opening preference panel');
menu_arrow.classList.add('open');
settings_options.style.height = 'fit-content';
let h = settings_options.offsetHeight;
settings_options.style.height = '0px';
settings_options.offsetHeight;
settings_options.style.height = h+'px';
}
};
console.log("Setup preference panel");
console.log("User preferences: ",this.prefs);
// parse user preference from server, add options to menu and attach onchange handler
for (const prefId in this.prefs) {
let pref = this.prefs[prefId];
if (parseInt(prefId) >= 200 || parseInt(prefId) < 100) continue;
if (Object.values(pref.values).length == 2) { // preference is toggle (could be improved, not all binary options are on/off
placeLast(this.format_block('toggle_pref',{
id: prefId,
lable: _(pref.name)
}), $('preferences_panel_options'));
} else { // preference is selection
let options = '';
for (const prefOpt in pref.values) {
options += this.format_block('selection_pref_option',{
id: prefOpt,
name: _(pref.values[prefOpt].name)
});
}
placeLast(this.format_block('selection_pref',{
id: prefId,
lable: _(pref.name),
options: options
}), $('preferences_panel_options'));
}
let prefInput: any = document.querySelector(`#preference_option_${prefId} .preference_input`);
console.log(prefInput);
prefInput.onchange = () => {
if (Object.values(pref.values).length == 2) {
this.updatePreference(prefId,prefInput.checked? '1':'2');
} else {
this.updatePreference(prefId,prefInput.value);
}
};
}
}
// -- element positioning and animations -- //
/**
* Custom made positional placing function as alternative to framework method placeOnObject.
*
* Added optional placing surface, all-in-one optional pixel relative positioning, optional positioning origin (center / top-left standard), made positioning scale invariant.
*/
public placeOnElement(element: HTMLElement, target: HTMLElement, surface?: HTMLElement, position?: Vec2, center: boolean = true) {
surface = surface || $(this.defaultSlidingSurface);
// temporarily remove transform to make positioning scale invariant
let transform = element.style.transform;
element.style.transform = '';
let targetPos = getElementGlobalPosition(target);
let surfacePos = getElementGlobalPosition(surface);
let targetSize = getElementRenderSize(target);
let elementSize = getElementRenderSize(element);
// set transform again
element.style.transform = transform;
console.log(targetPos);
console.log(surfacePos);
console.log(targetSize);
console.log(elementSize);
let centeringOffset: Vec2 = {
x: center? (targetSize.width/2 - elementSize.width/2) : 0,
y: center? (targetSize.height/2 - elementSize.height/2) : 0,
}
position = position || { x: 0, y: 0 }
if (element.parentElement != surface) surface.append(element);
assignStyle(element, {
position: 'absolute',
left: (targetPos.x - surfacePos.x + centeringOffset.x + position.x) + 'px',
top: (targetPos.y - surfacePos.y + centeringOffset.y + position.y) + 'px',
});
}
/**
* Custom made simple slide animation function as alternative to framework method slideOnObject.
*
* Uses placeOnElement method, thus includes all it's features, plus adaptive scaling for target containers that have a different scale value than origin.
*/
public slideOnElement(element: HTMLElement, target: HTMLElement, duration: number, delay: number = 0, surface?: HTMLElement, position?: Vec2, toScale: number = 1, center: boolean = true) {
surface = surface || $(this.defaultSlidingSurface);
duration *= this.animationsSpeed;
delay *= this.animationsSpeed;
console.log(duration);
this.placeOnElement(element,element);
assignStyle(element, {
transition: `all ${duration}ms ${delay}ms ease-in-out`
});
console.log('scaling',element.style.transform,toScale);
if (toScale != 1) element.style.transform += `scale(${toScale})`;
this.placeOnElement(element,target,surface,position,center);
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
element.style.transition = '';
console.log('sliding completed');
resolve();
}, duration+delay);
});
}
/**
* Custom made configuranble animation function that adds upon the features of the simpler slideOnElement method.
*
* Options: (see SlideAnimationConfig interface for properties types)
* - duration
* - delay
* - pos
* - append
* - beforeSibling
* - phantomIn
* - phantomOut
* - slideSurface
* - className
* - adaptScale
*
* Notes: phantoms are used to gradually take/free up the space occupied by the element in the container, appends element by default in the end
*/
public slideElementAnim(element: HTMLElement, target: HTMLElement, options?: SlideAnimationConfig) {
let config = Object.assign(this.defaultSlideAnimation, options);
// get surface
let surface: HTMLElement;
switch (config.slideSurface) {
case 'default': surface = $(this.defaultSlidingSurface);
break;
case 'parent': surface = element.parentElement;
break;
case 'common_ancestor': surface = getCommonAncestor(element,target);
break;
default: surface = $(config.slideSurface);
break;
}
// check if beforeSibling, if set, exists
if (config.append && config.beforeSibling) {
if (!target.querySelector('#'+config.beforeSibling)) {
console.error(`Sibling ${config.beforeSibling} is not a child of Target`)
}
}
// calc adapt scale
let toScale = 1;
let fromScale = getCommonFinalTransform(element,target);
if (config.adaptScale) {
let scaleDetector = element.cloneNode(true) as HTMLElement;
assignStyle(scaleDetector, {
position: 'absolute',
visibility: 'hidden'
});
target.append(scaleDetector);
toScale = getElementRenderSize(scaleDetector).width / getElementRenderSize(element).width;
scaleDetector.remove();
}
// setup phantoms
// phantom in element destination
let phin_el: HTMLElement;
if (config.phantomIn) {
// create phantom
phin_el = element.cloneNode(true) as HTMLElement;
// append phantom in target
if (config.beforeSibling) {
$(config.beforeSibling).before(phin_el);
} else {
target.append(phin_el);
}
assignStyle(phin_el, {
visibility: 'hidden',
width: '0px',
height: '0px',
});
// separation between assignment blocks needed to be sure transition is set
// [!] phantom animation will work only if element has already set static width and height values
// setup phantom properties
assignStyle(phin_el, {
transitionProperty: 'width, height',
transition: `${config.duration * this.animationsSpeed * 0.4}ms ${config.delay * this.animationsSpeed}ms ease-in-out`
});
// trigger animation and make phantom appear, taking space for the arrival of element
assignStyle(phin_el, {
width: element.style.width,
height: element.style.height
});
}
// phantom replacing element on previous location
if (config.phantomOut) {
// create phantom
let phout_el = element.cloneNode(true) as HTMLElement;
// swap position with element and place element on surface
element.after(phout_el);
surface.append(element);
// position it on its phantom copy, so that it will start animation from its original position
this.placeOnElement(element,phout_el);
phout_el.id = ''; // clear id of phantom to avoid interferance
assignStyle(phout_el, {
visibility: 'hidden',
});
// setup phantom properties
assignStyle(phout_el, {
transitionProperty: 'width, height',
transition: `${config.duration * this.animationsSpeed * 0.4}ms ${config.delay * this.animationsSpeed}ms ease-in-out`,
});
phout_el.ontransitionend = () => { phout_el.remove(); };
// trigger animation and make phantom disappear, freeing space for the departing element
assignStyle(phout_el, {
width: '0px',
height: '0px'
});
}
// before animation start, set scale to sliding element
if (toScale != 1) {
this.placeOnElement(element,element);
element.style.transform = fromScale;
}
// add class for sliding state
element.classList.add(config.className);
// set promise
return new Promise<void>((resolve, reject) => {
// slide element
this.slideOnElement(
element,
(config.phantomIn)? phin_el : target,
config.duration,
config.delay,
surface,
config.pos,
toScale,
!config.phantomIn
)
.then(() => {
// remove class for sliding state
element.classList.remove(config.className);
// append if
if (config.phantomIn) {
phin_el.replaceWith(element);
} else if (config.append) {
if (config.beforeSibling) {
$(config.beforeSibling).before(element);
} else {
target.append(element);
}
}
assignStyle(element,{},true);
resolve();
})
})
}
//#endregion
/// -- GAME STATES -- ///
//#region
public onEnteringState(stateName: string, args: any) {
console.log( 'Entering state: '+stateName );
switch( stateName ) {
case 'dummmy':
break;
}
}
public onLeavingState(stateName: string) {
console.log( 'Leaving state: '+stateName );
switch( stateName ) {
case 'dummmy':
break;
}
}
public onUpdateActionButtons(stateName: string, args: any) {
console.log( 'onUpdateActionButtons: '+stateName );
if (this.isCurrentPlayerActive()) {
switch(stateName) {
}
}
}
//#endregion
/// -- GAME UTILITY -- ///
//#region
//#endregion
/// -- ACTION HANDLERS -- ///
//#region
//#endregion
/// -- NOTIFICATIONS -- ///
// #region
setupNotifications() {
console.log( 'notifications subscriptions setup' );
let notifs: any = [
['log',0],
['dump',0],
];
notifs.forEach((notif) => {
dojo.subscribe(notif[0], this, `notif_${notif[0]}`);
if (notif[1] > 0) this.notifqueue.setSynchronous(notif[0], notif[1]);
});
}
notif_log(notif: Notif) {
console.log('LOGGING!');
console.log(notif.log);
}
notif_dump(notif: Notif) {
console.log('DUMPING!');
console.log(notif.args.dump);
}
//#endregion
}