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