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