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