Add a small silent when landing on variant page to allow newgame sound when unfocused
[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();
92ff5bae
BA
396 if (!continuation)
397 {
398 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
399 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {});
400 }
1d184b4c 401 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
d35f20e4 402 const socketOpenListener = () => {
1d184b4c
BA
403 if (continuation)
404 {
dfb4afc1
BA
405 const fen = localStorage.getItem("fen");
406 const mycolor = localStorage.getItem("mycolor");
407 const oppid = localStorage.getItem("oppid");
408 const moves = JSON.parse(localStorage.getItem("moves"));
409 this.newGame("human", fen, mycolor, oppid, moves, true);
a29d9d6b 410 // Send ping to server (answer pong if opponent is connected)
ecf44502 411 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
1d184b4c 412 }
30ff6e04
BA
413 else if (localStorage.getItem("newgame") === variant)
414 {
415 // New game request has been cancelled on disconnect
186516b8 416 this.seek = true;
001344b9 417 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
30ff6e04 418 }
1d184b4c 419 };
d35f20e4 420 const socketMessageListener = msg => {
1d184b4c
BA
421 const data = JSON.parse(msg.data);
422 switch (data.code)
423 {
424 case "newgame": //opponent found
425 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
426 break;
427 case "newmove": //..he played!
428 this.play(data.move, "animate");
429 break;
f3802fcd 430 case "pong": //received if we sent a ping (game still alive on our side)
1d184b4c 431 this.oppConnected = true;
a29d9d6b 432 const L = this.vr.moves.length;
f3802fcd 433 // Send our "last state" informations to opponent
a29d9d6b
BA
434 this.conn.send(JSON.stringify({
435 code:"lastate",
f3802fcd 436 oppid:this.oppid,
a29d9d6b
BA
437 lastMove:L>0?this.vr.moves[L-1]:undefined,
438 movesCount:L,
439 }));
1d184b4c 440 break;
a29d9d6b
BA
441 case "lastate": //got opponent infos about last move (we might have resigned)
442 if (this.mode!="human" || this.oppid!=data.oppid)
443 {
444 // OK, we resigned
445 this.conn.send(JSON.stringify({
446 code:"lastate",
f3802fcd 447 oppid:this.oppid,
a29d9d6b
BA
448 lastMove:undefined,
449 movesCount:-1,
450 }));
451 }
452 else if (data.movesCount < 0)
453 {
454 // OK, he resigned
455 this.endGame(this.mycolor=="w"?"1-0":"0-1");
456 }
457 else if (data.movesCount < this.vr.moves.length)
458 {
459 // We must tell last move to opponent
460 const L = this.vr.moves.length;
461 this.conn.send(JSON.stringify({
462 code:"lastate",
f3802fcd 463 oppid:this.oppid,
a29d9d6b
BA
464 lastMove:this.vr.moves[L-1],
465 movesCount:L,
466 }));
467 }
468 else if (data.movesCount > this.vr.moves.length) //just got last move from him
469 this.play(data.lastMove, "animate");
ecf44502 470 break;
1d184b4c 471 case "resign": //..you won!
dfb4afc1 472 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 473 break;
f3802fcd 474 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
475 case "connect":
476 case "disconnect":
477 if (this.mode == "human" && this.oppid == data.id)
478 this.oppConnected = (data.code == "connect");
479 break;
480 }
481 };
d35f20e4 482 const socketCloseListener = () => {
d35f20e4
BA
483 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
484 this.conn.addEventListener('open', socketOpenListener);
485 this.conn.addEventListener('message', socketMessageListener);
486 this.conn.addEventListener('close', socketCloseListener);
487 };
488 this.conn.onopen = socketOpenListener;
489 this.conn.onmessage = socketMessageListener;
490 this.conn.onclose = socketCloseListener;
1d184b4c
BA
491 },
492 methods: {
01ca2adc
BA
493 download: function() {
494 let content = document.getElementById("pgn-game").innerHTML;
495 content = content.replace(/<br>/g, "\n");
496 // Prepare and trigger download link
497 let downloadAnchor = document.getElementById("download");
498 downloadAnchor.setAttribute("download", "game.pgn");
499 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
500 downloadAnchor.click();
501 },
dfb4afc1
BA
502 endGame: function(score) {
503 this.score = score;
ecf44502 504 let modalBox = document.getElementById("modal-eog");
186516b8 505 modalBox.checked = true;
204e289b 506 // Variants may have special PGN structure (so next function isn't defined here)
3840e240
BA
507 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
508 setTimeout(() => { modalBox.checked = false; }, 2000);
1d184b4c
BA
509 if (this.mode == "human")
510 this.clearStorage();
3840e240 511 this.mode = "idle";
1d184b4c
BA
512 this.oppid = "";
513 },
f3802fcd
BA
514 getEndgameMessage: function(score) {
515 let eogMessage = "Unfinished";
516 switch (this.score)
517 {
518 case "1-0":
519 eogMessage = "White win";
520 break;
521 case "0-1":
522 eogMessage = "Black win";
523 break;
524 case "1/2":
525 eogMessage = "Draw";
526 break;
527 }
528 return eogMessage;
529 },
3ed62725
BA
530 toggleExpertMode: function() {
531 this.expert = !this.expert;
532 document.cookie = "expert=" + (this.expert ? "1" : "0");
533 },
1d184b4c
BA
534 resign: function() {
535 if (this.mode == "human" && this.oppConnected)
d35f20e4
BA
536 {
537 try {
538 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
539 } catch (INVALID_STATE_ERR) {
a29d9d6b 540 return; //socket is not ready (and not yet reconnected)
d35f20e4
BA
541 }
542 }
dfb4afc1 543 this.endGame(this.mycolor=="w"?"0-1":"1-0");
1d184b4c 544 },
762b7c9c
BA
545 setStorage: function() {
546 localStorage.setItem("myid", this.myid);
547 localStorage.setItem("variant", variant);
548 localStorage.setItem("mycolor", this.mycolor);
549 localStorage.setItem("oppid", this.oppid);
550 localStorage.setItem("fenStart", this.fenStart);
551 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
1d184b4c 552 localStorage.setItem("fen", this.vr.getFen());
762b7c9c
BA
553 },
554 updateStorage: function() {
dfb4afc1 555 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
762b7c9c 556 localStorage.setItem("fen", this.vr.getFen());
1d184b4c
BA
557 },
558 clearStorage: function() {
559 delete localStorage["variant"];
560 delete localStorage["myid"];
561 delete localStorage["mycolor"];
562 delete localStorage["oppid"];
762b7c9c 563 delete localStorage["fenStart"];
1d184b4c 564 delete localStorage["fen"];
dfb4afc1 565 delete localStorage["moves"];
1d184b4c 566 },
f3802fcd
BA
567 clickGameSeek: function() {
568 if (this.mode == "human")
569 return; //no newgame while playing
570 if (this.seek)
01a135e2 571 {
f3802fcd 572 delete localStorage["newgame"]; //cancel game seek
01a135e2
BA
573 this.seek = false;
574 }
f3802fcd 575 else
f3802fcd 576 this.newGame("human");
f3802fcd
BA
577 },
578 clickComputerGame: function() {
579 if (this.mode == "human")
580 return; //no newgame while playing
581 this.newGame("computer");
582 },
dfb4afc1 583 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
4b353936 584 //const fen = "1n2T1n0/p2pO2p/1s1k1s2/8/3S2p1/2U2cO1/P3PuPP/3K1BR1 0100";
55eb331d 585 const fen = fenInit || VariantRules.GenRandInitFen();
1d184b4c 586 console.log(fen); //DEBUG
dfb4afc1 587 this.score = "*";
1d184b4c
BA
588 if (mode=="human" && !oppId)
589 {
cd3174c5
BA
590 const storageVariant = localStorage.getItem("variant");
591 if (!!storageVariant && storageVariant !== variant)
592 {
cd3174c5
BA
593 alert("Finish your " + storageVariant + " game first!");
594 return;
595 }
1d184b4c 596 // Send game request and wait..
01a135e2
BA
597 localStorage["newgame"] = variant;
598 this.seek = true;
1d184b4c 599 this.clearStorage(); //in case of
d35f20e4
BA
600 try {
601 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
602 } catch (INVALID_STATE_ERR) {
603 return; //nothing achieved
604 }
f3802fcd 605 if (continuation !== "reconnect") //TODO: bad HACK...
a68d899d 606 {
ecf44502 607 let modalBox = document.getElementById("modal-newgame");
a68d899d
BA
608 modalBox.checked = true;
609 setTimeout(() => { modalBox.checked = false; }, 2000);
610 }
1d184b4c
BA
611 return;
612 }
dfb4afc1 613 this.vr = new VariantRules(fen, moves || []);
3840e240 614 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1d184b4c 615 this.mode = mode;
1fcaa356 616 this.incheck = []; //in case of
762b7c9c
BA
617 this.fenStart = continuation
618 ? localStorage.getItem("fenStart")
619 : fen.split(" ")[0]; //Only the position matters
1d184b4c
BA
620 if (mode=="human")
621 {
622 // Opponent found!
623 if (!continuation)
624 {
ecf44502 625 // Not playing sound on game continuation:
ea8417ff 626 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
ecf44502 627 document.getElementById("modal-newgame").checked = false;
1d184b4c
BA
628 }
629 this.oppid = oppId;
630 this.oppConnected = true;
631 this.mycolor = color;
186516b8 632 this.seek = false;
e64a4eff
BA
633 if (!!moves && moves.length > 0) //imply continuation
634 {
e64a4eff 635 const lastMove = moves[moves.length-1];
cd4cad04 636 this.vr.undo(lastMove);
46302e64 637 this.incheck = this.vr.getCheckSquares(lastMove);
e64a4eff
BA
638 this.vr.play(lastMove, "ingame");
639 }
186516b8 640 delete localStorage["newgame"];
762b7c9c 641 this.setStorage(); //in case of interruptions
1d184b4c
BA
642 }
643 else //against computer
644 {
f3c10e18 645 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
1d184b4c
BA
646 if (this.mycolor == 'b')
647 setTimeout(this.playComputerMove, 500);
648 }
649 },
650 playComputerMove: function() {
4b353936 651 const timeStart = Date.now();
46302e64 652 const compMove = this.vr.getComputerMove();
4b353936
BA
653 // (first move) HACK: avoid selecting elements before they appear on page:
654 const delay = Math.max(500-(Date.now()-timeStart), 0);
655 setTimeout(() => this.play(compMove, "animate"), delay);
1d184b4c
BA
656 },
657 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
658 getSquareId: function(o) {
659 // NOTE: a separator is required to allow any size of board
660 return "sq-" + o.x + "-" + o.y;
661 },
662 // Inverse function
663 getSquareFromId: function(id) {
664 let idParts = id.split('-');
665 return [parseInt(idParts[1]), parseInt(idParts[2])];
666 },
667 mousedown: function(e) {
668 e = e || window.event;
669 e.preventDefault(); //disable native drag & drop
670 if (!this.selectedPiece && e.target.classList.contains("piece"))
671 {
672 // Next few lines to center the piece on mouse cursor
673 let rect = e.target.parentNode.getBoundingClientRect();
674 this.start = {
675 x: rect.x + rect.width/2,
676 y: rect.y + rect.width/2,
677 id: e.target.parentNode.id
678 };
679 this.selectedPiece = e.target.cloneNode();
680 this.selectedPiece.style.position = "absolute";
681 this.selectedPiece.style.top = 0;
682 this.selectedPiece.style.display = "inline-block";
683 this.selectedPiece.style.zIndex = 3000;
684 let startSquare = this.getSquareFromId(e.target.parentNode.id);
55eb331d 685 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
1d184b4c
BA
686 ? this.vr.getPossibleMovesFrom(startSquare)
687 : [];
688 e.target.parentNode.appendChild(this.selectedPiece);
689 }
690 },
691 mousemove: function(e) {
692 if (!this.selectedPiece)
693 return;
694 e = e || window.event;
695 // If there is an active element, move it around
696 if (!!this.selectedPiece)
697 {
698 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
699 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
700 }
701 },
702 mouseup: function(e) {
703 if (!this.selectedPiece)
704 return;
705 e = e || window.event;
706 // Read drop target (or parentElement, parentNode... if type == "img")
707 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
708 let landing = document.elementFromPoint(e.clientX, e.clientY);
709 this.selectedPiece.style.zIndex = 3000;
710 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
711 landing = landing.parentNode;
712 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
713 return;
714 // OK: process move attempt
715 let endSquare = this.getSquareFromId(landing.id);
716 let moves = this.findMatchingMoves(endSquare);
717 this.possibleMoves = [];
718 if (moves.length > 1)
719 this.choices = moves;
720 else if (moves.length==1)
721 this.play(moves[0]);
722 // Else: impossible move
723 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
724 delete this.selectedPiece;
725 this.selectedPiece = null;
726 },
727 findMatchingMoves: function(endSquare) {
728 // Run through moves list and return the matching set (if promotions...)
729 let moves = [];
730 this.possibleMoves.forEach(function(m) {
731 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
732 moves.push(m);
733 });
734 return moves;
735 },
736 animateMove: function(move) {
737 let startSquare = document.getElementById(this.getSquareId(move.start));
738 let endSquare = document.getElementById(this.getSquareId(move.end));
739 let rectStart = startSquare.getBoundingClientRect();
740 let rectEnd = endSquare.getBoundingClientRect();
741 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
92ff5bae
BA
742 let movingPiece =
743 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
744 // HACK for animation (with positive translate, image slides "under background"...)
1d184b4c
BA
745 // Possible improvement: just alter squares on the piece's way...
746 squares = document.getElementsByClassName("board");
747 for (let i=0; i<squares.length; i++)
748 {
749 let square = squares.item(i);
750 if (square.id != this.getSquareId(move.start))
751 square.style.zIndex = "-1";
752 }
753 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
754 movingPiece.style.transitionDuration = "0.2s";
755 movingPiece.style.zIndex = "3000";
756 setTimeout( () => {
757 for (let i=0; i<squares.length; i++)
758 squares.item(i).style.zIndex = "auto";
759 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
760 this.play(move);
761 }, 200);
762 },
763 play: function(move, programmatic) {
764 if (!!programmatic) //computer or human opponent
765 {
766 this.animateMove(move);
767 return;
768 }
46302e64 769 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
1d184b4c
BA
770 // Not programmatic, or animation is over
771 if (this.mode == "human" && this.vr.turn == this.mycolor)
a29d9d6b 772 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
ea8417ff 773 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
1d184b4c
BA
774 this.vr.play(move, "ingame");
775 if (this.mode == "human")
776 this.updateStorage(); //after our moves and opponent moves
46302e64 777 const eog = this.vr.checkGameOver();
1d184b4c
BA
778 if (eog != "*")
779 this.endGame(eog);
780 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
781 setTimeout(this.playComputerMove, 500);
782 },
783 },
784})