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