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