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