Play computer move in webworker to not freeze interface
[vchess.git] / public / javascripts / components / game.js
1 // Game logic on a variant page
2 Vue.component('my-game', {
3 props: ["problem"],
4 data: function() {
5 return {
6 vr: null, //object to check moves, store them, FEN..
7 mycolor: "w",
8 possibleMoves: [], //filled after each valid click/dragstart
9 choices: [], //promotion pieces, or checkered captures... (as moves)
10 start: {}, //pixels coordinates + id of starting square (click or drag)
11 selectedPiece: null, //moving piece (or clicked piece)
12 conn: null, //socket connection
13 score: "*", //'*' means 'unfinished'
14 mode: "idle", //human, friend, computer or idle (when not playing)
15 oppid: "", //opponent ID in case of HH game
16 oppConnected: false,
17 seek: false,
18 fenStart: "",
19 incheck: [],
20 pgnTxt: "",
21 hints: (getCookie("hints") === "1" ? true : false),
22 color: getCookie("color", "lichess"), //lichess, chesscom or chesstempo
23 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
24 sound: parseInt(getCookie("sound", "2")),
25 // Web worker to play computer moves without freezing interface:
26 compWorker: new Worker('/javascripts/playCompMove.js'),
27 timeStart: undefined, //time when computer starts thinking
28 };
29 },
30 watch: {
31 problem: function(p, pp) {
32 // 'problem' prop changed: update board state
33 this.newGame("problem", p.fen, V.ParseFen(p.fen).turn);
34 },
35 },
36 render(h) {
37 const [sizeX,sizeY] = [V.size.x,V.size.y];
38 const smallScreen = (window.innerWidth <= 420);
39 // Precompute hints squares to facilitate rendering
40 let hintSquares = doubleArray(sizeX, sizeY, false);
41 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
42 // Also precompute in-check squares
43 let incheckSq = doubleArray(sizeX, sizeY, false);
44 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
45 let elementArray = [];
46 let actionArray = [];
47 actionArray.push(
48 h('button',
49 {
50 on: { click: this.clickGameSeek },
51 attrs: { "aria-label": 'New online game' },
52 'class': {
53 "tooltip": true,
54 "bottom": true, //display below
55 "seek": this.seek,
56 "playing": this.mode == "human",
57 "small": smallScreen,
58 },
59 },
60 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
61 );
62 if (["idle","computer"].includes(this.mode))
63 {
64 actionArray.push(
65 h('button',
66 {
67 on: { click: this.clickComputerGame },
68 attrs: { "aria-label": 'New game VS computer' },
69 'class': {
70 "tooltip":true,
71 "bottom": true,
72 "playing": this.mode == "computer",
73 "small": smallScreen,
74 },
75 },
76 [h('i', { 'class': { "material-icons": true } }, "computer")])
77 );
78 }
79 if (["idle","friend"].includes(this.mode))
80 {
81 actionArray.push(
82 h('button',
83 {
84 on: { click: this.clickFriendGame },
85 attrs: { "aria-label": 'New IRL game' },
86 'class': {
87 "tooltip":true,
88 "bottom": true,
89 "playing": this.mode == "friend",
90 "small": smallScreen,
91 },
92 },
93 [h('i', { 'class': { "material-icons": true } }, "people")])
94 );
95 }
96 if (!!this.vr)
97 {
98 const square00 = document.getElementById("sq-0-0");
99 const squareWidth = !!square00
100 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
101 : 0;
102 const settingsBtnElt = document.getElementById("settingsBtn");
103 const indicWidth = !!settingsBtnElt //-2 for border:
104 ? parseFloat(window.getComputedStyle(settingsBtnElt).height.slice(0,-2)) - 2
105 : (smallScreen ? 31 : 37);
106 if (this.mode == "human")
107 {
108 const connectedIndic = h(
109 'div',
110 {
111 "class": {
112 "topindicator": true,
113 "indic-left": true,
114 "connected": this.oppConnected,
115 "disconnected": !this.oppConnected,
116 },
117 style: {
118 "width": indicWidth + "px",
119 "height": indicWidth + "px",
120 },
121 }
122 );
123 elementArray.push(connectedIndic);
124 }
125 const turnIndic = h(
126 'div',
127 {
128 "class": {
129 "topindicator": true,
130 "indic-right": true,
131 "white-turn": this.vr.turn=="w",
132 "black-turn": this.vr.turn=="b",
133 },
134 style: {
135 "width": indicWidth + "px",
136 "height": indicWidth + "px",
137 },
138 }
139 );
140 elementArray.push(turnIndic);
141 const settingsBtn = h(
142 'button',
143 {
144 on: { click: this.showSettings },
145 attrs: {
146 "aria-label": 'Settings',
147 "id": "settingsBtn",
148 },
149 'class': {
150 "tooltip": true,
151 "topindicator": true,
152 "indic-left": true,
153 "settings-btn": !smallScreen,
154 "settings-btn-small": smallScreen,
155 },
156 },
157 [h('i', { 'class': { "material-icons": true } }, "settings")]
158 );
159 elementArray.push(settingsBtn);
160 if (this.mode == "problem")
161 {
162 // Show problem instructions
163 elementArray.push(
164 h('div',
165 {
166 attrs: { id: "instructions-div" },
167 "class": { "section-content": true },
168 },
169 [
170 h('p',
171 {
172 attrs: { id: "problem-instructions" },
173 domProps: { innerHTML: this.problem.instructions }
174 }
175 )
176 ]
177 )
178 );
179 }
180 const choices = h('div',
181 {
182 attrs: { "id": "choices" },
183 'class': { 'row': true },
184 style: {
185 "display": this.choices.length>0?"block":"none",
186 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
187 "width": (this.choices.length * squareWidth) + "px",
188 "height": squareWidth + "px",
189 },
190 },
191 this.choices.map( m => { //a "choice" is a move
192 return h('div',
193 {
194 'class': {
195 'board': true,
196 ['board'+sizeY]: true,
197 },
198 style: {
199 'width': (100/this.choices.length) + "%",
200 'padding-bottom': (100/this.choices.length) + "%",
201 },
202 },
203 [h('img',
204 {
205 attrs: { "src": '/images/pieces/' +
206 VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
207 'class': { 'choice-piece': true },
208 on: { "click": e => { this.play(m); this.choices=[]; } },
209 })
210 ]
211 );
212 })
213 );
214 // Create board element (+ reserves if needed by variant or mode)
215 const lm = this.vr.lastMove;
216 const showLight = this.hints &&
217 (this.mode!="idle" || this.cursor==this.vr.moves.length);
218 const gameDiv = h('div',
219 {
220 'class': { 'game': true },
221 },
222 [_.range(sizeX).map(i => {
223 let ci = this.mycolor=='w' ? i : sizeX-i-1;
224 return h(
225 'div',
226 {
227 'class': {
228 'row': true,
229 },
230 style: { 'opacity': this.choices.length>0?"0.5":"1" },
231 },
232 _.range(sizeY).map(j => {
233 let cj = this.mycolor=='w' ? j : sizeY-j-1;
234 let elems = [];
235 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
236 {
237 elems.push(
238 h(
239 'img',
240 {
241 'class': {
242 'piece': true,
243 'ghost': !!this.selectedPiece
244 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
245 },
246 attrs: {
247 src: "/images/pieces/" +
248 VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
249 },
250 }
251 )
252 );
253 }
254 if (this.hints && hintSquares[ci][cj])
255 {
256 elems.push(
257 h(
258 'img',
259 {
260 'class': {
261 'mark-square': true,
262 },
263 attrs: {
264 src: "/images/mark.svg",
265 },
266 }
267 )
268 );
269 }
270 return h(
271 'div',
272 {
273 'class': {
274 'board': true,
275 ['board'+sizeY]: true,
276 'light-square': (i+j)%2==0,
277 'dark-square': (i+j)%2==1,
278 [this.color]: true,
279 'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
280 'incheck': showLight && incheckSq[ci][cj],
281 },
282 attrs: {
283 id: this.getSquareId({x:ci,y:cj}),
284 },
285 },
286 elems
287 );
288 })
289 );
290 }), choices]
291 );
292 if (this.mode != "idle")
293 {
294 actionArray.push(
295 h('button',
296 {
297 on: { click: this.resign },
298 attrs: { "aria-label": 'Resign' },
299 'class': {
300 "tooltip":true,
301 "bottom": true,
302 "small": smallScreen,
303 },
304 },
305 [h('i', { 'class': { "material-icons": true } }, "flag")])
306 );
307 }
308 else if (this.vr.moves.length > 0)
309 {
310 // A game finished, and another is not started yet: allow navigation
311 actionArray = actionArray.concat([
312 h('button',
313 {
314 on: { click: e => this.undo() },
315 attrs: { "aria-label": 'Undo' },
316 "class": {
317 "small": smallScreen,
318 "marginleft": true,
319 },
320 },
321 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
322 h('button',
323 {
324 on: { click: e => this.play() },
325 attrs: { "aria-label": 'Play' },
326 "class": { "small": smallScreen },
327 },
328 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
329 ]
330 );
331 }
332 if (["friend","problem"].includes(this.mode))
333 {
334 actionArray = actionArray.concat(
335 [
336 h('button',
337 {
338 on: { click: this.undoInGame },
339 attrs: { "aria-label": 'Undo' },
340 "class": {
341 "small": smallScreen,
342 "marginleft": true,
343 },
344 },
345 [h('i', { 'class': { "material-icons": true } }, "undo")]
346 ),
347 h('button',
348 {
349 on: { click: () => { this.mycolor = this.vr.getOppCol(this.mycolor) } },
350 attrs: { "aria-label": 'Flip' },
351 "class": { "small": smallScreen },
352 },
353 [h('i', { 'class': { "material-icons": true } }, "cached")]
354 ),
355 ]);
356 }
357 elementArray.push(gameDiv);
358 if (!!this.vr.reserve)
359 {
360 const shiftIdx = (this.mycolor=="w" ? 0 : 1);
361 let myReservePiecesArray = [];
362 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
363 {
364 myReservePiecesArray.push(h('div',
365 {
366 'class': {'board':true, ['board'+sizeY]:true},
367 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
368 },
369 [
370 h('img',
371 {
372 'class': {"piece":true},
373 attrs: {
374 "src": "/images/pieces/" +
375 this.vr.getReservePpath(this.mycolor,i) + ".svg",
376 }
377 }),
378 h('sup',
379 {"class": { "reserve-count": true } },
380 [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ]
381 )
382 ]));
383 }
384 let oppReservePiecesArray = [];
385 const oppCol = this.vr.getOppCol(this.mycolor);
386 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
387 {
388 oppReservePiecesArray.push(h('div',
389 {
390 'class': {'board':true, ['board'+sizeY]:true},
391 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
392 },
393 [
394 h('img',
395 {
396 'class': {"piece":true},
397 attrs: {
398 "src": "/images/pieces/" +
399 this.vr.getReservePpath(oppCol,i) + ".svg",
400 }
401 }),
402 h('sup',
403 {"class": { "reserve-count": true } },
404 [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ]
405 )
406 ]));
407 }
408 let reserves = h('div',
409 {
410 'class':{
411 'game': true,
412 "reserve-div": true,
413 },
414 },
415 [
416 h('div',
417 {
418 'class': {
419 'row': true,
420 "reserve-row-1": true,
421 },
422 },
423 myReservePiecesArray
424 ),
425 h('div',
426 { 'class': { 'row': true }},
427 oppReservePiecesArray
428 )
429 ]
430 );
431 elementArray.push(reserves);
432 }
433 const modalEog = [
434 h('input',
435 {
436 attrs: { "id": "modal-eog", type: "checkbox" },
437 "class": { "modal": true },
438 }),
439 h('div',
440 {
441 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
442 },
443 [
444 h('div',
445 {
446 "class": { "card": true, "smallpad": true },
447 },
448 [
449 h('label',
450 {
451 attrs: { "for": "modal-eog" },
452 "class": { "modal-close": true },
453 }
454 ),
455 h('h3',
456 {
457 attrs: { "id": "eogMessage" },
458 "class": { "section": true },
459 domProps: { innerHTML: this.endgameMessage },
460 }
461 )
462 ]
463 )
464 ]
465 )
466 ];
467 elementArray = elementArray.concat(modalEog);
468 }
469 // NOTE: this modal could be in Pug view (no usage of Vue functions or variables)
470 const modalNewgame = [
471 h('input',
472 {
473 attrs: { "id": "modal-newgame", type: "checkbox" },
474 "class": { "modal": true },
475 }),
476 h('div',
477 {
478 attrs: { "role": "dialog", "aria-labelledby": "newGameTxt" },
479 },
480 [
481 h('div',
482 {
483 "class": { "card": true, "smallpad": true },
484 },
485 [
486 h('label',
487 {
488 attrs: { "id": "close-newgame", "for": "modal-newgame" },
489 "class": { "modal-close": true },
490 }
491 ),
492 h('h3',
493 {
494 attrs: { "id": "newGameTxt" },
495 "class": { "section": true },
496 domProps: { innerHTML: "New game" },
497 }
498 ),
499 h('p',
500 {
501 "class": { "section": true },
502 domProps: { innerHTML: "Waiting for opponent..." },
503 }
504 )
505 ]
506 )
507 ]
508 )
509 ];
510 elementArray = elementArray.concat(modalNewgame);
511 const modalFenEdit = [
512 h('input',
513 {
514 attrs: { "id": "modal-fenedit", type: "checkbox" },
515 "class": { "modal": true },
516 }),
517 h('div',
518 {
519 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
520 },
521 [
522 h('div',
523 {
524 "class": { "card": true, "smallpad": true },
525 },
526 [
527 h('label',
528 {
529 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
530 "class": { "modal-close": true },
531 }
532 ),
533 h('h3',
534 {
535 attrs: { "id": "titleFenedit" },
536 "class": { "section": true },
537 domProps: { innerHTML: "Position + flags (FEN):" },
538 }
539 ),
540 h('input',
541 {
542 attrs: {
543 "id": "input-fen",
544 type: "text",
545 value: VariantRules.GenRandInitFen(),
546 },
547 }
548 ),
549 h('button',
550 {
551 on: { click:
552 () => {
553 const fen = document.getElementById("input-fen").value;
554 document.getElementById("modal-fenedit").checked = false;
555 this.newGame("friend", fen);
556 }
557 },
558 domProps: { innerHTML: "Ok" },
559 }
560 ),
561 h('button',
562 {
563 on: { click:
564 () => {
565 document.getElementById("input-fen").value =
566 VariantRules.GenRandInitFen();
567 }
568 },
569 domProps: { innerHTML: "Random" },
570 }
571 ),
572 ]
573 )
574 ]
575 )
576 ];
577 elementArray = elementArray.concat(modalFenEdit);
578 const modalSettings = [
579 h('input',
580 {
581 attrs: { "id": "modal-settings", type: "checkbox" },
582 "class": { "modal": true },
583 }),
584 h('div',
585 {
586 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
587 },
588 [
589 h('div',
590 {
591 "class": { "card": true, "smallpad": true },
592 },
593 [
594 h('label',
595 {
596 attrs: { "id": "close-settings", "for": "modal-settings" },
597 "class": { "modal-close": true },
598 }
599 ),
600 h('h3',
601 {
602 attrs: { "id": "settingsTitle" },
603 "class": { "section": true },
604 domProps: { innerHTML: "Preferences" },
605 }
606 ),
607 h('fieldset',
608 { },
609 [
610 //h('legend', { domProps: { innerHTML: "Legend title" } }),
611 h('label',
612 {
613 attrs: { for: "setHints" },
614 domProps: { innerHTML: "Show hints?" },
615 },
616 ),
617 h('input',
618 {
619 attrs: {
620 "id": "setHints",
621 type: "checkbox",
622 checked: this.hints,
623 },
624 on: { "change": this.toggleHints },
625 }
626 ),
627 ]
628 ),
629 h('fieldset',
630 { },
631 [
632 h('label',
633 {
634 attrs: { for: "selectColor" },
635 domProps: { innerHTML: "Board colors" },
636 },
637 ),
638 h("select",
639 {
640 attrs: { "id": "selectColor" },
641 on: { "change": this.setColor },
642 },
643 [
644 h("option",
645 {
646 domProps: {
647 "value": "lichess",
648 innerHTML: "brown"
649 },
650 attrs: { "selected": this.color=="lichess" },
651 }
652 ),
653 h("option",
654 {
655 domProps: {
656 "value": "chesscom",
657 innerHTML: "green"
658 },
659 attrs: { "selected": this.color=="chesscom" },
660 }
661 ),
662 h("option",
663 {
664 domProps: {
665 "value": "chesstempo",
666 innerHTML: "blue"
667 },
668 attrs: { "selected": this.color=="chesstempo" },
669 }
670 ),
671 ],
672 ),
673 ]
674 ),
675 h('fieldset',
676 { },
677 [
678 h('label',
679 {
680 attrs: { for: "selectSound" },
681 domProps: { innerHTML: "Play sounds?" },
682 },
683 ),
684 h("select",
685 {
686 attrs: { "id": "selectSound" },
687 on: { "change": this.setSound },
688 },
689 [
690 h("option",
691 {
692 domProps: {
693 "value": "0",
694 innerHTML: "None"
695 },
696 attrs: { "selected": this.sound==0 },
697 }
698 ),
699 h("option",
700 {
701 domProps: {
702 "value": "1",
703 innerHTML: "Newgame"
704 },
705 attrs: { "selected": this.sound==1 },
706 }
707 ),
708 h("option",
709 {
710 domProps: {
711 "value": "2",
712 innerHTML: "All"
713 },
714 attrs: { "selected": this.sound==2 },
715 }
716 ),
717 ],
718 ),
719 ]
720 ),
721 ]
722 )
723 ]
724 )
725 ];
726 elementArray = elementArray.concat(modalSettings);
727 const actions = h('div',
728 {
729 attrs: { "id": "actions" },
730 'class': { 'text-center': true },
731 },
732 actionArray
733 );
734 elementArray.push(actions);
735 if (this.score != "*" && this.pgnTxt.length > 0)
736 {
737 elementArray.push(
738 h('div',
739 {
740 attrs: { id: "pgn-div" },
741 "class": { "section-content": true },
742 },
743 [
744 h('a',
745 {
746 attrs: {
747 id: "download",
748 href: "#",
749 }
750 }
751 ),
752 h('p',
753 {
754 attrs: { id: "pgn-game" },
755 domProps: { innerHTML: this.pgnTxt }
756 }
757 ),
758 h('button',
759 {
760 attrs: { "id": "downloadBtn" },
761 on: { click: this.download },
762 domProps: { innerHTML: "Download game" },
763 }
764 ),
765 ]
766 )
767 );
768 }
769 else if (this.mode != "idle")
770 {
771 if (this.mode == "problem")
772 {
773 // Show problem solution (on click)
774 elementArray.push(
775 h('div',
776 {
777 attrs: { id: "solution-div" },
778 "class": { "section-content": true },
779 },
780 [
781 h('h3',
782 {
783 domProps: { innerHTML: "Show solution" },
784 on: { click: this.toggleShowSolution },
785 }
786 ),
787 h('p',
788 {
789 attrs: { id: "problem-solution" },
790 domProps: { innerHTML: this.problem.solution }
791 }
792 )
793 ]
794 )
795 );
796 }
797 // Show current FEN
798 elementArray.push(
799 h('div',
800 {
801 attrs: { id: "fen-div" },
802 "class": { "section-content": true },
803 },
804 [
805 h('p',
806 {
807 attrs: { id: "fen-string" },
808 domProps: { innerHTML: this.vr.getBaseFen() }
809 }
810 )
811 ]
812 )
813 );
814 }
815 return h(
816 'div',
817 {
818 'class': {
819 "col-sm-12":true,
820 "col-md-8":true,
821 "col-md-offset-2":true,
822 "col-lg-6":true,
823 "col-lg-offset-3":true,
824 },
825 // NOTE: click = mousedown + mouseup
826 on: {
827 mousedown: this.mousedown,
828 mousemove: this.mousemove,
829 mouseup: this.mouseup,
830 touchstart: this.mousedown,
831 touchmove: this.mousemove,
832 touchend: this.mouseup,
833 },
834 },
835 elementArray
836 );
837 },
838 computed: {
839 endgameMessage: function() {
840 let eogMessage = "Unfinished";
841 switch (this.score)
842 {
843 case "1-0":
844 eogMessage = "White win";
845 break;
846 case "0-1":
847 eogMessage = "Black win";
848 break;
849 case "1/2":
850 eogMessage = "Draw";
851 break;
852 }
853 return eogMessage;
854 },
855 },
856 created: function() {
857 const url = socketUrl;
858 const humanContinuation = (localStorage.getItem("variant") === variant);
859 const computerContinuation = (localStorage.getItem("comp-variant") === variant);
860 this.myid = (humanContinuation ? localStorage.getItem("myid") : getRandString());
861 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
862 const socketOpenListener = () => {
863 if (humanContinuation) //game VS human has priority
864 {
865 const fen = localStorage.getItem("fen");
866 const mycolor = localStorage.getItem("mycolor");
867 const oppid = localStorage.getItem("oppid");
868 const moves = JSON.parse(localStorage.getItem("moves"));
869 this.newGame("human", fen, mycolor, oppid, moves, true);
870 // Send ping to server (answer pong if opponent is connected)
871 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
872 }
873 else if (computerContinuation)
874 {
875 const fen = localStorage.getItem("comp-fen");
876 const mycolor = localStorage.getItem("comp-mycolor");
877 const moves = JSON.parse(localStorage.getItem("comp-moves"));
878 this.newGame("computer", fen, mycolor, undefined, moves, true);
879 }
880 };
881 const socketMessageListener = msg => {
882 const data = JSON.parse(msg.data);
883 switch (data.code)
884 {
885 case "duplicate":
886 // We opened another tab on the same game
887 this.mode = "idle";
888 this.vr = null;
889 alert("Already playing a game in this variant on another tab!");
890 break;
891 case "newgame": //opponent found
892 // oppid: opponent socket ID
893 this.newGame("human", data.fen, data.color, data.oppid);
894 break;
895 case "newmove": //..he played!
896 this.play(data.move, "animate");
897 break;
898 case "pong": //received if we sent a ping (game still alive on our side)
899 this.oppConnected = true;
900 const L = this.vr.moves.length;
901 // Send our "last state" informations to opponent
902 this.conn.send(JSON.stringify({
903 code:"lastate",
904 oppid:this.oppid,
905 lastMove:L>0?this.vr.moves[L-1]:undefined,
906 movesCount:L,
907 }));
908 break;
909 case "lastate": //got opponent infos about last move (we might have resigned)
910 if (this.mode!="human" || this.oppid!=data.oppid)
911 {
912 // OK, we resigned
913 this.conn.send(JSON.stringify({
914 code:"lastate",
915 oppid:this.oppid,
916 lastMove:undefined,
917 movesCount:-1,
918 }));
919 }
920 else if (data.movesCount < 0)
921 {
922 // OK, he resigned
923 this.endGame(this.mycolor=="w"?"1-0":"0-1");
924 }
925 else if (data.movesCount < this.vr.moves.length)
926 {
927 // We must tell last move to opponent
928 const L = this.vr.moves.length;
929 this.conn.send(JSON.stringify({
930 code:"lastate",
931 oppid:this.oppid,
932 lastMove:this.vr.moves[L-1],
933 movesCount:L,
934 }));
935 }
936 else if (data.movesCount > this.vr.moves.length) //just got last move from him
937 this.play(data.lastMove, "animate");
938 break;
939 case "resign": //..you won!
940 this.endGame(this.mycolor=="w"?"1-0":"0-1");
941 break;
942 // TODO: also use (dis)connect info to count online players?
943 case "connect":
944 case "disconnect":
945 if (this.mode == "human" && this.oppid == data.id)
946 this.oppConnected = (data.code == "connect");
947 break;
948 }
949 };
950 const socketCloseListener = () => {
951 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
952 this.conn.addEventListener('open', socketOpenListener);
953 this.conn.addEventListener('message', socketMessageListener);
954 this.conn.addEventListener('close', socketCloseListener);
955 };
956 this.conn.onopen = socketOpenListener;
957 this.conn.onmessage = socketMessageListener;
958 this.conn.onclose = socketCloseListener;
959 // Listen to keyboard left/right to navigate in game
960 document.onkeydown = event => {
961 if (this.mode == "idle" && !!this.vr && this.vr.moves.length > 0
962 && [37,39].includes(event.keyCode))
963 {
964 event.preventDefault();
965 if (event.keyCode == 37) //Back
966 this.undo();
967 else //Forward (39)
968 this.play();
969 }
970 };
971 // Computer moves web worker logic:
972 this.compWorker.postMessage(["scripts",variant]);
973 const self = this;
974 this.compWorker.onmessage = function(e) {
975 const compMove = e.data;
976 // (first move) HACK: small delay to avoid selecting elements
977 // before they appear on page:
978 const delay = Math.max(500-(Date.now()-self.timeStart), 0);
979 setTimeout(() => {
980 if (self.mode == "computer") //Warning: mode could have changed!
981 self.play(compMove, "animate")
982 }, delay);
983 }
984 },
985 methods: {
986 toggleShowSolution: function() {
987 let problemSolution = document.getElementById("problem-solution");
988 problemSolution.style.display =
989 !problemSolution.style.display || problemSolution.style.display == "none"
990 ? "block"
991 : "none";
992 },
993 download: function() {
994 let content = document.getElementById("pgn-game").innerHTML;
995 content = content.replace(/<br>/g, "\n");
996 // Prepare and trigger download link
997 let downloadAnchor = document.getElementById("download");
998 downloadAnchor.setAttribute("download", "game.pgn");
999 downloadAnchor.href = "data:text/plain;charset=utf-8," +
1000 encodeURIComponent(content);
1001 downloadAnchor.click();
1002 },
1003 showScoreMsg: function() {
1004 let modalBox = document.getElementById("modal-eog");
1005 modalBox.checked = true;
1006 setTimeout(() => { modalBox.checked = false; }, 2000);
1007 },
1008 endGame: function(score) {
1009 this.score = score;
1010 this.showScoreMsg();
1011 // Variants may have special PGN structure (so next function isn't defined here)
1012 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
1013 if (["human","computer"].includes(this.mode))
1014 this.clearStorage();
1015 this.mode = "idle";
1016 this.cursor = this.vr.moves.length; //to navigate in finished game
1017 this.oppid = "";
1018 },
1019 setStorage: function() {
1020 if (this.mode=="human")
1021 {
1022 localStorage.setItem("myid", this.myid);
1023 localStorage.setItem("oppid", this.oppid);
1024 }
1025 // 'prefix' = "comp-" to resume games vs. computer
1026 const prefix = (this.mode=="computer" ? "comp-" : "");
1027 localStorage.setItem(prefix+"variant", variant);
1028 localStorage.setItem(prefix+"mycolor", this.mycolor);
1029 localStorage.setItem(prefix+"fenStart", this.fenStart);
1030 localStorage.setItem(prefix+"moves", JSON.stringify(this.vr.moves));
1031 localStorage.setItem(prefix+"fen", this.vr.getFen());
1032 },
1033 updateStorage: function() {
1034 const prefix = (this.mode=="computer" ? "comp-" : "");
1035 localStorage.setItem(prefix+"moves", JSON.stringify(this.vr.moves));
1036 localStorage.setItem(prefix+"fen", this.vr.getFen());
1037 },
1038 clearStorage: function() {
1039 if (this.mode=="human")
1040 {
1041 delete localStorage["myid"];
1042 delete localStorage["oppid"];
1043 }
1044 const prefix = (this.mode=="computer" ? "comp-" : "");
1045 delete localStorage[prefix+"variant"];
1046 delete localStorage[prefix+"mycolor"];
1047 delete localStorage[prefix+"fenStart"];
1048 delete localStorage[prefix+"fen"];
1049 delete localStorage[prefix+"moves"];
1050 },
1051 // HACK because mini-css tooltips are persistent after click...
1052 getRidOfTooltip: function(elt) {
1053 elt.style.visibility = "hidden";
1054 setTimeout(() => { elt.style.visibility="visible"; }, 100);
1055 },
1056 showSettings: function(e) {
1057 this.getRidOfTooltip(e.currentTarget);
1058 document.getElementById("modal-settings").checked = true;
1059 },
1060 toggleHints: function() {
1061 this.hints = !this.hints;
1062 setCookie("hints", this.hints ? "1" : "0");
1063 },
1064 setColor: function(e) {
1065 this.color = e.target.options[e.target.selectedIndex].value;
1066 setCookie("color", this.color);
1067 },
1068 setSound: function(e) {
1069 this.sound = parseInt(e.target.options[e.target.selectedIndex].value);
1070 setCookie("sound", this.sound);
1071 },
1072 clickGameSeek: function(e) {
1073 this.getRidOfTooltip(e.currentTarget);
1074 if (this.mode == "human")
1075 return; //no newgame while playing
1076 if (this.seek)
1077 {
1078 this.conn.send(JSON.stringify({code:"cancelnewgame"}));
1079 this.seek = false;
1080 }
1081 else
1082 this.newGame("human");
1083 },
1084 clickComputerGame: function(e) {
1085 this.getRidOfTooltip(e.currentTarget);
1086 if (this.mode == "human")
1087 return; //no newgame while playing
1088 this.newGame("computer");
1089 },
1090 clickFriendGame: function(e) {
1091 this.getRidOfTooltip(e.currentTarget);
1092 document.getElementById("modal-fenedit").checked = true;
1093 },
1094 resign: function(e) {
1095 this.getRidOfTooltip(e.currentTarget);
1096 if (this.mode == "human" && this.oppConnected)
1097 {
1098 try {
1099 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
1100 } catch (INVALID_STATE_ERR) {
1101 return; //socket is not ready (and not yet reconnected)
1102 }
1103 }
1104 this.endGame(this.mycolor=="w"?"0-1":"1-0");
1105 },
1106 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
1107 const fen = fenInit || VariantRules.GenRandInitFen();
1108 console.log(fen); //DEBUG
1109 if (mode=="human" && !oppId)
1110 {
1111 const storageVariant = localStorage.getItem("variant");
1112 if (!!storageVariant && storageVariant !== variant)
1113 return alert("Finish your " + storageVariant + " game first!");
1114 // Send game request and wait..
1115 try {
1116 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
1117 } catch (INVALID_STATE_ERR) {
1118 return; //nothing achieved
1119 }
1120 this.seek = true;
1121 let modalBox = document.getElementById("modal-newgame");
1122 modalBox.checked = true;
1123 setTimeout(() => { modalBox.checked = false; }, 2000);
1124 return;
1125 }
1126 if (mode == "computer" && !continuation)
1127 {
1128 const storageVariant = localStorage.getItem("comp-variant");
1129 if (!!storageVariant && storageVariant !== variant)
1130 {
1131 if (!confirm("Unfinished " + storageVariant +
1132 " computer game will be erased"))
1133 {
1134 return;
1135 }
1136 }
1137 }
1138 if (this.mode == "computer" && mode == "human")
1139 {
1140 // Save current computer game to resume it later
1141 this.setStorage();
1142 }
1143 this.vr = new VariantRules(fen, moves || []);
1144 this.score = "*";
1145 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1146 this.mode = mode;
1147 if (continuation && moves.length > 0) //NOTE: "continuation": redundant test
1148 {
1149 const lastMove = moves[moves.length-1];
1150 this.vr.undo(lastMove);
1151 this.incheck = this.vr.getCheckSquares(lastMove);
1152 this.vr.play(lastMove, "ingame");
1153 }
1154 else
1155 this.incheck = [];
1156 if (continuation)
1157 {
1158 const prefix = (mode=="computer" ? "comp-" : "");
1159 this.fenStart = localStorage.getItem(prefix+"fenStart");
1160 }
1161 else
1162 this.fenStart = V.ParseFen(fen).position; //this is enough
1163 if (mode=="human")
1164 {
1165 // Opponent found!
1166 if (!continuation) //not playing sound on game continuation
1167 {
1168 if (this.sound >= 1)
1169 new Audio("/sounds/newgame.mp3").play().catch(err => {});
1170 document.getElementById("modal-newgame").checked = false;
1171 }
1172 this.oppid = oppId;
1173 this.oppConnected = !continuation;
1174 this.mycolor = color;
1175 this.seek = false;
1176 this.setStorage(); //in case of interruptions
1177 }
1178 else if (mode == "computer")
1179 {
1180 this.compWorker.postMessage(["init",this.vr.getFen()]);
1181 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
1182 if (this.mycolor == 'b')
1183 this.playComputerMove();
1184 }
1185 //else: against a (IRL) friend or problem solving: nothing more to do
1186 },
1187 playComputerMove: function() {
1188 this.timeStart = Date.now();
1189 this.compWorker.postMessage(["askmove"]);
1190 },
1191 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1192 getSquareId: function(o) {
1193 // NOTE: a separator is required to allow any size of board
1194 return "sq-" + o.x + "-" + o.y;
1195 },
1196 // Inverse function
1197 getSquareFromId: function(id) {
1198 let idParts = id.split('-');
1199 return [parseInt(idParts[1]), parseInt(idParts[2])];
1200 },
1201 mousedown: function(e) {
1202 e = e || window.event;
1203 let ingame = false;
1204 let elem = e.target;
1205 while (!ingame && elem !== null)
1206 {
1207 if (elem.classList.contains("game"))
1208 {
1209 ingame = true;
1210 break;
1211 }
1212 elem = elem.parentElement;
1213 }
1214 if (!ingame) //let default behavior (click on button...)
1215 return;
1216 e.preventDefault(); //disable native drag & drop
1217 if (!this.selectedPiece && e.target.classList.contains("piece"))
1218 {
1219 // Next few lines to center the piece on mouse cursor
1220 let rect = e.target.parentNode.getBoundingClientRect();
1221 this.start = {
1222 x: rect.x + rect.width/2,
1223 y: rect.y + rect.width/2,
1224 id: e.target.parentNode.id
1225 };
1226 this.selectedPiece = e.target.cloneNode();
1227 this.selectedPiece.style.position = "absolute";
1228 this.selectedPiece.style.top = 0;
1229 this.selectedPiece.style.display = "inline-block";
1230 this.selectedPiece.style.zIndex = 3000;
1231 const startSquare = this.getSquareFromId(e.target.parentNode.id);
1232 this.possibleMoves = [];
1233 if (this.mode != "idle")
1234 {
1235 const color = ["friend","problem"].includes(this.mode)
1236 ? this.vr.turn
1237 : this.mycolor;
1238 if (this.vr.canIplay(color,startSquare))
1239 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
1240 }
1241 // Next line add moving piece just after current image
1242 // (required for Crazyhouse reserve)
1243 e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
1244 }
1245 },
1246 mousemove: function(e) {
1247 if (!this.selectedPiece)
1248 return;
1249 e = e || window.event;
1250 // If there is an active element, move it around
1251 if (!!this.selectedPiece)
1252 {
1253 const [offsetX,offsetY] = !!e.clientX
1254 ? [e.clientX,e.clientY] //desktop browser
1255 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone
1256 this.selectedPiece.style.left = (offsetX-this.start.x) + "px";
1257 this.selectedPiece.style.top = (offsetY-this.start.y) + "px";
1258 }
1259 },
1260 mouseup: function(e) {
1261 if (!this.selectedPiece)
1262 return;
1263 e = e || window.event;
1264 // Read drop target (or parentElement, parentNode... if type == "img")
1265 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coords
1266 const [offsetX,offsetY] = !!e.clientX
1267 ? [e.clientX,e.clientY]
1268 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY];
1269 let landing = document.elementFromPoint(offsetX, offsetY);
1270 this.selectedPiece.style.zIndex = 3000;
1271 // Next condition: classList.contains(piece) fails because of marks
1272 while (landing.tagName == "IMG")
1273 landing = landing.parentNode;
1274 if (this.start.id == landing.id)
1275 {
1276 // A click: selectedPiece and possibleMoves are already filled
1277 return;
1278 }
1279 // OK: process move attempt
1280 let endSquare = this.getSquareFromId(landing.id);
1281 let moves = this.findMatchingMoves(endSquare);
1282 this.possibleMoves = [];
1283 if (moves.length > 1)
1284 this.choices = moves;
1285 else if (moves.length==1)
1286 this.play(moves[0]);
1287 // Else: impossible move
1288 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
1289 delete this.selectedPiece;
1290 this.selectedPiece = null;
1291 },
1292 findMatchingMoves: function(endSquare) {
1293 // Run through moves list and return the matching set (if promotions...)
1294 let moves = [];
1295 this.possibleMoves.forEach(function(m) {
1296 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
1297 moves.push(m);
1298 });
1299 return moves;
1300 },
1301 animateMove: function(move) {
1302 let startSquare = document.getElementById(this.getSquareId(move.start));
1303 let endSquare = document.getElementById(this.getSquareId(move.end));
1304 let rectStart = startSquare.getBoundingClientRect();
1305 let rectEnd = endSquare.getBoundingClientRect();
1306 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
1307 let movingPiece =
1308 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
1309 // HACK for animation (with positive translate, image slides "under background")
1310 // Possible improvement: just alter squares on the piece's way...
1311 squares = document.getElementsByClassName("board");
1312 for (let i=0; i<squares.length; i++)
1313 {
1314 let square = squares.item(i);
1315 if (square.id != this.getSquareId(move.start))
1316 square.style.zIndex = "-1";
1317 }
1318 movingPiece.style.transform = "translate(" + translation.x + "px," +
1319 translation.y + "px)";
1320 movingPiece.style.transitionDuration = "0.2s";
1321 movingPiece.style.zIndex = "3000";
1322 setTimeout( () => {
1323 for (let i=0; i<squares.length; i++)
1324 squares.item(i).style.zIndex = "auto";
1325 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
1326 this.play(move);
1327 }, 250);
1328 },
1329 play: function(move, programmatic) {
1330 if (!move)
1331 {
1332 // Navigate after game is over
1333 if (this.cursor >= this.vr.moves.length)
1334 return; //already at the end
1335 move = this.vr.moves[this.cursor++];
1336 }
1337 if (!!programmatic) //computer or human opponent
1338 {
1339 this.animateMove(move);
1340 return;
1341 }
1342 // Not programmatic, or animation is over
1343 if (this.mode == "human" && this.vr.turn == this.mycolor)
1344 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
1345 if (this.sound == 2)
1346 new Audio("/sounds/chessmove1.mp3").play().catch(err => {});
1347 if (this.mode != "idle")
1348 {
1349 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
1350 this.vr.play(move, "ingame");
1351 if (this.mode == "computer")
1352 {
1353 // Send the move to web worker
1354 this.compWorker.postMessage(["newmove",move]);
1355 }
1356 }
1357 else
1358 {
1359 VariantRules.PlayOnBoard(this.vr.board, move);
1360 this.$forceUpdate(); //TODO: ?!
1361 }
1362 if (["human","computer"].includes(this.mode))
1363 this.updateStorage(); //after our moves and opponent moves
1364 if (this.mode != "idle")
1365 {
1366 const eog = this.vr.checkGameOver();
1367 if (eog != "*")
1368 {
1369 if (["human","computer"].includes(this.mode))
1370 this.endGame(eog);
1371 else
1372 {
1373 // Just show score on screen (allow undo)
1374 this.score = eog;
1375 this.showScoreMsg();
1376 }
1377 }
1378 }
1379 if (this.mode == "computer" && this.vr.turn != this.mycolor)
1380 this.playComputerMove();
1381 },
1382 undo: function() {
1383 // Navigate after game is over
1384 if (this.cursor == 0)
1385 return; //already at the beginning
1386 if (this.cursor == this.vr.moves.length)
1387 this.incheck = []; //in case of...
1388 const move = this.vr.moves[--this.cursor];
1389 VariantRules.UndoOnBoard(this.vr.board, move);
1390 this.$forceUpdate(); //TODO: ?!
1391 },
1392 undoInGame: function() {
1393 const lm = this.vr.lastMove;
1394 if (!!lm)
1395 {
1396 this.vr.undo(lm);
1397 const lmBefore = this.vr.lastMove;
1398 if (!!lmBefore)
1399 {
1400 this.vr.undo(lmBefore);
1401 this.incheck = this.vr.getCheckSquares(lmBefore);
1402 this.vr.play(lmBefore, "ingame");
1403 }
1404 else
1405 this.incheck = [];
1406 }
1407 },
1408 },
1409 })