CLeaner way to fix PGN
[vchess.git] / public / javascripts / components / game.js
CommitLineData
a29d9d6b 1// TODO: use indexedDB instead of localStorage? (more flexible: allow several games)
1d184b4c
BA
2Vue.component('my-game', {
3 data: function() {
4 return {
5 vr: null, //object to check moves, store them, FEN..
6 mycolor: "w",
7 possibleMoves: [], //filled after each valid click/dragstart
8 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket messages
dfb4afc1 12 score: "*", //'*' means 'unfinished'
1d184b4c
BA
13 mode: "idle", //human, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
15 oppConnected: false,
186516b8 16 seek: false,
762b7c9c 17 fenStart: "",
4b5fe306 18 incheck: [],
3840e240 19 pgnTxt: "",
3ed62725 20 expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false,
1d184b4c
BA
21 };
22 },
23 render(h) {
24 let [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; });
4b5fe306
BA
28 // Also precompute in-check squares
29 let incheckSq = doubleArray(sizeX, sizeY, false);
30 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
1d184b4c 31 let elementArray = [];
186516b8
BA
32 const playingHuman = (this.mode == "human");
33 const playingComp = (this.mode == "computer");
1d184b4c
BA
34 let actionArray = [
35 h('button',
36 {
f3802fcd 37 on: { click: this.clickGameSeek },
1d184b4c 38 attrs: { "aria-label": 'New game VS human' },
186516b8
BA
39 'class': {
40 "tooltip": true,
0706ea91 41 "bottom": true, //display below
186516b8
BA
42 "seek": this.seek,
43 "playing": playingHuman,
44 },
1d184b4c
BA
45 },
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
47 h('button',
48 {
f3802fcd 49 on: { click: this.clickComputerGame },
1d184b4c 50 attrs: { "aria-label": 'New game VS computer' },
186516b8
BA
51 'class': {
52 "tooltip":true,
0706ea91 53 "bottom": true,
186516b8
BA
54 "playing": playingComp,
55 },
1d184b4c
BA
56 },
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
58 ];
59 if (!!this.vr)
60 {
bdb1f12d
BA
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);
1d184b4c
BA
66 if (this.mode == "human")
67 {
68 let connectedIndic = h(
69 'div',
70 {
71 "class": {
bdb1f12d
BA
72 "topindicator": true,
73 "indic-left": true,
1d184b4c
BA
74 "connected": this.oppConnected,
75 "disconnected": !this.oppConnected,
76 },
bdb1f12d
BA
77 style: {
78 "width": indicWidth + "px",
79 "height": indicWidth + "px",
80 },
1d184b4c
BA
81 }
82 );
83 elementArray.push(connectedIndic);
84 }
bdb1f12d
BA
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);
3ed62725
BA
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);
1d184b4c
BA
117 let choices = h('div',
118 {
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
121 style: {
1d184b4c
BA
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': { 'board': true },
132 style: {
133 'width': (100/this.choices.length) + "%",
134 'padding-bottom': (100/this.choices.length) + "%",
135 },
136 },
137 [h('img',
138 {
139 attrs: { "src": '/images/pieces/' + VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
140 'class': { 'choice-piece': true, 'board': true },
141 on: { "click": e => { this.play(m); this.choices=[]; } },
142 })
143 ]
144 );
145 })
146 );
147 // Create board element (+ reserves if needed by variant or mode)
148 let gameDiv = h('div',
149 {
150 'class': { 'game': true },
151 },
152 [_.range(sizeX).map(i => {
153 let ci = this.mycolor=='w' ? i : sizeX-i-1;
154 return h(
155 'div',
156 {
157 'class': {
158 'row': true,
159 },
160 style: { 'opacity': this.choices.length>0?"0.5":"1" },
161 },
162 _.range(sizeY).map(j => {
163 let cj = this.mycolor=='w' ? j : sizeY-j-1;
164 let elems = [];
165 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
166 {
167 elems.push(
168 h(
169 'img',
170 {
171 'class': {
172 'piece': true,
173 'ghost': !!this.selectedPiece && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
174 },
175 attrs: {
176 src: "/images/pieces/" + VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
177 },
178 }
179 )
180 );
181 }
3ed62725 182 if (!this.expert && hintSquares[ci][cj])
1d184b4c
BA
183 {
184 elems.push(
185 h(
186 'img',
187 {
188 'class': {
189 'mark-square': true,
190 },
191 attrs: {
192 src: "/images/mark.svg",
193 },
194 }
195 )
196 );
197 }
30ff6e04 198 const lm = this.vr.lastMove;
e64a4eff 199 const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
1d184b4c
BA
200 return h(
201 'div',
202 {
203 'class': {
204 'board': true,
3ed62725
BA
205 'light-square': (i+j)%2==0 && (this.expert || !highlight),
206 'dark-square': (i+j)%2==1 && (this.expert || !highlight),
207 'highlight': !this.expert && highlight,
208 'incheck': !this.expert && incheckSq[ci][cj],
1d184b4c
BA
209 },
210 attrs: {
211 id: this.getSquareId({x:ci,y:cj}),
212 },
213 },
214 elems
215 );
216 })
217 );
218 }), choices]
219 );
220 actionArray.push(
221 h('button',
222 {
223 on: { click: this.resign },
224 attrs: { "aria-label": 'Resign' },
0706ea91
BA
225 'class': {
226 "tooltip":true,
227 "bottom": true,
228 },
1d184b4c
BA
229 },
230 [h('i', { 'class': { "material-icons": true } }, "flag")])
231 );
232 elementArray.push(gameDiv);
233 // if (!!vr.reserve)
234 // {
235 // let reserve = h('div',
236 // {'class':{'game':true}}, [
237 // h('div',
238 // { 'class': { 'row': true }},
239 // [
240 // h('div',
241 // {'class':{'board':true}},
242 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
243 // )
244 // ]
245 // )
246 // ],
247 // );
248 // elementArray.push(reserve);
249 // }
f3802fcd 250 const eogMessage = this.getEndgameMessage(this.score);
1d184b4c
BA
251 const modalEog = [
252 h('input',
253 {
ecf44502 254 attrs: { "id": "modal-eog", type: "checkbox" },
1d184b4c
BA
255 "class": { "modal": true },
256 }),
257 h('div',
258 {
259 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
260 },
261 [
262 h('div',
263 {
264 "class": { "card": true, "smallpad": true },
265 },
01a135e2
BA
266 [
267 h('label',
268 {
269 attrs: { "for": "modal-eog" },
270 "class": { "modal-close": true },
271 }
272 ),
273 h('h3',
274 {
275 "class": { "section": true },
276 domProps: { innerHTML: eogMessage },
277 }
278 )
279 ]
1d184b4c
BA
280 )
281 ]
282 )
283 ];
284 elementArray = elementArray.concat(modalEog);
285 }
286 const modalNewgame = [
287 h('input',
288 {
ecf44502 289 attrs: { "id": "modal-newgame", type: "checkbox" },
1d184b4c
BA
290 "class": { "modal": true },
291 }),
292 h('div',
293 {
294 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
295 },
296 [
297 h('div',
298 {
299 "class": { "card": true, "smallpad": true },
300 },
301 [
302 h('label',
303 {
ecf44502 304 attrs: { "id": "close-newgame", "for": "modal-newgame" },
1d184b4c
BA
305 "class": { "modal-close": true },
306 }
307 ),
308 h('h3',
309 {
310 "class": { "section": true },
311 domProps: { innerHTML: "New game" },
312 }
313 ),
314 h('p',
315 {
316 "class": { "section": true },
317 domProps: { innerHTML: "Waiting for opponent..." },
318 }
319 )
320 ]
321 )
322 ]
323 )
324 ];
325 elementArray = elementArray.concat(modalNewgame);
326 const actions = h('div',
327 {
328 attrs: { "id": "actions" },
329 'class': { 'text-center': true },
330 },
331 actionArray
332 );
333 elementArray.push(actions);
01a135e2
BA
334 if (this.score != "*")
335 {
336 elementArray.push(
337 h('div',
01ca2adc 338 { attrs: { id: "pgn-div" } },
01a135e2 339 [
01ca2adc
BA
340 h('a',
341 {
342 attrs: {
343 id: "download",
344 href: "#",
345 }
346 }
347 ),
01a135e2
BA
348 h('p',
349 {
01ca2adc
BA
350 attrs: { id: "pgn-game" },
351 on: { click: this.download },
01a135e2 352 domProps: {
3840e240 353 innerHTML: this.pgnTxt
01a135e2
BA
354 }
355 }
356 )
357 ]
358 )
359 );
360 }
1d184b4c
BA
361 return h(
362 'div',
363 {
364 'class': {
365 "col-sm-12":true,
366 "col-md-8":true,
367 "col-md-offset-2":true,
368 "col-lg-6":true,
369 "col-lg-offset-3":true,
370 },
371 // NOTE: click = mousedown + mouseup --> what about smartphone?!
372 on: {
373 mousedown: this.mousedown,
374 mousemove: this.mousemove,
375 mouseup: this.mouseup,
376 touchdown: this.mousedown,
377 touchmove: this.mousemove,
378 touchup: this.mouseup,
379 },
380 },
381 elementArray
382 );
383 },
384 created: function() {
385 const url = socketUrl;
386 const continuation = (localStorage.getItem("variant") === variant);
387 this.myid = continuation
388 ? localStorage.getItem("myid")
389 // random enough (TODO: function)
390 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
391 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
d35f20e4 392 const socketOpenListener = () => {
1d184b4c
BA
393 if (continuation)
394 {
dfb4afc1
BA
395 const fen = localStorage.getItem("fen");
396 const mycolor = localStorage.getItem("mycolor");
397 const oppid = localStorage.getItem("oppid");
398 const moves = JSON.parse(localStorage.getItem("moves"));
399 this.newGame("human", fen, mycolor, oppid, moves, true);
a29d9d6b 400 // Send ping to server (answer pong if opponent is connected)
ecf44502 401 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
1d184b4c 402 }
30ff6e04
BA
403 else if (localStorage.getItem("newgame") === variant)
404 {
405 // New game request has been cancelled on disconnect
186516b8 406 this.seek = true;
001344b9 407 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
30ff6e04 408 }
1d184b4c 409 };
d35f20e4 410 const socketMessageListener = msg => {
1d184b4c 411 const data = JSON.parse(msg.data);
f3802fcd 412 console.log("Receive message: " + data.code);
1d184b4c
BA
413 switch (data.code)
414 {
415 case "newgame": //opponent found
416 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
417 break;
418 case "newmove": //..he played!
419 this.play(data.move, "animate");
420 break;
f3802fcd 421 case "pong": //received if we sent a ping (game still alive on our side)
1d184b4c 422 this.oppConnected = true;
a29d9d6b 423 const L = this.vr.moves.length;
f3802fcd 424 // Send our "last state" informations to opponent
a29d9d6b
BA
425 this.conn.send(JSON.stringify({
426 code:"lastate",
f3802fcd 427 oppid:this.oppid,
a29d9d6b
BA
428 lastMove:L>0?this.vr.moves[L-1]:undefined,
429 movesCount:L,
430 }));
1d184b4c 431 break;
a29d9d6b
BA
432 case "lastate": //got opponent infos about last move (we might have resigned)
433 if (this.mode!="human" || this.oppid!=data.oppid)
434 {
435 // OK, we resigned
436 this.conn.send(JSON.stringify({
437 code:"lastate",
f3802fcd 438 oppid:this.oppid,
a29d9d6b
BA
439 lastMove:undefined,
440 movesCount:-1,
441 }));
442 }
443 else if (data.movesCount < 0)
444 {
445 // OK, he resigned
446 this.endGame(this.mycolor=="w"?"1-0":"0-1");
447 }
448 else if (data.movesCount < this.vr.moves.length)
449 {
450 // We must tell last move to opponent
451 const L = this.vr.moves.length;
452 this.conn.send(JSON.stringify({
453 code:"lastate",
f3802fcd 454 oppid:this.oppid,
a29d9d6b
BA
455 lastMove:this.vr.moves[L-1],
456 movesCount:L,
457 }));
458 }
459 else if (data.movesCount > this.vr.moves.length) //just got last move from him
460 this.play(data.lastMove, "animate");
ecf44502 461 break;
1d184b4c 462 case "resign": //..you won!
dfb4afc1 463 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 464 break;
f3802fcd 465 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
466 case "connect":
467 case "disconnect":
468 if (this.mode == "human" && this.oppid == data.id)
469 this.oppConnected = (data.code == "connect");
470 break;
471 }
472 };
d35f20e4 473 const socketCloseListener = () => {
d35f20e4
BA
474 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
475 this.conn.addEventListener('open', socketOpenListener);
476 this.conn.addEventListener('message', socketMessageListener);
477 this.conn.addEventListener('close', socketCloseListener);
478 };
479 this.conn.onopen = socketOpenListener;
480 this.conn.onmessage = socketMessageListener;
481 this.conn.onclose = socketCloseListener;
1d184b4c
BA
482 },
483 methods: {
01ca2adc
BA
484 download: function() {
485 let content = document.getElementById("pgn-game").innerHTML;
486 content = content.replace(/<br>/g, "\n");
487 // Prepare and trigger download link
488 let downloadAnchor = document.getElementById("download");
489 downloadAnchor.setAttribute("download", "game.pgn");
490 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
491 downloadAnchor.click();
492 },
dfb4afc1
BA
493 endGame: function(score) {
494 this.score = score;
ecf44502 495 let modalBox = document.getElementById("modal-eog");
186516b8 496 modalBox.checked = true;
3840e240
BA
497 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
498 setTimeout(() => { modalBox.checked = false; }, 2000);
1d184b4c
BA
499 if (this.mode == "human")
500 this.clearStorage();
3840e240 501 this.mode = "idle";
1d184b4c
BA
502 this.oppid = "";
503 },
f3802fcd
BA
504 getEndgameMessage: function(score) {
505 let eogMessage = "Unfinished";
506 switch (this.score)
507 {
508 case "1-0":
509 eogMessage = "White win";
510 break;
511 case "0-1":
512 eogMessage = "Black win";
513 break;
514 case "1/2":
515 eogMessage = "Draw";
516 break;
517 }
518 return eogMessage;
519 },
3ed62725
BA
520 toggleExpertMode: function() {
521 this.expert = !this.expert;
522 document.cookie = "expert=" + (this.expert ? "1" : "0");
523 },
1d184b4c
BA
524 resign: function() {
525 if (this.mode == "human" && this.oppConnected)
d35f20e4
BA
526 {
527 try {
528 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
529 } catch (INVALID_STATE_ERR) {
a29d9d6b 530 return; //socket is not ready (and not yet reconnected)
d35f20e4
BA
531 }
532 }
dfb4afc1 533 this.endGame(this.mycolor=="w"?"0-1":"1-0");
1d184b4c 534 },
762b7c9c
BA
535 setStorage: function() {
536 localStorage.setItem("myid", this.myid);
537 localStorage.setItem("variant", variant);
538 localStorage.setItem("mycolor", this.mycolor);
539 localStorage.setItem("oppid", this.oppid);
540 localStorage.setItem("fenStart", this.fenStart);
541 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
1d184b4c 542 localStorage.setItem("fen", this.vr.getFen());
762b7c9c
BA
543 },
544 updateStorage: function() {
dfb4afc1 545 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
762b7c9c 546 localStorage.setItem("fen", this.vr.getFen());
1d184b4c
BA
547 },
548 clearStorage: function() {
549 delete localStorage["variant"];
550 delete localStorage["myid"];
551 delete localStorage["mycolor"];
552 delete localStorage["oppid"];
762b7c9c 553 delete localStorage["fenStart"];
1d184b4c 554 delete localStorage["fen"];
dfb4afc1 555 delete localStorage["moves"];
1d184b4c 556 },
f3802fcd
BA
557 clickGameSeek: function() {
558 if (this.mode == "human")
559 return; //no newgame while playing
560 if (this.seek)
01a135e2 561 {
f3802fcd 562 delete localStorage["newgame"]; //cancel game seek
01a135e2
BA
563 this.seek = false;
564 }
f3802fcd 565 else
f3802fcd 566 this.newGame("human");
f3802fcd
BA
567 },
568 clickComputerGame: function() {
569 if (this.mode == "human")
570 return; //no newgame while playing
571 this.newGame("computer");
572 },
dfb4afc1 573 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
1d184b4c
BA
574 const fen = fenInit || VariantRules.GenRandInitFen();
575 console.log(fen); //DEBUG
dfb4afc1 576 this.score = "*";
1d184b4c
BA
577 if (mode=="human" && !oppId)
578 {
cd3174c5
BA
579 const storageVariant = localStorage.getItem("variant");
580 if (!!storageVariant && storageVariant !== variant)
581 {
cd3174c5
BA
582 alert("Finish your " + storageVariant + " game first!");
583 return;
584 }
1d184b4c 585 // Send game request and wait..
01a135e2
BA
586 localStorage["newgame"] = variant;
587 this.seek = true;
1d184b4c 588 this.clearStorage(); //in case of
d35f20e4
BA
589 try {
590 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
591 } catch (INVALID_STATE_ERR) {
592 return; //nothing achieved
593 }
f3802fcd 594 if (continuation !== "reconnect") //TODO: bad HACK...
a68d899d 595 {
ecf44502 596 let modalBox = document.getElementById("modal-newgame");
a68d899d
BA
597 modalBox.checked = true;
598 setTimeout(() => { modalBox.checked = false; }, 2000);
599 }
1d184b4c
BA
600 return;
601 }
dfb4afc1 602 this.vr = new VariantRules(fen, moves || []);
3840e240 603 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1d184b4c 604 this.mode = mode;
1fcaa356 605 this.incheck = []; //in case of
762b7c9c
BA
606 this.fenStart = continuation
607 ? localStorage.getItem("fenStart")
608 : fen.split(" ")[0]; //Only the position matters
1d184b4c
BA
609 if (mode=="human")
610 {
611 // Opponent found!
612 if (!continuation)
613 {
ecf44502 614 // Not playing sound on game continuation:
ea8417ff 615 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
ecf44502 616 document.getElementById("modal-newgame").checked = false;
1d184b4c
BA
617 }
618 this.oppid = oppId;
619 this.oppConnected = true;
620 this.mycolor = color;
186516b8 621 this.seek = false;
e64a4eff
BA
622 if (!!moves && moves.length > 0) //imply continuation
623 {
e64a4eff 624 const lastMove = moves[moves.length-1];
cd4cad04 625 this.vr.undo(lastMove);
46302e64 626 this.incheck = this.vr.getCheckSquares(lastMove);
e64a4eff
BA
627 this.vr.play(lastMove, "ingame");
628 }
186516b8 629 delete localStorage["newgame"];
762b7c9c 630 this.setStorage(); //in case of interruptions
1d184b4c
BA
631 }
632 else //against computer
633 {
634 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
635 if (this.mycolor == 'b')
636 setTimeout(this.playComputerMove, 500);
637 }
638 },
639 playComputerMove: function() {
46302e64 640 const compMove = this.vr.getComputerMove();
1d184b4c
BA
641 // HACK: avoid selecting elements before they appear on page:
642 setTimeout(() => this.play(compMove, "animate"), 500);
643 },
644 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
645 getSquareId: function(o) {
646 // NOTE: a separator is required to allow any size of board
647 return "sq-" + o.x + "-" + o.y;
648 },
649 // Inverse function
650 getSquareFromId: function(id) {
651 let idParts = id.split('-');
652 return [parseInt(idParts[1]), parseInt(idParts[2])];
653 },
654 mousedown: function(e) {
655 e = e || window.event;
656 e.preventDefault(); //disable native drag & drop
657 if (!this.selectedPiece && e.target.classList.contains("piece"))
658 {
659 // Next few lines to center the piece on mouse cursor
660 let rect = e.target.parentNode.getBoundingClientRect();
661 this.start = {
662 x: rect.x + rect.width/2,
663 y: rect.y + rect.width/2,
664 id: e.target.parentNode.id
665 };
666 this.selectedPiece = e.target.cloneNode();
667 this.selectedPiece.style.position = "absolute";
668 this.selectedPiece.style.top = 0;
669 this.selectedPiece.style.display = "inline-block";
670 this.selectedPiece.style.zIndex = 3000;
671 let startSquare = this.getSquareFromId(e.target.parentNode.id);
7d6b0773 672 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
1d184b4c
BA
673 ? this.vr.getPossibleMovesFrom(startSquare)
674 : [];
675 e.target.parentNode.appendChild(this.selectedPiece);
676 }
677 },
678 mousemove: function(e) {
679 if (!this.selectedPiece)
680 return;
681 e = e || window.event;
682 // If there is an active element, move it around
683 if (!!this.selectedPiece)
684 {
685 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
686 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
687 }
688 },
689 mouseup: function(e) {
690 if (!this.selectedPiece)
691 return;
692 e = e || window.event;
693 // Read drop target (or parentElement, parentNode... if type == "img")
694 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
695 let landing = document.elementFromPoint(e.clientX, e.clientY);
696 this.selectedPiece.style.zIndex = 3000;
697 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
698 landing = landing.parentNode;
699 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
700 return;
701 // OK: process move attempt
702 let endSquare = this.getSquareFromId(landing.id);
703 let moves = this.findMatchingMoves(endSquare);
704 this.possibleMoves = [];
705 if (moves.length > 1)
706 this.choices = moves;
707 else if (moves.length==1)
708 this.play(moves[0]);
709 // Else: impossible move
710 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
711 delete this.selectedPiece;
712 this.selectedPiece = null;
713 },
714 findMatchingMoves: function(endSquare) {
715 // Run through moves list and return the matching set (if promotions...)
716 let moves = [];
717 this.possibleMoves.forEach(function(m) {
718 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
719 moves.push(m);
720 });
721 return moves;
722 },
723 animateMove: function(move) {
724 let startSquare = document.getElementById(this.getSquareId(move.start));
725 let endSquare = document.getElementById(this.getSquareId(move.end));
726 let rectStart = startSquare.getBoundingClientRect();
727 let rectEnd = endSquare.getBoundingClientRect();
728 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
729 let movingPiece = document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
730 // HACK for animation (otherwise with positive translate, image slides "under background"...)
731 // Possible improvement: just alter squares on the piece's way...
732 squares = document.getElementsByClassName("board");
733 for (let i=0; i<squares.length; i++)
734 {
735 let square = squares.item(i);
736 if (square.id != this.getSquareId(move.start))
737 square.style.zIndex = "-1";
738 }
739 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
740 movingPiece.style.transitionDuration = "0.2s";
741 movingPiece.style.zIndex = "3000";
742 setTimeout( () => {
743 for (let i=0; i<squares.length; i++)
744 squares.item(i).style.zIndex = "auto";
745 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
746 this.play(move);
747 }, 200);
748 },
749 play: function(move, programmatic) {
750 if (!!programmatic) //computer or human opponent
751 {
752 this.animateMove(move);
753 return;
754 }
46302e64 755 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
1d184b4c
BA
756 // Not programmatic, or animation is over
757 if (this.mode == "human" && this.vr.turn == this.mycolor)
a29d9d6b 758 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
ea8417ff 759 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
1d184b4c
BA
760 this.vr.play(move, "ingame");
761 if (this.mode == "human")
762 this.updateStorage(); //after our moves and opponent moves
46302e64 763 const eog = this.vr.checkGameOver();
1d184b4c
BA
764 if (eog != "*")
765 this.endGame(eog);
766 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
767 setTimeout(this.playComputerMove, 500);
768 },
769 },
770})