Fix mousedown event (only in game)
[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 highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
206 return h(
207 'div',
208 {
209 'class': {
210 'board': true,
211 ['board'+sizeY]: true,
212 'light-square': (i+j)%2==0 && (this.expert || !highlight),
213 'dark-square': (i+j)%2==1 && (this.expert || !highlight),
214 'highlight': !this.expert && highlight,
215 'incheck': !this.expert && incheckSq[ci][cj],
216 },
217 attrs: {
218 id: this.getSquareId({x:ci,y:cj}),
219 },
220 },
221 elems
222 );
223 })
224 );
225 }), choices]
226 );
227 if (this.mode != "idle")
228 {
229 actionArray.push(
230 h('button',
231 {
232 on: { click: this.resign },
233 attrs: { "aria-label": 'Resign' },
234 'class': {
235 "tooltip":true,
236 "bottom": true,
237 },
238 },
239 [h('i', { 'class': { "material-icons": true } }, "flag")])
240 );
241 }
242 elementArray.push(gameDiv);
243 if (!!this.vr.reserve)
244 {
245 const shiftIdx = (this.mycolor=="w" ? 0 : 1);
246 let myReservePiecesArray = [];
247 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
248 {
249 myReservePiecesArray.push(h('div',
250 {
251 'class': {'board':true, ['board'+sizeY]:true},
252 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
253 },
254 [
255 h('img',
256 {
257 'class': {"piece":true},
258 attrs: {
259 "src": "/images/pieces/" +
260 this.vr.getReservePpath(this.mycolor,i) + ".svg",
261 }
262 }),
263 h('sup',
264 {style: { "padding-left":"40%"} },
265 [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ]
266 )
267 ]));
268 }
269 let oppReservePiecesArray = [];
270 const oppCol = this.vr.getOppCol(this.mycolor);
271 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
272 {
273 oppReservePiecesArray.push(h('div',
274 {
275 'class': {'board':true, ['board'+sizeY]:true},
276 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
277 },
278 [
279 h('img',
280 {
281 'class': {"piece":true},
282 attrs: {
283 "src": "/images/pieces/" +
284 this.vr.getReservePpath(oppCol,i) + ".svg",
285 }
286 }),
287 h('sup',
288 {style: { "padding-left":"40%"} },
289 [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ]
290 )
291 ]));
292 }
293 let reserves = h('div',
294 {
295 'class':{'game':true},
296 style: {"margin-bottom": "20px"},
297 },
298 [
299 h('div',
300 {
301 'class': { 'row': true },
302 style: {"margin-bottom": "15px"},
303 },
304 myReservePiecesArray
305 ),
306 h('div',
307 { 'class': { 'row': true }},
308 oppReservePiecesArray
309 )
310 ]
311 );
312 elementArray.push(reserves);
313 }
314 const eogMessage = this.getEndgameMessage(this.score);
315 const modalEog = [
316 h('input',
317 {
318 attrs: { "id": "modal-eog", type: "checkbox" },
319 "class": { "modal": true },
320 }),
321 h('div',
322 {
323 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
324 },
325 [
326 h('div',
327 {
328 "class": { "card": true, "smallpad": true },
329 },
330 [
331 h('label',
332 {
333 attrs: { "for": "modal-eog" },
334 "class": { "modal-close": true },
335 }
336 ),
337 h('h3',
338 {
339 "class": { "section": true },
340 domProps: { innerHTML: eogMessage },
341 }
342 )
343 ]
344 )
345 ]
346 )
347 ];
348 elementArray = elementArray.concat(modalEog);
349 }
350 const modalNewgame = [
351 h('input',
352 {
353 attrs: { "id": "modal-newgame", type: "checkbox" },
354 "class": { "modal": true },
355 }),
356 h('div',
357 {
358 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
359 },
360 [
361 h('div',
362 {
363 "class": { "card": true, "smallpad": true },
364 },
365 [
366 h('label',
367 {
368 attrs: { "id": "close-newgame", "for": "modal-newgame" },
369 "class": { "modal-close": true },
370 }
371 ),
372 h('h3',
373 {
374 "class": { "section": true },
375 domProps: { innerHTML: "New game" },
376 }
377 ),
378 h('p',
379 {
380 "class": { "section": true },
381 domProps: { innerHTML: "Waiting for opponent..." },
382 }
383 )
384 ]
385 )
386 ]
387 )
388 ];
389 elementArray = elementArray.concat(modalNewgame);
390 const actions = h('div',
391 {
392 attrs: { "id": "actions" },
393 'class': { 'text-center': true },
394 },
395 actionArray
396 );
397 elementArray.push(actions);
398 if (this.score != "*")
399 {
400 elementArray.push(
401 h('div',
402 { attrs: { id: "pgn-div" } },
403 [
404 h('a',
405 {
406 attrs: {
407 id: "download",
408 href: "#",
409 }
410 }
411 ),
412 h('p',
413 {
414 attrs: { id: "pgn-game" },
415 on: { click: this.download },
416 domProps: {
417 innerHTML: this.pgnTxt
418 }
419 }
420 )
421 ]
422 )
423 );
424 }
425 return h(
426 'div',
427 {
428 'class': {
429 "col-sm-12":true,
430 "col-md-8":true,
431 "col-md-offset-2":true,
432 "col-lg-6":true,
433 "col-lg-offset-3":true,
434 },
435 // NOTE: click = mousedown + mouseup --> what about smartphone?!
436 on: {
437 mousedown: this.mousedown,
438 mousemove: this.mousemove,
439 mouseup: this.mouseup,
440 touchstart: this.mousedown,
441 touchmove: this.mousemove,
442 touchend: this.mouseup,
443 },
444 },
445 elementArray
446 );
447 },
448 created: function() {
449 const url = socketUrl;
450 const continuation = (localStorage.getItem("variant") === variant);
451 this.myid = continuation
452 ? localStorage.getItem("myid")
453 // random enough (TODO: function)
454 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
455 if (!continuation)
456 {
457 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
458 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {});
459 }
460 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
461 const socketOpenListener = () => {
462 if (continuation)
463 {
464 const fen = localStorage.getItem("fen");
465 const mycolor = localStorage.getItem("mycolor");
466 const oppid = localStorage.getItem("oppid");
467 const moves = JSON.parse(localStorage.getItem("moves"));
468 this.newGame("human", fen, mycolor, oppid, moves, true);
469 // Send ping to server (answer pong if opponent is connected)
470 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
471 }
472 else if (localStorage.getItem("newgame") === variant)
473 {
474 // New game request has been cancelled on disconnect
475 this.seek = true;
476 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
477 }
478 };
479 const socketMessageListener = msg => {
480 const data = JSON.parse(msg.data);
481 switch (data.code)
482 {
483 case "newgame": //opponent found
484 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
485 break;
486 case "newmove": //..he played!
487 this.play(data.move, "animate");
488 break;
489 case "pong": //received if we sent a ping (game still alive on our side)
490 this.oppConnected = true;
491 const L = this.vr.moves.length;
492 // Send our "last state" informations to opponent
493 this.conn.send(JSON.stringify({
494 code:"lastate",
495 oppid:this.oppid,
496 lastMove:L>0?this.vr.moves[L-1]:undefined,
497 movesCount:L,
498 }));
499 break;
500 case "lastate": //got opponent infos about last move (we might have resigned)
501 if (this.mode!="human" || this.oppid!=data.oppid)
502 {
503 // OK, we resigned
504 this.conn.send(JSON.stringify({
505 code:"lastate",
506 oppid:this.oppid,
507 lastMove:undefined,
508 movesCount:-1,
509 }));
510 }
511 else if (data.movesCount < 0)
512 {
513 // OK, he resigned
514 this.endGame(this.mycolor=="w"?"1-0":"0-1");
515 }
516 else if (data.movesCount < this.vr.moves.length)
517 {
518 // We must tell last move to opponent
519 const L = this.vr.moves.length;
520 this.conn.send(JSON.stringify({
521 code:"lastate",
522 oppid:this.oppid,
523 lastMove:this.vr.moves[L-1],
524 movesCount:L,
525 }));
526 }
527 else if (data.movesCount > this.vr.moves.length) //just got last move from him
528 this.play(data.lastMove, "animate");
529 break;
530 case "resign": //..you won!
531 this.endGame(this.mycolor=="w"?"1-0":"0-1");
532 break;
533 // TODO: also use (dis)connect info to count online players?
534 case "connect":
535 case "disconnect":
536 if (this.mode == "human" && this.oppid == data.id)
537 this.oppConnected = (data.code == "connect");
538 break;
539 }
540 };
541 const socketCloseListener = () => {
542 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
543 this.conn.addEventListener('open', socketOpenListener);
544 this.conn.addEventListener('message', socketMessageListener);
545 this.conn.addEventListener('close', socketCloseListener);
546 };
547 this.conn.onopen = socketOpenListener;
548 this.conn.onmessage = socketMessageListener;
549 this.conn.onclose = socketCloseListener;
550 },
551 methods: {
552 download: function() {
553 let content = document.getElementById("pgn-game").innerHTML;
554 content = content.replace(/<br>/g, "\n");
555 // Prepare and trigger download link
556 let downloadAnchor = document.getElementById("download");
557 downloadAnchor.setAttribute("download", "game.pgn");
558 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
559 downloadAnchor.click();
560 },
561 endGame: function(score) {
562 this.score = score;
563 let modalBox = document.getElementById("modal-eog");
564 modalBox.checked = true;
565 // Variants may have special PGN structure (so next function isn't defined here)
566 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
567 setTimeout(() => { modalBox.checked = false; }, 2000);
568 if (this.mode == "human")
569 this.clearStorage();
570 this.mode = "idle";
571 this.oppid = "";
572 },
573 getEndgameMessage: function(score) {
574 let eogMessage = "Unfinished";
575 switch (this.score)
576 {
577 case "1-0":
578 eogMessage = "White win";
579 break;
580 case "0-1":
581 eogMessage = "Black win";
582 break;
583 case "1/2":
584 eogMessage = "Draw";
585 break;
586 }
587 return eogMessage;
588 },
589 toggleExpertMode: function() {
590 this.expert = !this.expert;
591 document.cookie = "expert=" + (this.expert ? "1" : "0");
592 },
593 resign: function() {
594 if (this.mode == "human" && this.oppConnected)
595 {
596 try {
597 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
598 } catch (INVALID_STATE_ERR) {
599 return; //socket is not ready (and not yet reconnected)
600 }
601 }
602 this.endGame(this.mycolor=="w"?"0-1":"1-0");
603 },
604 setStorage: function() {
605 localStorage.setItem("myid", this.myid);
606 localStorage.setItem("variant", variant);
607 localStorage.setItem("mycolor", this.mycolor);
608 localStorage.setItem("oppid", this.oppid);
609 localStorage.setItem("fenStart", this.fenStart);
610 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
611 localStorage.setItem("fen", this.vr.getFen());
612 },
613 updateStorage: function() {
614 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
615 localStorage.setItem("fen", this.vr.getFen());
616 },
617 clearStorage: function() {
618 delete localStorage["variant"];
619 delete localStorage["myid"];
620 delete localStorage["mycolor"];
621 delete localStorage["oppid"];
622 delete localStorage["fenStart"];
623 delete localStorage["fen"];
624 delete localStorage["moves"];
625 },
626 clickGameSeek: function() {
627 if (this.mode == "human")
628 return; //no newgame while playing
629 if (this.seek)
630 {
631 delete localStorage["newgame"]; //cancel game seek
632 this.seek = false;
633 }
634 else
635 this.newGame("human");
636 },
637 clickComputerGame: function() {
638 if (this.mode == "human")
639 return; //no newgame while playing
640 this.newGame("computer");
641 },
642 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
643 const fen = fenInit || VariantRules.GenRandInitFen();
644 console.log(fen); //DEBUG
645 this.score = "*";
646 if (mode=="human" && !oppId)
647 {
648 const storageVariant = localStorage.getItem("variant");
649 if (!!storageVariant && storageVariant !== variant)
650 {
651 alert("Finish your " + storageVariant + " game first!");
652 return;
653 }
654 // Send game request and wait..
655 localStorage["newgame"] = variant;
656 this.seek = true;
657 this.clearStorage(); //in case of
658 try {
659 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
660 } catch (INVALID_STATE_ERR) {
661 return; //nothing achieved
662 }
663 if (continuation !== "reconnect") //TODO: bad HACK...
664 {
665 let modalBox = document.getElementById("modal-newgame");
666 modalBox.checked = true;
667 setTimeout(() => { modalBox.checked = false; }, 2000);
668 }
669 return;
670 }
671 // random enough (TODO: function)
672 this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
673 this.vr = new VariantRules(fen, moves || []);
674 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
675 this.mode = mode;
676 this.incheck = []; //in case of
677 this.fenStart = continuation
678 ? localStorage.getItem("fenStart")
679 : fen.split(" ")[0]; //Only the position matters
680 if (mode=="human")
681 {
682 // Opponent found!
683 if (!continuation)
684 {
685 // Not playing sound on game continuation:
686 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
687 document.getElementById("modal-newgame").checked = false;
688 }
689 this.oppid = oppId;
690 this.oppConnected = true;
691 this.mycolor = color;
692 this.seek = false;
693 if (!!moves && moves.length > 0) //imply continuation
694 {
695 const lastMove = moves[moves.length-1];
696 this.vr.undo(lastMove);
697 this.incheck = this.vr.getCheckSquares(lastMove);
698 this.vr.play(lastMove, "ingame");
699 }
700 delete localStorage["newgame"];
701 this.setStorage(); //in case of interruptions
702 }
703 else //against computer
704 {
705 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
706 if (this.mycolor == 'b')
707 setTimeout(this.playComputerMove, 500);
708 }
709 },
710 playComputerMove: function() {
711 const timeStart = Date.now();
712 const nbMoves = this.vr.moves.length; //using played moves to know if search finished
713 const gameId = this.gameId; //to know if game was reset before timer end
714 setTimeout(
715 () => {
716 if (gameId != this.gameId)
717 return; //game stopped
718 const L = this.vr.moves.length;
719 if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish
720 this.vr.shouldReturn = true;
721 }, 5000);
722 const compMove = this.vr.getComputerMove();
723 // (first move) HACK: avoid selecting elements before they appear on page:
724 const delay = Math.max(500-(Date.now()-timeStart), 0);
725 setTimeout(() => this.play(compMove, "animate"), delay);
726 },
727 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
728 getSquareId: function(o) {
729 // NOTE: a separator is required to allow any size of board
730 return "sq-" + o.x + "-" + o.y;
731 },
732 // Inverse function
733 getSquareFromId: function(id) {
734 let idParts = id.split('-');
735 return [parseInt(idParts[1]), parseInt(idParts[2])];
736 },
737 mousedown: function(e) {
738 e = e || window.event;
739 let ingame = false;
740 let elem = e.target;
741 while (!ingame && elem !== null)
742 {
743 if (elem.classList.contains("game"))
744 {
745 ingame = true;
746 break;
747 }
748 elem = elem.parentElement;
749 }
750 if (!ingame) //let default behavior (click on button...)
751 return;
752 e.preventDefault(); //disable native drag & drop
753 if (!this.selectedPiece && e.target.classList.contains("piece"))
754 {
755 // Next few lines to center the piece on mouse cursor
756 let rect = e.target.parentNode.getBoundingClientRect();
757 this.start = {
758 x: rect.x + rect.width/2,
759 y: rect.y + rect.width/2,
760 id: e.target.parentNode.id
761 };
762 this.selectedPiece = e.target.cloneNode();
763 this.selectedPiece.style.position = "absolute";
764 this.selectedPiece.style.top = 0;
765 this.selectedPiece.style.display = "inline-block";
766 this.selectedPiece.style.zIndex = 3000;
767 let startSquare = this.getSquareFromId(e.target.parentNode.id);
768 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
769 ? this.vr.getPossibleMovesFrom(startSquare)
770 : [];
771 // Next line add moving piece just after current image (required for Crazyhouse reserve)
772 e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
773 }
774 },
775 mousemove: function(e) {
776 if (!this.selectedPiece)
777 return;
778 e = e || window.event;
779 // If there is an active element, move it around
780 if (!!this.selectedPiece)
781 {
782 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
783 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
784 }
785 },
786 mouseup: function(e) {
787 if (!this.selectedPiece)
788 return;
789 e = e || window.event;
790 // Read drop target (or parentElement, parentNode... if type == "img")
791 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
792 let landing = document.elementFromPoint(e.clientX, e.clientY);
793 this.selectedPiece.style.zIndex = 3000;
794 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
795 landing = landing.parentNode;
796 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
797 return;
798 // OK: process move attempt
799 let endSquare = this.getSquareFromId(landing.id);
800 let moves = this.findMatchingMoves(endSquare);
801 this.possibleMoves = [];
802 if (moves.length > 1)
803 this.choices = moves;
804 else if (moves.length==1)
805 this.play(moves[0]);
806 // Else: impossible move
807 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
808 delete this.selectedPiece;
809 this.selectedPiece = null;
810 },
811 findMatchingMoves: function(endSquare) {
812 // Run through moves list and return the matching set (if promotions...)
813 let moves = [];
814 this.possibleMoves.forEach(function(m) {
815 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
816 moves.push(m);
817 });
818 return moves;
819 },
820 animateMove: function(move) {
821 let startSquare = document.getElementById(this.getSquareId(move.start));
822 let endSquare = document.getElementById(this.getSquareId(move.end));
823 let rectStart = startSquare.getBoundingClientRect();
824 let rectEnd = endSquare.getBoundingClientRect();
825 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
826 let movingPiece =
827 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
828 // HACK for animation (with positive translate, image slides "under background"...)
829 // Possible improvement: just alter squares on the piece's way...
830 squares = document.getElementsByClassName("board");
831 for (let i=0; i<squares.length; i++)
832 {
833 let square = squares.item(i);
834 if (square.id != this.getSquareId(move.start))
835 square.style.zIndex = "-1";
836 }
837 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
838 movingPiece.style.transitionDuration = "0.2s";
839 movingPiece.style.zIndex = "3000";
840 setTimeout( () => {
841 for (let i=0; i<squares.length; i++)
842 squares.item(i).style.zIndex = "auto";
843 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
844 this.play(move);
845 }, 200);
846 },
847 play: function(move, programmatic) {
848 if (!!programmatic) //computer or human opponent
849 {
850 this.animateMove(move);
851 return;
852 }
853 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
854 // Not programmatic, or animation is over
855 if (this.mode == "human" && this.vr.turn == this.mycolor)
856 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
857 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
858 this.vr.play(move, "ingame");
859 if (this.mode == "human")
860 this.updateStorage(); //after our moves and opponent moves
861 const eog = this.vr.checkGameOver();
862 if (eog != "*")
863 this.endGame(eog);
864 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
865 setTimeout(this.playComputerMove, 500);
866 },
867 },
868 })