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