-
Notifications
You must be signed in to change notification settings - Fork 0
/
magicmaze.js
1110 lines (1028 loc) · 35.7 KB
/
magicmaze.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 <[email protected]> & Emmanuel Colin <[email protected]>
* MagicMaze implementation : © Patrick Xia <[email protected]>
*
* 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.
* -----
*/
// This is written in JavaScript Standard Style.
// (https://standardjs.com)
// If you are seeing semicolons and bizarre loop variables named _loop#,
// this is because you are reading the babelified version of this source code.
// Please refer to the github for the non-transformed version.
// Define the libraries that the BGA framework gives us to begin with
// and the imports.
/* global $, define, ebg, dojo, g_gamethemeurl, getRoles, _ */
'use strict'
const SECS_TO_MILLIS = 1000.0
const MILLIS_TO_SECS = 0.001
const BORDER_WIDTH = 20
const CELL_SIZE = 54
const MEEPLE_SIZE = 30
// X is also checked for, but is never valid.
const VALID_MOVES = 'WNSERPH'
const N_TOKENS = 4
function toScreenCoords (x, y) {
// Thanks Sarah Howell ([email protected]) for the
// lovely math behind this implementation. Note that this only
// works for the coordinates of the cell in the top left of every
// tile.
// 00 10 20 30
// 01 11 21 31 41 51 61 71
// 02 12 22 32 42 52 62 72
// 03 13 23 33 43 53 63 73
// 44 54 64 74
const x0 = Math.floor((y + 4 * x) / 17)
const y0 = Math.floor((x - 4 * y) / 17)
const left = 2 * BORDER_WIDTH * x0 + x * CELL_SIZE
const top = -2 * BORDER_WIDTH * y0 + y * CELL_SIZE
return [left, top]
}
const mageId = 3
function isMage (tokenId) {
return tokenId === mageId
}
function createTileEl (tileX, tileY, rot, cssClass, parent) {
const screenCoords = toScreenCoords(tileX, tileY)
return dojo.create('div', {
class: cssClass,
style: {
position: 'absolute',
left: (screenCoords[0] - BORDER_WIDTH) + 'px',
top: (screenCoords[1] - BORDER_WIDTH) + 'px',
transform: `rotate(${rot}deg)`
}
}, parent)
}
function updateTimer (obj, el) {
if (!obj.deadline) {
return
}
const deadline = SECS_TO_MILLIS * obj.deadline
const rawLeft = Math.floor(MILLIS_TO_SECS * (deadline - Date.now()))
if (rawLeft < -10) {
obj.refreshDeadline()
}
const left = Math.max(0, rawLeft)
const minutes = Math.floor(left / 60)
let seconds = left % 60
if (seconds < 10) seconds = '0' + seconds
el.innerHTML = minutes + ':' + seconds
if (obj.tilesRemain > 0) {
el.innerHTML += `<br/>□ ${obj.tilesRemain}`
}
}
function dispatchMove (obj, tokenId, arr) {
let arg = {}
let path = ''
if (tokenId == null) {
path = 'magicmaze/magicmaze/notify.html'
arg = {
player_id: arr[0]
}
} else if (tokenId === -1) {
path = '/magicmaze/magicmaze/attemptWarp.html'
arg = {
x: arr[0],
y: arr[1]
}
} else if (arr.length === 3) {
path = '/magicmaze/magicmaze/attemptMove.html'
arg = {
token_id: tokenId,
x: arr[0],
y: arr[1],
keep_moving: arr[2]
}
} else {
if (arr[0] === 0) {
path = '/magicmaze/magicmaze/attemptExplore.html'
arg = {
token_id: tokenId
}
// explore
} else {
path = '/magicmaze/magicmaze/attemptEscalator.html'
arg = {
token_id: tokenId
}
}
}
obj.ajaxcall(path,
arg, this, function (result) {}, function (error) { if (error) console.log(error) })
}
function updateWarpHighlight (dojo, obj) {
const node = dojo.query('.mm_filterwarp')
// If spectator or we have the warp ability
if (!(obj.player_id in obj.abilities) || obj.abilities[obj.player_id].indexOf('P') !== -1) {
node.style('opacity', '0.0')
node.style('pointer-events', 'auto')
} else {
node.style('opacity', '0.3')
node.style('pointer-events', 'auto')
node.attr('title', '')
}
}
function setupAbilities (dojo, obj) {
$('playerlist').innerText = ''
for (const playerId in obj.players) {
const player = obj.players[playerId]
const parentID = `player_board_${playerId}`
const els = dojo.query(`#${parentID} .mm_abilityblock`)
if (els.length === 0) {
const overallID = `overall_player_board_${playerId}`
const notifyFn = function () {
if (obj.last_notify === undefined || Date.now() - obj.last_notify > 1000) {
obj.last_notify = Date.now()
dispatchMove(obj, null, [playerId])
}
}
dojo.connect($(overallID), 'ondblclick', this, function (evt) {
notifyFn()
})
dojo.query(`#${overallID}`).attr('title', _('Double-click to notify'))
els[0] = dojo.create('div', {
class: 'mm_abilityblock'
}, $(parentID))
const nameEl = $(`player_name_${playerId}`)
const notifyEl = dojo.create('div', {
class: 'mm_notify',
innerHTML: '←🔔'
}, nameEl)
dojo.connect(notifyEl, 'onmouseover', this, function (evt) {
evt.stopPropagation()
})
dojo.connect(notifyEl, 'onclick', this, function (evt) {
notifyFn()
})
}
const playerEl = els[0]
playerEl.innerText = ''
const backgroundEl = dojo.create('div', {
class: 'mm_ability'
}, playerEl)
const abilities =
getRoles(
Object.keys(obj.players).length,
player.player_no,
obj.flips)
obj.abilities[playerId] = abilities
for (const ability of abilities) {
dojo.create('div', {
class: `mm_ability${ability}`
}, backgroundEl)
}
if (parseInt(obj.attention_pawn) === parseInt(playerId)) {
dojo.create('div', {
class: 'mm_redpawn'
}, playerEl)
}
}
const body = document.getElementsByTagName('body')[0]
for (const c of VALID_MOVES) {
const node = dojo.query(`.mm_action${c}`)
if (!(obj.player_id in obj.abilities) || obj.abilities[obj.player_id].indexOf(c) === -1) {
node.style('visibility', 'hidden')
dojo.removeClass(body, `mm_can_${c}`)
} else {
node.style('visibility', 'visible')
dojo.addClass(body, `mm_can_${c}`)
}
}
updateWarpHighlight(dojo, obj)
}
function previewNextTile (obj, dojo, info, onlyLocked) {
const tileId = parseInt(info.tile_id)
obj.nextTile = tileId
// TODO Maybe consider disabling this feature. It makes it much easier.
obj.previewElements.forEach(function (els, tokenId) {
if (onlyLocked && !obj.locked.has(tokenId)) {
return
}
if (obj.mageStatus !== 0 && !isMage(tokenId)) {
return
}
for (const el of els) {
if (obj.mageStatus === 0 && 'mm_magepreview' in el) {
continue
}
const newEl = dojo.create('div', {
class: `tile${tileId}`
}, el)
if ('mm_shadeelement' in el) {
dojo.style(el.mm_shadeelement, 'visibility', 'hidden')
}
dojo.style(newEl, 'transform', `rotate(${el.mm_rot}deg)`)
dojo.style(newEl, 'opacity', '0.6')
// Float previews above "draw a tile", because "draw a new tile"
// actually isn't operable. This situation happens if we start an
// explore action and somebody else moves a meeple that is eligible for
// explore at the exact same new tile location.
dojo.style(el, 'z-index', '1')
}
})
}
function placeTile (obj, tile) {
$('mm_next_explore').innerHTML = ''
delete obj.nextTile
obj.locked.clear()
dojo.query('#mm_next_explore_container').style('visibility', 'hidden')
const x = parseInt(tile.position_x)
const y = parseInt(tile.position_y)
const noMoreTiles = (obj.tilesRemain === 0)
obj.previewElements.forEach(function (els, tokenId, map) {
for (const el of els) {
if (noMoreTiles || el.mm_key === getKey(x, y)) {
dojo.destroy(el)
map.delete(tokenId)
} else {
// Shade / other nonsense will be regenerated
el.innerHTML = ''
dojo.style(el, 'z-index', el.mm_zindex)
}
}
})
createTileEl(x, y, tile.rotation, `tile${tile.tile_id}`, $('mm_area_scrollable'))
// TODO should this loop even be here? Could possibly place into createTileEl
// but it might get written to multiple times.
const screenCoords = toScreenCoords(x, y)
for (let i = 0; i < 4; ++i) {
for (let j = 0; j < 4; ++j) {
const key = getKey(x + i, y + j)
const cellLeft = screenCoords[0] + i * CELL_SIZE
const cellTop = screenCoords[1] + j * CELL_SIZE
obj.tileIds.set(key, tile.tile_id)
obj.relativexs.set(key, i)
obj.relativeys.set(key, j)
obj.lefts.set(key, cellLeft)
obj.tops.set(key, cellTop)
const clickableZone = dojo.create('div', {
style: {
position: 'absolute',
width: CELL_SIZE + 'px',
height: CELL_SIZE + 'px',
left: cellLeft + 'px',
top: cellTop + 'px'
}
}, $('mm_area_scrollable_oversurface'))
clickableZone.cellLeft = cellLeft
clickableZone.cellTop = cellTop
clickableZone.posX = x + i
clickableZone.posY = y + j
clickableZone.onclick = (evt) => cellClickHandler(dojo, obj, clickableZone, evt)
clickableZone.onmouseenter = (evt) => cellMoveHandler(dojo, obj, clickableZone, evt)
clickableZone.onmouseleave = (evt) => cellMoveHandler(dojo, obj, undefined, evt)
obj.clickableCells.set(key, clickableZone)
}
}
}
function drawEscalators (obj) {
obj.escalators.forEach(function (dst, srcKey) {
if (obj.escalatorEls.has(srcKey)) {
return
}
const src = splitKey(srcKey)
const xs = [src[0], dst[0]].sort((a, b) => a - b)
const ys = [src[1], dst[1]].sort((a, b) => a - b)
const topLeft = getKey(xs[0], ys[0])
const left = obj.lefts.get(topLeft) + 0.4 * CELL_SIZE
const top = obj.tops.get(topLeft) + 0.4 * CELL_SIZE
// srcX is always least, so if dstY is less than srcY it is nesw
const dir = (dst[1] < src[1]) ? 'nesw' : 'nwse'
const el = dojo.create('div', {
class: `mm_escalator mm_escalator_${dir}`,
style: {
position: 'absolute',
width: `${(xs[1] - xs[0]) * 1.25 * CELL_SIZE}px`,
height: `${(ys[1] - ys[0]) * 1.25 * CELL_SIZE}px`,
left: `${left}px`,
top: `${top}px`
}
}, $('mm_area_scrollable_oversurface'))
obj.escalatorEls.set(srcKey, el)
dojo.connect(el, 'onclick', obj, function (evt) {
const eligible = new Set()
obj.characterLocs.forEach(function (loc, tokenId) {
if ((loc[0] === dst[0] && loc[1] === dst[1]) ||
(loc[0] === src[0] && loc[1] === src[1])) {
eligible.add(tokenId)
}
})
if (eligible.size !== 1) {
return
}
dispatchMove(obj, [...eligible][0], [1])
})
})
}
function abilityNeeded (x, y) {
if (y === 0 && x === -1) return 'W'
if (y === 0 && x === 1) return 'E'
if (x === 0 && y === -1) return 'N'
if (x === 0 && y === 1) return 'S'
return 'X'
}
function eligibleMoves (game, x, y) {
const ret = []
if (!(game.player_id in game.abilities)) {
return ret
}
for (let token = 0; token < N_TOKENS; ++token) {
const [tokenX, tokenY] = game.characterLocs.get(token)
const dx = x - tokenX
const dy = y - tokenY
const ability = abilityNeeded(dx, dy)
if (game.abilities[game.player_id].indexOf(ability) !== -1) {
ret.push([token, ability, dx, dy])
}
}
return ret
}
function cellClickHandler (dojo, game, cell, evt) {
if (!(game.player_id in game.abilities)) {
return
}
const possibleWarp = 'warpFn' in cell && game.abilities[game.player_id].indexOf('P') !== -1
const possibleMoves = eligibleMoves(game, cell.posX, cell.posY)
if (possibleMoves.length > 1) {
game.showMessage(_('Possibly ambiguous move, use the specific arrow to move the desired character'), 'error')
}
if (!possibleWarp && possibleMoves.length === 1) {
const [token, , dx, dy] = possibleMoves[0]
dispatchMove(game, token, [dx, dy, evt.shiftKey])
}
// Display warp regardless because it self-disambiguates.
if (possibleWarp) {
cell.timer = setTimeout(function () {
if (cell.confirmEl !== undefined) {
// Already clicked, but clicked again somehow before we
// rendered.
return
}
if (!cell.prevent) {
cell.confirmEl = dojo.create('div', {
class: 'mm_action',
style: {
position: 'absolute',
width: CELL_SIZE + 'px',
height: CELL_SIZE + 'px',
left: cell.cellLeft + 'px',
top: cell.cellTop + 'px',
'text-align': 'center',
'line-height': CELL_SIZE + 'px',
'font-size': '48px'
},
innerHTML: '✔'
}, $('mm_area_scrollable_oversurface'))
setTimeout(function () {
if (cell.confirmEl !== undefined) {
dojo.destroy(cell.confirmEl)
cell.confirmEl = undefined
}
}, 4000)
dojo.connect(cell.confirmEl, 'onclick', null, function (evt) {
dojo.destroy(this) // warpFn does this, but in case we've messed up the confirmEl
cell.warpFn(evt)
})
}
cell.prevent = false
}, 250)
}
}
function cellMoveHandler (dojo, game, cell) {
let possibleMoves = []
if (cell !== undefined) {
possibleMoves = eligibleMoves(game, cell.posX, cell.posY)
}
dojo.query('.mm_action').removeClass('mm_bold')
for (const move of possibleMoves) {
const [token, ability] = move
dojo.query(`#mm_token${token} .mm_action${ability}`).addClass('mm_bold')
}
}
function drawProperties (dojo, game, properties) {
if (properties.warp) {
for (const warp of properties.warp) {
const key = getKey(warp.position_x, warp.position_y)
const clickableZone = game.clickableCells.get(key)
clickableZone.classList.add('mm_filterwarp')
clickableZone.warpFn = function (evt) {
evt.stopPropagation() // Or we get in a state where we regenerate this element
clearTimeout(clickableZone.timer)
clickableZone.prevent = true
if (clickableZone.confirmEl !== undefined) {
dojo.destroy(clickableZone.confirmEl)
clickableZone.confirmEl = undefined
}
dispatchMove(game, -1, [warp.position_x, warp.position_y])
}
clickableZone.ondblclick = clickableZone.warpFn
}
}
updateWarpHighlight(dojo, game)
if (properties.used) {
for (const used of properties.used) {
drawUsed(game, used.position_x, used.position_y)
}
}
if (properties.explore) {
for (const explore of properties.explore) {
const key = getKey(explore.position_x, explore.position_y)
const tokenId = parseInt(explore.token_id)
game.explores.set(key, tokenId)
}
}
if (properties.crystal) {
for (const crystal of properties.crystal) {
game.crystals.add(getKey(crystal.position_x, crystal.position_y))
}
}
if (properties.escalator) {
for (const escalator of properties.escalator) {
// Canonical element is the one with the lower x
const oldX = parseInt(escalator.old_x, 10)
const oldY = parseInt(escalator.old_y, 10)
const newX = parseInt(escalator.new_x, 10)
const newY = parseInt(escalator.new_y, 10)
// Why not just sort? Because < works terribly on arrays.
let srcX, srcY, dstX, dstY
if (oldX < newX) {
srcX = oldX
srcY = oldY
dstX = newX
dstY = newY
} else {
srcX = newX
srcY = newY
dstX = oldX
dstY = oldY
}
game.escalators.set(getKey(srcX, srcY), [dstX, dstY])
}
drawEscalators(game)
}
}
function drawUsed (obj, x, y) {
const key = getKey(x, y)
obj.crystals.delete(key)
const cellLeft = obj.lefts.get(key)
const cellTop = obj.tops.get(key)
dojo.create('div', {
class: 'mm_used',
style: {
left: cellLeft + 'px',
top: cellTop + 'px'
}
}, $('mm_area_scrollable'))
}
function getKey (x, y) {
return `${x}_${y}`
}
function splitKey (x) {
return x.split('_', 2).map(function (x) { return parseInt(x, 10) })
}
function toZoomLevel (ratio) {
return Math.log(ratio) / Math.log(1.1)
}
function toZoomRatio (level) {
return Math.pow(1.1, level)
}
function clampLevel (level) {
// 4 is roughly 2x, -14 is roughly 25%
return Math.min(4, Math.max(-14, level))
}
// NB this map looks different than the PHP one because the PHP one maps tile -> tile
// whereas we're mapping meeple_loc -> new_tile_loc
function computeNewTileLoc (obj, exploreX, exploreY) {
const key = getKey(exploreX, exploreY)
const newTileLoc = new Map([
['2_0', [-1, -4]],
['3_2', [1, -1]],
['1_3', [-2, 1]],
['0_1', [-4, -2]]
])
const newTileRot = new Map([
['2_0', 0],
['3_2', 90],
['1_3', 180],
['0_1', -90]
])
const relativeloc = getKey(obj.relativexs.get(key), obj.relativeys.get(key))
const dx = newTileLoc.get(relativeloc)
if (dx === undefined) {
throw new Error(`internal error: explore on unexpected space ${relativeloc}`)
}
const newx = exploreX + dx[0]
const newy = exploreY + dx[1]
if (obj.tileIds.has(getKey(newx, newy))) {
return [false, 0, 0, 0]
}
const rot = newTileRot.get(relativeloc)
if (rot === undefined) {
throw new Error(`internal error: explore on unexpected space ${relativeloc}`)
}
return [true, newx, newy, rot]
}
function destroyPreviews (obj, tokenId) {
if (obj.previewElements.has(tokenId)) {
// If two meeples can explore in the same location, we'll just
// overlap two divs and only one will be deleted.
for (const el of obj.previewElements.get(tokenId)) {
dojo.destroy(el)
}
obj.previewElements.delete(tokenId)
}
}
function drawMagePreviews (obj) {
if (obj.tilesRemain === 0) {
return
}
obj.previewElements.set(mageId, [])
for (const key of obj.explores.keys()) {
const [exploreX, exploreY] = splitKey(key)
const [ok, newX, newY, rot] = computeNewTileLoc(obj, exploreX, exploreY)
if (!ok) continue
// TODO perhaps "mage preview tile" css class
const el = createTileEl(newX, newY, 0, 'mm_preview_tile', $('mm_area_scrollable_oversurface'))
el.mm_key = key
el.mm_rot = rot
el.mm_magepreview = true
dojo.create('div', {
class: 'mm_shade_preview'
}, el)
const srcTileID = obj.tileIds.get(key)
const newRelativeX = obj.relativexs.get(key)
const newRelativeY = obj.relativeys.get(key)
dojo.connect(el, 'onclick', el, function (evt) {
if (obj.mageStatus !== 0) {
obj.onCreateTile(srcTileID, newRelativeX, newRelativeY)
} else {
dispatchMove(obj, mageId, [0])
}
})
// Lower the priority of mage explores. We want regular explores to be used
// before mage explores when clicking on the map. Note that there could exist
// regular explore / regular explore conflicts as well; those are resolved
// arbitrarily.
dojo.style(el, 'z-index', '-1')
obj.mm_zindex = -1
obj.previewElements.get(mageId).push(el)
}
}
function placeCharacter (obj, info) {
const x = parseInt(info.position_x)
const y = parseInt(info.position_y)
const tokenId = parseInt(info.token_id)
obj.characterLocs.set(tokenId, [x, y])
const key = getKey(x, y)
const top = obj.tops.get(key)
const left = obj.lefts.get(key)
const adjust = (CELL_SIZE - MEEPLE_SIZE) / 2
obj.rescale(1.0)
obj.slideToObjectPos(`mm_token${info.token_id}`,
'mm_area_scrollable_oversurface',
left + adjust,
top + adjust,
/* duration */ 200).play()
obj.rescale()
destroyPreviews(obj, tokenId)
if (obj.tilesRemain === 0) {
return
}
if (isMage(tokenId) && obj.crystals.has(key)) {
obj.drawingMagePreviews = true
drawMagePreviews(obj)
return
}
if (isMage(tokenId)) {
obj.drawingMagePreviews = false
}
if (obj.explores.get(key) === tokenId) {
const [ok, newX, newY, rot] = computeNewTileLoc(obj, x, y)
if (!ok) return
const el = createTileEl(newX, newY, 0, 'mm_preview_tile', $('mm_area_scrollable_oversurface'))
el.mm_key = getKey(newX, newY)
el.mm_rot = rot
obj.mm_zindex = 0
dojo.connect(el, 'onclick', obj, function (evt) {
dispatchMove(obj, tokenId, [0])
})
obj.previewElements.set(tokenId, [el])
}
}
function fromEntries (iterable) {
return [...iterable].reduce((obj, [key, val]) => {
obj[key] = val
return obj
}, {})
}
function filterZombies (obj) {
return fromEntries(Object.entries(obj).filter(function (pair) { return !pair[1].player_zombie }))
}
define([
'dojo', 'dojo/_base/declare',
'ebg/core/gamegui',
'ebg/counter',
'ebg/scrollmap',
g_gamethemeurl + 'modules/mm-playerability.js' // eslint-disable-line camelcase
],
function (dojo, declare) {
return declare('bgagame.magicmaze', ebg.core.gamegui, {
constructor: function () {
this.lefts = new Map()
this.tops = new Map()
this.tileIds = new Map()
this.relativexs = new Map()
this.relativeys = new Map()
this.crystals = new Set()
this.explores = new Map()
this.escalators = new Map()
this.escalatorEls = new Map()
this.previewElements = new Map() // coord key -> dom element
this.clickableCells = new Map()
this.visualCells = new Map()
this.scrollmap = new ebg.scrollmap() // eslint-disable-line new-cap
this.locked = new Set()
this.characterLocs = new Map()
this.displayedSteal = false
this.displayedEscape = false
this.lastRefreshDeadline = 0
this.zoomLevel = 0
this.drawingMagePreviews = false
},
setup: function (gamedatas) {
const game = this
this.abilities = []
this.players = filterZombies(gamedatas.players)
// Setting up player boards
if (gamedatas.attention_pawn) {
this.attention_pawn = parseInt(gamedatas.attention_pawn)
}
if (parseInt(this.player_id) === this.attention_pawn) {
dojo.query('#mm_border').style('visibility', 'visible')
}
this.flips = gamedatas.flips
this.tilesRemain = parseInt(gamedatas.tiles_remain, 10)
if (gamedatas.time_left) {
this.deadline = (Date.now() / 1000.0) + parseFloat(gamedatas.time_left)
setTimeout(() => game.refreshDeadline(), 3000)
}
this.scrollmap.create(
$('mm_area_container'),
$('mm_area_scrollable'),
$('mm_area_surface'),
$('mm_area_scrollable_oversurface')
)
this.scrollmap.setupOnScreenArrows(150)
for (const key in gamedatas.tiles) {
placeTile(this, gamedatas.tiles[key])
}
drawProperties(dojo, this, gamedatas.properties)
for (const key in gamedatas.tokens) {
placeCharacter(this, gamedatas.tokens[key])
const tokenId = gamedatas.tokens[key].token_id
if (gamedatas.tokens[key].locked === '1') {
this.locked.add(parseInt(tokenId, 10))
}
const base = `#mm_control${tokenId} `
dojo.connect(document.querySelector(base + '> .mm_actionN'), 'onclick', this, function (evt) {
// up
dispatchMove(this, tokenId, [0, -1, evt.shiftKey])
})
dojo.connect(document.querySelector(base + '> .mm_actionW'), 'onclick', this, function (evt) {
// left
dispatchMove(this, tokenId, [-1, 0, evt.shiftKey])
})
dojo.connect(document.querySelector(base + '> .mm_actionE'), 'onclick', this, function (evt) {
// right
dispatchMove(this, tokenId, [1, 0, evt.shiftKey])
})
dojo.connect(document.querySelector(base + '> .mm_actionS'), 'onclick', this, function (evt) {
// down
dispatchMove(this, tokenId, [0, 1, evt.shiftKey])
})
dojo.connect(document.querySelector(base + '> .mm_actionH'), 'onclick', this, function (evt) {
// explore
dispatchMove(this, tokenId, [0])
})
dojo.connect(document.querySelector(base + '> .mm_actionR'), 'onclick', this, function (evt) {
// escalator
dispatchMove(this, tokenId, [1])
})
dojo.connect(document.querySelector(base + '> .mm_actionP'), 'onclick', this, function (evt) {
const el = dojo.query('.mm_filterwarp')
el.style('animation', 'none')
setTimeout(function () {
el.style('animation', 'mm_inverseblink 0.3s')
el.style('animation-iteration-count', 2)
}, 0)
})
const base2 = `#mm_token${tokenId}`
dojo.connect(document.querySelector(base2 + '> .mm_actionN'), 'onclick', this, function (evt) {
// up
dispatchMove(this, tokenId, [0, -1, evt.shiftKey])
})
dojo.connect(document.querySelector(base2 + '> .mm_actionW'), 'onclick', this, function (evt) {
// left
dispatchMove(this, tokenId, [-1, 0, evt.shiftKey])
})
dojo.connect(document.querySelector(base2 + '> .mm_actionE'), 'onclick', this, function (evt) {
// up
dispatchMove(this, tokenId, [1, 0, evt.shiftKey])
})
dojo.connect(document.querySelector(base2 + '> .mm_actionS'), 'onclick', this, function (evt) {
// down
dispatchMove(this, tokenId, [0, 1, evt.shiftKey])
})
}
dojo.connect($('mm_movetop'), 'onclick', this, 'onMoveTop')
dojo.connect($('mm_moveleft'), 'onclick', this, 'onMoveLeft')
dojo.connect($('mm_moveright'), 'onclick', this, 'onMoveRight')
dojo.connect($('mm_movedown'), 'onclick', this, 'onMoveDown')
dojo.connect($('mm_area_container'), 'onwheel', this, 'onWheel')
dojo.connect($('mm_zoom_in'), 'onclick', this, 'onZoomIn')
dojo.connect($('mm_zoom_reset'), 'onclick', this, 'onZoomReset')
dojo.connect($('mm_zoom_out'), 'onclick', this, 'onZoomOut')
dojo.connect($('mm_zoom_fit'), 'onclick', this, 'onZoomFit')
dojo.connect($('mm_objectives_float'), 'onclick', this, function (evt) {
dojo.query('#mm_objectives_float').style('visibility', 'hidden')
})
this.mageStatus = parseInt(gamedatas.mage_status, 10)
// Needs to be after placeCharacter
if (gamedatas.next_tile) {
previewNextTile(this, dojo, gamedatas.next_tile, /* onlyLocked= */true)
}
// This needs to access some properties created earlier, do this as late as possible.
setupAbilities(dojo, this)
// Setup game notifications to handle (see "setupNotifications" method below)
this.setupNotifications()
window.setInterval(function () { updateTimer(game, $('mm_timer_numbers')) }, 500)
},
onMoveTop: function (evt) {
evt.preventDefault()
this.scrollmap.scroll(0, 300)
},
onMoveLeft: function (evt) {
evt.preventDefault()
this.scrollmap.scroll(300, 0)
},
onMoveRight: function (evt) {
evt.preventDefault()
this.scrollmap.scroll(-300, 0)
},
onMoveDown: function (evt) {
evt.preventDefault()
this.scrollmap.scroll(0, -300)
},
onWheel: function (evt) {
if (evt.ctrlKey) {
// either a pinch event or a whole-page zoom event (hitting the ctrl key while scrolling)
// either way, ignore it
return
}
if (evt.wheelDeltaY) {
if (Math.abs(evt.wheelDeltaY) !== 120) {
// mouse wheels have exactly 120 for delta, everything else
// does not. TODO: replace this with debounce for trackpad
return
}
} else {
// firefox: doesn't set wheelDeltaY, but does set the deltaMode to 1
if (evt.deltaMode === 0) {
return
}
}
if (evt.deltaY < 0) {
this.onZoomIn(evt)
} else {
this.onZoomOut(evt)
}
},
onZoomIn: function (evt) {
evt.preventDefault()
this.zoomLevel += 1
this.zoomLevel = clampLevel(this.zoomLevel)
this.rescale()
},
onZoomOut: function (evt) {
evt.preventDefault()
this.zoomLevel -= 1
this.zoomLevel = clampLevel(this.zoomLevel)
this.rescale()
},
onZoomFit: function (evt) {
const containerStyle = dojo.getComputedStyle(dojo.byId('mm_area_container'))
const viewWidth = parseInt(containerStyle.width, 10)
const viewHeight = parseInt(containerStyle.height, 10)
let minX, minY, maxX, maxY
dojo.query('#mm_area_scrollable > div').forEach(function (el) {
if (!el.className.startsWith('tile')) {
return
}
const x = parseInt(dojo.getStyle(el, 'left'), 10)
const y = parseInt(dojo.getStyle(el, 'top'), 10)
const height = parseInt(dojo.getStyle(el, 'height'), 10)
const width = parseInt(dojo.getStyle(el, 'width'), 10)
if (minX === undefined || x < minX) {
minX = x
}
if (maxX === undefined || (x + width) > maxX) {
maxX = x + width
}
if (minY === undefined || y < minY) {
minY = y
}
if (maxY === undefined || (y + height) > maxY) {
maxY = y + height
}
})
const widthRequired = maxX - minX
const heightRequired = maxY - minY
const ratio = Math.min(viewWidth / widthRequired, viewHeight / heightRequired)
const centerX = (maxX + minX) * 0.5
const centerY = (minY + maxY) * 0.5
const debugString = `${minX} ${minY} ${maxX} ${maxY} ${viewWidth} ${viewHeight}`
if (isNaN(ratio)) {
throw new Error(`error determining view ratio; ${debugString}`)
}
// Don't allow zoom in as part of this operation
this.zoomLevel = Math.min(0, clampLevel(toZoomLevel(ratio)))
this.rescale()
// Center the view
if (isNaN(centerX) || isNaN(centerY)) {
throw new Error(`could not determine center; ${debugString}`)
}
const newRatio = toZoomRatio(this.zoomLevel)
const newX = -(centerX * newRatio - viewWidth * 0.5)
const newY = -(centerY * newRatio - viewHeight * 0.5)
for (const element of ['mm_area_scrollable', 'mm_area_scrollable_oversurface']) {
dojo.query('#' + element).style('left', `${newX}px`)
dojo.query('#' + element).style('top', `${newY}px`)
}
},
onZoomReset: function (evt) {
evt.preventDefault()
this.zoomLevel = 0
this.rescale()
},
rescale: function (zoomRatio) {
if (zoomRatio === undefined) {
zoomRatio = toZoomRatio(this.zoomLevel)
}
// You need to set these individually. If these divs are in a div that sets a transform, the mouse
// coordinates are all screwy and it will break click+drag.
for (const element of ['mm_area_scrollable', 'mm_area_scrollable_oversurface']) {
dojo.query('#' + element).style('transform', 'scale(' + zoomRatio + ')')
}
},
/// ////////////////////////////////////////////////
/// / Game & client states
// onEnteringState: this method is called each time we are entering into a new game state.
// You can use this method to perform some user interface changes at this moment.
//
//
onEnteringState: function (stateName, args) {
const el = dojo.query('#mm_objectives_float')
switch (stateName) {
case 'pre_game':
case 'steal_loud':
case 'steal_quiet':
if (!this.displayedSteal) {
this.displayedSteal = true
el.style('visibility', 'visible')
setTimeout(function () {
el.style('visibility', 'hidden')
}, 4500)
}
break
case 'escape_loud':
case 'escape_quiet':
if (!this.displayedEscape) {
this.displayedEscape = true
el.style('visibility', 'visible')
dojo.query('#mm_objectives_container').style('transform', 'rotateY(180deg)')
setTimeout(function () {
el.style('visibility', 'hidden')
}, 4500)
dojo.query('.mm_abilityP').forEach(function (node, index, arr) {
node.innerText = ''
dojo.create('div', {
class: 'mm_crossout'
}, node)
}
)
}
}
const bEl = dojo.query('#mm_talk_border')
if (stateName.includes('loud')) {
bEl.style('visibility', 'visible')
} else {
bEl.style('visibility', 'hidden')
}
},