Better squares highlighting
[vchess.git] / public / javascripts / components / game.js
1 Vue.component('my-game', {
2 data: function() {
3 return {
4 vr: null, //object to check moves, store them, FEN..
5 mycolor: "w",
6 possibleMoves: [], //filled after each valid click/dragstart
7 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
8 start: {}, //pixels coordinates + id of starting square (click or drag)
9 selectedPiece: null, //moving piece (or clicked piece)
10 conn: null, //socket messages
11 score: "*", //'*' means 'unfinished'
12 mode: "idle", //human, computer or idle (when not playing)
13 oppid: "", //opponent ID in case of HH game
14 oppConnected: false,
15 seek: false,
16 fenStart: "",
17 incheck: [],
18 pgnTxt: "",
19 expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false,
20 gameId: "", //used to limit computer moves' time
21 };
22 },
23 render(h) {
24 const [sizeX,sizeY] = VariantRules.size;
25 // Precompute hints squares to facilitate rendering
26 let hintSquares = doubleArray(sizeX, sizeY, false);
27 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
28 // Also precompute in-check squares
29 let incheckSq = doubleArray(sizeX, sizeY, false);
30 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
31 let elementArray = [];
32 const playingHuman = (this.mode == "human");
33 const playingComp = (this.mode == "computer");
34 let actionArray = [
35 h('button',
36 {
37 on: { click: this.clickGameSeek },
38 attrs: { "aria-label": 'New game VS human' },
39 'class': {
40 "tooltip": true,
41 "bottom": true, //display below
42 "seek": this.seek,
43 "playing": playingHuman,
44 },
45 },
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
47 h('button',
48 {
49 on: { click: this.clickComputerGame },
50 attrs: { "aria-label": 'New game VS computer' },
51 'class': {
52 "tooltip":true,
53 "bottom": true,
54 "playing": playingComp,
55 },
56 },
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
58 ];
59 if (!!this.vr)
60 {
61 const square00 = document.getElementById("sq-0-0");
62 const squareWidth = !!square00
63 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
64 : 0;
65 const indicWidth = (squareWidth>0 ? squareWidth/2 : 20);
66 if (this.mode == "human")
67 {
68 let connectedIndic = h(
69 'div',
70 {
71 "class": {
72 "topindicator": true,
73 "indic-left": true,
74 "connected": this.oppConnected,
75 "disconnected": !this.oppConnected,
76 },
77 style: {
78 "width": indicWidth + "px",
79 "height": indicWidth + "px",
80 },
81 }
82 );
83 elementArray.push(connectedIndic);
84 }
85 let turnIndic = h(
86 'div',
87 {
88 "class": {
89 "topindicator": true,
90 "indic-right": true,
91 "white-turn": this.vr.turn=="w",
92 "black-turn": this.vr.turn=="b",
93 },
94 style: {
95 "width": indicWidth + "px",
96 "height": indicWidth + "px",
97 },
98 }
99 );
100 elementArray.push(turnIndic);
101 let expertSwitch = h(
102 'button',
103 {
104 on: { click: this.toggleExpertMode },
105 attrs: { "aria-label": 'Toggle expert mode' },
106 'class': {
107 "tooltip":true,
108 "topindicator": true,
109 "indic-right": true,
110 "expert-switch": true,
111 "expert-mode": this.expert,
112 },
113 },
114 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
115 );
116 elementArray.push(expertSwitch);
117 let choices = h('div',
118 {
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
121 style: {
122 "display": this.choices.length>0?"block":"none",
123 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
124 "width": (this.choices.length * squareWidth) + "px",
125 "height": squareWidth + "px",
126 },
127 },
128 this.choices.map( m => { //a "choice" is a move
129 return h('div',
130 {
131 'class': {
132 'board': true,
133 ['board'+sizeY]: true,
134 },
135 style: {
136 'width': (100/this.choices.length) + "%",
137 'padding-bottom': (100/this.choices.length) + "%",
138 },
139 },
140 [h('img',
141 {
142 attrs: { "src": '/images/pieces/' +
143 VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
144 'class': { 'choice-piece': true },
145 on: { "click": e => { this.play(m); this.choices=[]; } },
146 })
147 ]
148 );
149 })
150 );
151 // Create board element (+ reserves if needed by variant or mode)
152 let gameDiv = h('div',
153 {
154 'class': { 'game': true },
155 },
156 [_.range(sizeX).map(i => {
157 let ci = this.mycolor=='w' ? i : sizeX-i-1;
158 return h(
159 'div',
160 {
161 'class': {
162 'row': true,
163 },
164 style: { 'opacity': this.choices.length>0?"0.5":"1" },
165 },
166 _.range(sizeY).map(j => {
167 let cj = this.mycolor=='w' ? j : sizeY-j-1;
168 let elems = [];
169 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
170 {
171 elems.push(
172 h(
173 'img',
174 {
175 'class': {
176 'piece': true,
177 'ghost': !!this.selectedPiece
178 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
179 },
180 attrs: {
181 src: "/images/pieces/" +
182 VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
183 },
184 }
185 )
186 );
187 }
188 if (!this.expert && hintSquares[ci][cj])
189 {
190 elems.push(
191 h(
192 'img',
193 {
194 'class': {
195 'mark-square': true,
196 },
197 attrs: {
198 src: "/images/mark.svg",
199 },
200 }
201 )
202 );
203 }
204 const lm = this.vr.lastMove;
205 const showLight = !this.expert &&
206 (this.mode!="idle" || this.cursor==this.vr.moves.length);
207 return h(
208 'div',
209 {
210 'class': {
211 'board': true,
212 ['board'+sizeY]: true,
213 'light-square': (i+j)%2==0,
214 'dark-square': (i+j)%2==1,
215 'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
216 'incheck': showLight && incheckSq[ci][cj],
217 },
218 attrs: {
219 id: this.getSquareId({x:ci,y:cj}),
220 },
221 },
222 elems
223 );
224 })
225 );
226 }), choices]
227 );
228 if (this.mode != "idle")
229 {
230 actionArray.push(
231 h('button',
232 {
233 on: { click: this.resign },
234 attrs: { "aria-label": 'Resign' },
235 'class': {
236 "tooltip":true,
237 "bottom": true,
238 },
239 },
240 [h('i', { 'class': { "material-icons": true } }, "flag")])
241 );
242 }
243 else if (this.vr.moves.length > 0)
244 {
245 // A game finished, and another is not started yet: allow navigation
246 actionArray = actionArray.concat([
247 h('button',
248 {
249 style: { "margin-left": "30px" },
250 on: { click: e => this.undo() },
251 attrs: { "aria-label": 'Undo' },
252 'class': {
253 "tooltip":true,
254 "bottom": true,
255 },
256 },
257 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
258 h('button',
259 {
260 on: { click: e => this.play() },
261 attrs: { "aria-label": 'Play' },
262 'class': {
263 "tooltip":true,
264 "bottom": true,
265 },
266 },
267 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
268 ]
269 );
270 }
271 elementArray.push(gameDiv);
272 if (!!this.vr.reserve)
273 {
274 const shiftIdx = (this.mycolor=="w" ? 0 : 1);
275 let myReservePiecesArray = [];
276 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
277 {
278 myReservePiecesArray.push(h('div',
279 {
280 'class': {'board':true, ['board'+sizeY]:true},
281 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
282 },
283 [
284 h('img',
285 {
286 'class': {"piece":true},
287 attrs: {
288 "src": "/images/pieces/" +
289 this.vr.getReservePpath(this.mycolor,i) + ".svg",
290 }
291 }),
292 h('sup',
293 {style: { "padding-left":"40%"} },
294 [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ]
295 )
296 ]));
297 }
298 let oppReservePiecesArray = [];
299 const oppCol = this.vr.getOppCol(this.mycolor);
300 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
301 {
302 oppReservePiecesArray.push(h('div',
303 {
304 'class': {'board':true, ['board'+sizeY]:true},
305 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
306 },
307 [
308 h('img',
309 {
310 'class': {"piece":true},
311 attrs: {
312 "src": "/images/pieces/" +
313 this.vr.getReservePpath(oppCol,i) + ".svg",
314 }
315 }),
316 h('sup',
317 {style: { "padding-left":"40%"} },
318 [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ]
319 )
320 ]));
321 }
322 let reserves = h('div',
323 {
324 'class':{'game':true},
325 style: {"margin-bottom": "20px"},
326 },
327 [
328 h('div',
329 {
330 'class': { 'row': true },
331 style: {"margin-bottom": "15px"},
332 },
333 myReservePiecesArray
334 ),
335 h('div',
336 { 'class': { 'row': true }},
337 oppReservePiecesArray
338 )
339 ]
340 );
341 elementArray.push(reserves);
342 }
343 const eogMessage = this.getEndgameMessage(this.score);
344 const modalEog = [
345 h('input',
346 {
347 attrs: { "id": "modal-eog", type: "checkbox" },
348 "class": { "modal": true },
349 }),
350 h('div',
351 {
352 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
353 },
354 [
355 h('div',
356 {
357 "class": { "card": true, "smallpad": true },
358 },
359 [
360 h('label',
361 {
362 attrs: { "for": "modal-eog" },
363 "class": { "modal-close": true },
364 }
365 ),
366 h('h3',
367 {
368 "class": { "section": true },
369 domProps: { innerHTML: eogMessage },
370 }
371 )
372 ]
373 )
374 ]
375 )
376 ];
377 elementArray = elementArray.concat(modalEog);
378 }
379 const modalNewgame = [
380 h('input',
381 {
382 attrs: { "id": "modal-newgame", type: "checkbox" },
383 "class": { "modal": true },
384 }),
385 h('div',
386 {
387 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
388 },
389 [
390 h('div',
391 {
392 "class": { "card": true, "smallpad": true },
393 },
394 [
395 h('label',
396 {
397 attrs: { "id": "close-newgame", "for": "modal-newgame" },
398 "class": { "modal-close": true },
399 }
400 ),
401 h('h3',
402 {
403 "class": { "section": true },
404 domProps: { innerHTML: "New game" },
405 }
406 ),
407 h('p',
408 {
409 "class": { "section": true },
410 domProps: { innerHTML: "Waiting for opponent..." },
411 }
412 )
413 ]
414 )
415 ]
416 )
417 ];
418 elementArray = elementArray.concat(modalNewgame);
419 const actions = h('div',
420 {
421 attrs: { "id": "actions" },
422 'class': { 'text-center': true },
423 },
424 actionArray
425 );
426 elementArray.push(actions);
427 if (this.score != "*")
428 {
429 elementArray.push(
430 h('div',
431 { attrs: { id: "pgn-div" } },
432 [
433 h('a',
434 {
435 attrs: {
436 id: "download",
437 href: "#",
438 }
439 }
440 ),
441 h('p',
442 {
443 attrs: { id: "pgn-game" },
444 on: { click: this.download },
445 domProps: { innerHTML: this.pgnTxt }
446 }
447 )
448 ]
449 )
450 );
451 }
452 else if (this.mode != "idle")
453 {
454 // Show current FEN (at least for debug)
455 elementArray.push(
456 h('div',
457 { attrs: { id: "fen-div" } },
458 [
459 h('p',
460 {
461 attrs: { id: "fen-string" },
462 domProps: { innerHTML: this.vr.getBaseFen() }
463 }
464 )
465 ]
466 )
467 );
468 }
469 return h(
470 'div',
471 {
472 'class': {
473 "col-sm-12":true,
474 "col-md-8":true,
475 "col-md-offset-2":true,
476 "col-lg-6":true,
477 "col-lg-offset-3":true,
478 },
479 // NOTE: click = mousedown + mouseup
480 on: {
481 mousedown: this.mousedown,
482 mousemove: this.mousemove,
483 mouseup: this.mouseup,
484 touchstart: this.mousedown,
485 touchmove: this.mousemove,
486 touchend: this.mouseup,
487 },
488 },
489 elementArray
490 );
491 },
492 created: function() {
493 const url = socketUrl;
494 const continuation = (localStorage.getItem("variant") === variant);
495 this.myid = continuation
496 ? localStorage.getItem("myid")
497 // random enough (TODO: function)
498 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
499 if (!continuation)
500 {
501 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
502 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {});
503 }
504 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
505 const socketOpenListener = () => {
506 if (continuation)
507 {
508 const fen = localStorage.getItem("fen");
509 const mycolor = localStorage.getItem("mycolor");
510 const oppid = localStorage.getItem("oppid");
511 const moves = JSON.parse(localStorage.getItem("moves"));
512 this.newGame("human", fen, mycolor, oppid, moves, true);
513 // Send ping to server (answer pong if opponent is connected)
514 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
515 }
516 else if (localStorage.getItem("newgame") === variant)
517 {
518 // New game request has been cancelled on disconnect
519 this.seek = true;
520 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
521 }
522 };
523 const socketMessageListener = msg => {
524 const data = JSON.parse(msg.data);
525 switch (data.code)
526 {
527 case "newgame": //opponent found
528 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
529 break;
530 case "newmove": //..he played!
531 this.play(data.move, "animate");
532 break;
533 case "pong": //received if we sent a ping (game still alive on our side)
534 this.oppConnected = true;
535 const L = this.vr.moves.length;
536 // Send our "last state" informations to opponent
537 this.conn.send(JSON.stringify({
538 code:"lastate",
539 oppid:this.oppid,
540 lastMove:L>0?this.vr.moves[L-1]:undefined,
541 movesCount:L,
542 }));
543 break;
544 case "lastate": //got opponent infos about last move (we might have resigned)
545 if (this.mode!="human" || this.oppid!=data.oppid)
546 {
547 // OK, we resigned
548 this.conn.send(JSON.stringify({
549 code:"lastate",
550 oppid:this.oppid,
551 lastMove:undefined,
552 movesCount:-1,
553 }));
554 }
555 else if (data.movesCount < 0)
556 {
557 // OK, he resigned
558 this.endGame(this.mycolor=="w"?"1-0":"0-1");
559 }
560 else if (data.movesCount < this.vr.moves.length)
561 {
562 // We must tell last move to opponent
563 const L = this.vr.moves.length;
564 this.conn.send(JSON.stringify({
565 code:"lastate",
566 oppid:this.oppid,
567 lastMove:this.vr.moves[L-1],
568 movesCount:L,
569 }));
570 }
571 else if (data.movesCount > this.vr.moves.length) //just got last move from him
572 this.play(data.lastMove, "animate");
573 break;
574 case "resign": //..you won!
575 this.endGame(this.mycolor=="w"?"1-0":"0-1");
576 break;
577 // TODO: also use (dis)connect info to count online players?
578 case "connect":
579 case "disconnect":
580 if (this.mode == "human" && this.oppid == data.id)
581 this.oppConnected = (data.code == "connect");
582 break;
583 }
584 };
585 const socketCloseListener = () => {
586 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
587 this.conn.addEventListener('open', socketOpenListener);
588 this.conn.addEventListener('message', socketMessageListener);
589 this.conn.addEventListener('close', socketCloseListener);
590 };
591 this.conn.onopen = socketOpenListener;
592 this.conn.onmessage = socketMessageListener;
593 this.conn.onclose = socketCloseListener;
594 // Listen to keyboard left/right to navigate in game
595 document.onkeydown = event => {
596 if (this.mode == "idle" && this.vr.moves.length > 0
597 && [37,39].includes(event.keyCode))
598 {
599 event.preventDefault();
600 if (event.keyCode == 37) //Back
601 this.undo();
602 else //Forward (39)
603 this.play();
604 }
605 };
606 },
607 methods: {
608 download: function() {
609 let content = document.getElementById("pgn-game").innerHTML;
610 content = content.replace(/<br>/g, "\n");
611 // Prepare and trigger download link
612 let downloadAnchor = document.getElementById("download");
613 downloadAnchor.setAttribute("download", "game.pgn");
614 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
615 downloadAnchor.click();
616 },
617 endGame: function(score) {
618 this.score = score;
619 let modalBox = document.getElementById("modal-eog");
620 modalBox.checked = true;
621 // Variants may have special PGN structure (so next function isn't defined here)
622 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
623 setTimeout(() => { modalBox.checked = false; }, 2000);
624 if (this.mode == "human")
625 this.clearStorage();
626 this.mode = "idle";
627 this.cursor = this.vr.moves.length; //to navigate in finished game
628 this.oppid = "";
629 },
630 getEndgameMessage: function(score) {
631 let eogMessage = "Unfinished";
632 switch (this.score)
633 {
634 case "1-0":
635 eogMessage = "White win";
636 break;
637 case "0-1":
638 eogMessage = "Black win";
639 break;
640 case "1/2":
641 eogMessage = "Draw";
642 break;
643 }
644 return eogMessage;
645 },
646 toggleExpertMode: function() {
647 this.expert = !this.expert;
648 document.cookie = "expert=" + (this.expert ? "1" : "0");
649 },
650 resign: function() {
651 if (this.mode == "human" && this.oppConnected)
652 {
653 try {
654 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
655 } catch (INVALID_STATE_ERR) {
656 return; //socket is not ready (and not yet reconnected)
657 }
658 }
659 this.endGame(this.mycolor=="w"?"0-1":"1-0");
660 },
661 setStorage: function() {
662 localStorage.setItem("myid", this.myid);
663 localStorage.setItem("variant", variant);
664 localStorage.setItem("mycolor", this.mycolor);
665 localStorage.setItem("oppid", this.oppid);
666 localStorage.setItem("fenStart", this.fenStart);
667 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
668 localStorage.setItem("fen", this.vr.getFen());
669 },
670 updateStorage: function() {
671 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
672 localStorage.setItem("fen", this.vr.getFen());
673 },
674 clearStorage: function() {
675 delete localStorage["variant"];
676 delete localStorage["myid"];
677 delete localStorage["mycolor"];
678 delete localStorage["oppid"];
679 delete localStorage["fenStart"];
680 delete localStorage["fen"];
681 delete localStorage["moves"];
682 },
683 clickGameSeek: function() {
684 if (this.mode == "human")
685 return; //no newgame while playing
686 if (this.seek)
687 {
688 delete localStorage["newgame"]; //cancel game seek
689 this.seek = false;
690 }
691 else
692 this.newGame("human");
693 },
694 clickComputerGame: function() {
695 if (this.mode == "human")
696 return; //no newgame while playing
697 this.newGame("computer");
698 },
699 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
700 const fen = fenInit || VariantRules.GenRandInitFen();
701 console.log(fen); //DEBUG
702 this.score = "*";
703 if (mode=="human" && !oppId)
704 {
705 const storageVariant = localStorage.getItem("variant");
706 if (!!storageVariant && storageVariant !== variant)
707 {
708 alert("Finish your " + storageVariant + " game first!");
709 return;
710 }
711 // Send game request and wait..
712 localStorage["newgame"] = variant;
713 this.seek = true;
714 this.clearStorage(); //in case of
715 try {
716 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
717 } catch (INVALID_STATE_ERR) {
718 return; //nothing achieved
719 }
720 if (continuation !== "reconnect") //TODO: bad HACK...
721 {
722 let modalBox = document.getElementById("modal-newgame");
723 modalBox.checked = true;
724 setTimeout(() => { modalBox.checked = false; }, 2000);
725 }
726 return;
727 }
728 // random enough (TODO: function)
729 this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
730 this.vr = new VariantRules(fen, moves || []);
731 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
732 this.mode = mode;
733 this.incheck = []; //in case of
734 this.fenStart = continuation
735 ? localStorage.getItem("fenStart")
736 : fen.split(" ")[0]; //Only the position matters
737 if (mode=="human")
738 {
739 // Opponent found!
740 if (!continuation)
741 {
742 // Not playing sound on game continuation:
743 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
744 document.getElementById("modal-newgame").checked = false;
745 }
746 this.oppid = oppId;
747 this.oppConnected = true;
748 this.mycolor = color;
749 this.seek = false;
750 if (!!moves && moves.length > 0) //imply continuation
751 {
752 const lastMove = moves[moves.length-1];
753 this.vr.undo(lastMove);
754 this.incheck = this.vr.getCheckSquares(lastMove);
755 this.vr.play(lastMove, "ingame");
756 }
757 delete localStorage["newgame"];
758 this.setStorage(); //in case of interruptions
759 }
760 else //against computer
761 {
762 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
763 if (this.mycolor == 'b')
764 setTimeout(this.playComputerMove, 500);
765 }
766 },
767 playComputerMove: function() {
768 const timeStart = Date.now();
769 const nbMoves = this.vr.moves.length; //using played moves to know if search finished
770 const gameId = this.gameId; //to know if game was reset before timer end
771 setTimeout(
772 () => {
773 if (gameId != this.gameId)
774 return; //game stopped
775 const L = this.vr.moves.length;
776 if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish
777 this.vr.shouldReturn = true;
778 }, 5000);
779 const compMove = this.vr.getComputerMove();
780 // (first move) HACK: avoid selecting elements before they appear on page:
781 const delay = Math.max(500-(Date.now()-timeStart), 0);
782 setTimeout(() => this.play(compMove, "animate"), delay);
783 },
784 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
785 getSquareId: function(o) {
786 // NOTE: a separator is required to allow any size of board
787 return "sq-" + o.x + "-" + o.y;
788 },
789 // Inverse function
790 getSquareFromId: function(id) {
791 let idParts = id.split('-');
792 return [parseInt(idParts[1]), parseInt(idParts[2])];
793 },
794 mousedown: function(e) {
795 e = e || window.event;
796 let ingame = false;
797 let elem = e.target;
798 while (!ingame && elem !== null)
799 {
800 if (elem.classList.contains("game"))
801 {
802 ingame = true;
803 break;
804 }
805 elem = elem.parentElement;
806 }
807 if (!ingame) //let default behavior (click on button...)
808 return;
809 e.preventDefault(); //disable native drag & drop
810 if (!this.selectedPiece && e.target.classList.contains("piece"))
811 {
812 // Next few lines to center the piece on mouse cursor
813 let rect = e.target.parentNode.getBoundingClientRect();
814 this.start = {
815 x: rect.x + rect.width/2,
816 y: rect.y + rect.width/2,
817 id: e.target.parentNode.id
818 };
819 this.selectedPiece = e.target.cloneNode();
820 this.selectedPiece.style.position = "absolute";
821 this.selectedPiece.style.top = 0;
822 this.selectedPiece.style.display = "inline-block";
823 this.selectedPiece.style.zIndex = 3000;
824 let startSquare = this.getSquareFromId(e.target.parentNode.id);
825 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
826 ? this.vr.getPossibleMovesFrom(startSquare)
827 : [];
828 // Next line add moving piece just after current image (required for Crazyhouse reserve)
829 e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
830 }
831 },
832 mousemove: function(e) {
833 if (!this.selectedPiece)
834 return;
835 e = e || window.event;
836 // If there is an active element, move it around
837 if (!!this.selectedPiece)
838 {
839 const [offsetX,offsetY] = !!e.clientX
840 ? [e.clientX,e.clientY] //desktop browser
841 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone
842 this.selectedPiece.style.left = (offsetX-this.start.x) + "px";
843 this.selectedPiece.style.top = (offsetY-this.start.y) + "px";
844 }
845 },
846 mouseup: function(e) {
847 if (!this.selectedPiece)
848 return;
849 e = e || window.event;
850 // Read drop target (or parentElement, parentNode... if type == "img")
851 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
852 const [offsetX,offsetY] = !!e.clientX
853 ? [e.clientX,e.clientY]
854 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY];
855 let landing = document.elementFromPoint(offsetX, offsetY);
856 this.selectedPiece.style.zIndex = 3000;
857 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
858 landing = landing.parentNode;
859 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
860 return;
861 // OK: process move attempt
862 let endSquare = this.getSquareFromId(landing.id);
863 let moves = this.findMatchingMoves(endSquare);
864 this.possibleMoves = [];
865 if (moves.length > 1)
866 this.choices = moves;
867 else if (moves.length==1)
868 this.play(moves[0]);
869 // Else: impossible move
870 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
871 delete this.selectedPiece;
872 this.selectedPiece = null;
873 },
874 findMatchingMoves: function(endSquare) {
875 // Run through moves list and return the matching set (if promotions...)
876 let moves = [];
877 this.possibleMoves.forEach(function(m) {
878 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
879 moves.push(m);
880 });
881 return moves;
882 },
883 animateMove: function(move) {
884 let startSquare = document.getElementById(this.getSquareId(move.start));
885 let endSquare = document.getElementById(this.getSquareId(move.end));
886 let rectStart = startSquare.getBoundingClientRect();
887 let rectEnd = endSquare.getBoundingClientRect();
888 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
889 let movingPiece =
890 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
891 // HACK for animation (with positive translate, image slides "under background"...)
892 // Possible improvement: just alter squares on the piece's way...
893 squares = document.getElementsByClassName("board");
894 for (let i=0; i<squares.length; i++)
895 {
896 let square = squares.item(i);
897 if (square.id != this.getSquareId(move.start))
898 square.style.zIndex = "-1";
899 }
900 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
901 movingPiece.style.transitionDuration = "0.2s";
902 movingPiece.style.zIndex = "3000";
903 setTimeout( () => {
904 for (let i=0; i<squares.length; i++)
905 squares.item(i).style.zIndex = "auto";
906 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
907 this.play(move);
908 }, 200);
909 },
910 play: function(move, programmatic) {
911 if (!move)
912 {
913 // Navigate after game is over
914 if (this.cursor >= this.vr.moves.length)
915 return; //already at the end
916 move = this.vr.moves[this.cursor++];
917 }
918 if (!!programmatic) //computer or human opponent
919 {
920 this.animateMove(move);
921 return;
922 }
923 // Not programmatic, or animation is over
924 if (this.mode == "human" && this.vr.turn == this.mycolor)
925 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
926 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
927 if (this.mode != "idle")
928 {
929 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
930 this.vr.play(move, "ingame");
931 }
932 else
933 {
934 VariantRules.PlayOnBoard(this.vr.board, move);
935 this.$forceUpdate(); //TODO: ?!
936 }
937 if (this.mode == "human")
938 this.updateStorage(); //after our moves and opponent moves
939 if (this.mode != "idle")
940 {
941 const eog = this.vr.checkGameOver();
942 if (eog != "*")
943 this.endGame(eog);
944 }
945 if (this.mode == "computer" && this.vr.turn != this.mycolor)
946 setTimeout(this.playComputerMove, 500);
947 },
948 undo: function() {
949 // Navigate after game is over
950 if (this.cursor == 0)
951 return; //already at the beginning
952 if (this.cursor == this.vr.moves.length)
953 this.incheck = []; //in case of...
954 const move = this.vr.moves[--this.cursor];
955 VariantRules.UndoOnBoard(this.vr.board, move);
956 this.$forceUpdate(); //TODO: ?!
957 }
958 },
959 })