Attempt to reduce button sizes on small screens
[vchess.git] / public / javascripts / components / game.js
CommitLineData
1d184b4c
BA
1Vue.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
dfb4afc1 11 score: "*", //'*' means 'unfinished'
2748531f 12 mode: "idle", //human, friend, computer or idle (when not playing)
1d184b4c
BA
13 oppid: "", //opponent ID in case of HH game
14 oppConnected: false,
186516b8 15 seek: false,
762b7c9c 16 fenStart: "",
4b5fe306 17 incheck: [],
3840e240 18 pgnTxt: "",
b019d603 19 expert: getCookie("expert") === "1" ? true : false,
efb20746 20 gameId: "", //used to limit computer moves' time
1d184b4c
BA
21 };
22 },
23 render(h) {
c94bc812 24 const [sizeX,sizeY] = VariantRules.size;
b8a0ec4a 25 const smallScreen = (screen.width <= 500);
1d184b4c
BA
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; });
4b5fe306
BA
29 // Also precompute in-check squares
30 let incheckSq = doubleArray(sizeX, sizeY, false);
31 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
1d184b4c 32 let elementArray = [];
2748531f 33 let actionArray = [];
1dcf83e8
BA
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",
b8a0ec4a 44 "small": smallScreen,
1d184b4c 45 },
1dcf83e8
BA
46 },
47 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
48 );
2748531f
BA
49 if (["idle","computer"].includes(this.mode))
50 {
51 actionArray.push(
52 h('button',
1d184b4c 53 {
f3802fcd 54 on: { click: this.clickComputerGame },
1d184b4c 55 attrs: { "aria-label": 'New game VS computer' },
186516b8
BA
56 'class': {
57 "tooltip":true,
0706ea91 58 "bottom": true,
2748531f 59 "playing": this.mode == "computer",
b8a0ec4a 60 "small": smallScreen,
186516b8 61 },
1d184b4c
BA
62 },
63 [h('i', { 'class': { "material-icons": true } }, "computer")])
2748531f
BA
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",
b8a0ec4a 77 "small": smallScreen,
2748531f
BA
78 },
79 },
80 [h('i', { 'class': { "material-icons": true } }, "people")])
81 );
82 }
1d184b4c
BA
83 if (!!this.vr)
84 {
bdb1f12d
BA
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);
1d184b4c
BA
90 if (this.mode == "human")
91 {
92 let connectedIndic = h(
93 'div',
94 {
95 "class": {
bdb1f12d
BA
96 "topindicator": true,
97 "indic-left": true,
1d184b4c
BA
98 "connected": this.oppConnected,
99 "disconnected": !this.oppConnected,
100 },
bdb1f12d
BA
101 style: {
102 "width": indicWidth + "px",
103 "height": indicWidth + "px",
104 },
1d184b4c
BA
105 }
106 );
107 elementArray.push(connectedIndic);
108 }
bdb1f12d
BA
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);
3ed62725
BA
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,
b8a0ec4a 136 "small": smallScreen,
3ed62725
BA
137 },
138 },
2748531f 139 [h('i', { 'class': { "material-icons": true } }, "visibility_off")]
3ed62725
BA
140 );
141 elementArray.push(expertSwitch);
1d184b4c
BA
142 let choices = h('div',
143 {
144 attrs: { "id": "choices" },
145 'class': { 'row': true },
146 style: {
1d184b4c
BA
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 {
c94bc812
BA
156 'class': {
157 'board': true,
8a196305 158 ['board'+sizeY]: true,
c94bc812 159 },
1d184b4c
BA
160 style: {
161 'width': (100/this.choices.length) + "%",
162 'padding-bottom': (100/this.choices.length) + "%",
163 },
164 },
165 [h('img',
166 {
4b353936
BA
167 attrs: { "src": '/images/pieces/' +
168 VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
c94bc812 169 'class': { 'choice-piece': true },
1d184b4c
BA
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,
4b353936
BA
202 'ghost': !!this.selectedPiece
203 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
1d184b4c
BA
204 },
205 attrs: {
4b353936
BA
206 src: "/images/pieces/" +
207 VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
1d184b4c
BA
208 },
209 }
210 )
211 );
212 }
3ed62725 213 if (!this.expert && hintSquares[ci][cj])
1d184b4c
BA
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 }
30ff6e04 229 const lm = this.vr.lastMove;
3300df38
BA
230 const showLight = !this.expert &&
231 (this.mode!="idle" || this.cursor==this.vr.moves.length);
1d184b4c
BA
232 return h(
233 'div',
234 {
235 'class': {
236 'board': true,
8a196305 237 ['board'+sizeY]: true,
3300df38
BA
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],
1d184b4c
BA
242 },
243 attrs: {
244 id: this.getSquareId({x:ci,y:cj}),
245 },
246 },
247 elems
248 );
249 })
250 );
251 }), choices]
252 );
204e289b
BA
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,
b8a0ec4a 263 "small": smallScreen,
204e289b 264 },
0706ea91 265 },
204e289b
BA
266 [h('i', { 'class': { "material-icons": true } }, "flag")])
267 );
268 }
e64084da
BA
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' },
b8a0ec4a 278 "class": { "small": smallScreen },
e64084da
BA
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' },
b8a0ec4a 285 "class": { "small": smallScreen },
e64084da
BA
286 },
287 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
288 ]
289 );
290 }
2748531f
BA
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' },
b8a0ec4a 300 "class": { "small": smallScreen },
2748531f
BA
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' },
b8a0ec4a 308 "class": { "small": smallScreen },
2748531f
BA
309 },
310 [h('i', { 'class': { "material-icons": true } }, "cached")]
311 ),
312 ]);
313 }
1d184b4c 314 elementArray.push(gameDiv);
5c42c64e 315 if (!!this.vr.reserve)
1221ac47 316 {
6752407b 317 const shiftIdx = (this.mycolor=="w" ? 0 : 1);
5c42c64e 318 let myReservePiecesArray = [];
1221ac47
BA
319 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
320 {
5c42c64e
BA
321 myReservePiecesArray.push(h('div',
322 {
323 'class': {'board':true, ['board'+sizeY]:true},
6752407b 324 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
5c42c64e
BA
325 },
326 [
327 h('img',
1221ac47
BA
328 {
329 'class': {"piece":true},
330 attrs: {
331 "src": "/images/pieces/" +
332 this.vr.getReservePpath(this.mycolor,i) + ".svg",
1221ac47 333 }
5c42c64e
BA
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},
6752407b 348 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
5c42c64e
BA
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 ]));
1221ac47 364 }
5c42c64e
BA
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 ),
1221ac47
BA
378 h('div',
379 { 'class': { 'row': true }},
5c42c64e 380 oppReservePiecesArray
1221ac47 381 )
5c42c64e 382 ]
1221ac47 383 );
5c42c64e 384 elementArray.push(reserves);
1221ac47 385 }
f3802fcd 386 const eogMessage = this.getEndgameMessage(this.score);
1d184b4c
BA
387 const modalEog = [
388 h('input',
389 {
ecf44502 390 attrs: { "id": "modal-eog", type: "checkbox" },
1d184b4c
BA
391 "class": { "modal": true },
392 }),
393 h('div',
394 {
c148615e 395 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
1d184b4c
BA
396 },
397 [
398 h('div',
399 {
400 "class": { "card": true, "smallpad": true },
401 },
01a135e2
BA
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 ]
1d184b4c
BA
416 )
417 ]
418 )
419 ];
420 elementArray = elementArray.concat(modalEog);
421 }
422 const modalNewgame = [
423 h('input',
424 {
ecf44502 425 attrs: { "id": "modal-newgame", type: "checkbox" },
1d184b4c
BA
426 "class": { "modal": true },
427 }),
428 h('div',
429 {
c148615e 430 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
1d184b4c
BA
431 },
432 [
433 h('div',
434 {
435 "class": { "card": true, "smallpad": true },
436 },
437 [
438 h('label',
439 {
ecf44502 440 attrs: { "id": "close-newgame", "for": "modal-newgame" },
1d184b4c
BA
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);
2748531f
BA
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);
1d184b4c
BA
528 const actions = h('div',
529 {
530 attrs: { "id": "actions" },
531 'class': { 'text-center': true },
532 },
533 actionArray
534 );
535 elementArray.push(actions);
01a135e2
BA
536 if (this.score != "*")
537 {
538 elementArray.push(
539 h('div',
01ca2adc 540 { attrs: { id: "pgn-div" } },
01a135e2 541 [
01ca2adc
BA
542 h('a',
543 {
544 attrs: {
545 id: "download",
546 href: "#",
547 }
548 }
549 ),
01a135e2
BA
550 h('p',
551 {
01ca2adc
BA
552 attrs: { id: "pgn-game" },
553 on: { click: this.download },
85be503d
BA
554 domProps: { innerHTML: this.pgnTxt }
555 }
556 )
557 ]
558 )
559 );
560 }
561 else if (this.mode != "idle")
562 {
2748531f 563 // Show current FEN
85be503d
BA
564 elementArray.push(
565 h('div',
566 { attrs: { id: "fen-div" } },
567 [
568 h('p',
569 {
570 attrs: { id: "fen-string" },
2748531f 571 domProps: { innerHTML: this.vr.getFen() }
01a135e2
BA
572 }
573 )
574 ]
575 )
576 );
577 }
1d184b4c
BA
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 },
dda21a71 588 // NOTE: click = mousedown + mouseup
1d184b4c
BA
589 on: {
590 mousedown: this.mousedown,
591 mousemove: this.mousemove,
592 mouseup: this.mouseup,
ffea77d9
BA
593 touchstart: this.mousedown,
594 touchmove: this.mousemove,
595 touchend: this.mouseup,
1d184b4c
BA
596 },
597 },
598 elementArray
599 );
600 },
601 created: function() {
602 const url = socketUrl;
603 const continuation = (localStorage.getItem("variant") === variant);
b019d603 604 this.myid = continuation ? localStorage.getItem("myid") : getRandString();
92ff5bae
BA
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 }
1d184b4c 610 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
d35f20e4 611 const socketOpenListener = () => {
1d184b4c
BA
612 if (continuation)
613 {
dfb4afc1
BA
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);
a29d9d6b 619 // Send ping to server (answer pong if opponent is connected)
ecf44502 620 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
1d184b4c 621 }
30ff6e04
BA
622 else if (localStorage.getItem("newgame") === variant)
623 {
624 // New game request has been cancelled on disconnect
001344b9 625 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
30ff6e04 626 }
1d184b4c 627 };
d35f20e4 628 const socketMessageListener = msg => {
1d184b4c
BA
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;
f3802fcd 638 case "pong": //received if we sent a ping (game still alive on our side)
1d184b4c 639 this.oppConnected = true;
a29d9d6b 640 const L = this.vr.moves.length;
f3802fcd 641 // Send our "last state" informations to opponent
a29d9d6b
BA
642 this.conn.send(JSON.stringify({
643 code:"lastate",
f3802fcd 644 oppid:this.oppid,
a29d9d6b
BA
645 lastMove:L>0?this.vr.moves[L-1]:undefined,
646 movesCount:L,
647 }));
1d184b4c 648 break;
a29d9d6b
BA
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",
f3802fcd 655 oppid:this.oppid,
a29d9d6b
BA
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",
f3802fcd 671 oppid:this.oppid,
a29d9d6b
BA
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");
ecf44502 678 break;
1d184b4c 679 case "resign": //..you won!
dfb4afc1 680 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 681 break;
f3802fcd 682 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
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 };
d35f20e4 690 const socketCloseListener = () => {
d35f20e4
BA
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;
e64084da
BA
699 // Listen to keyboard left/right to navigate in game
700 document.onkeydown = event => {
2748531f 701 if (this.mode == "idle" && !!this.vr && this.vr.moves.length > 0
e64084da
BA
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 };
1d184b4c
BA
711 },
712 methods: {
01ca2adc
BA
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 },
dfb4afc1
BA
722 endGame: function(score) {
723 this.score = score;
ecf44502 724 let modalBox = document.getElementById("modal-eog");
186516b8 725 modalBox.checked = true;
204e289b 726 // Variants may have special PGN structure (so next function isn't defined here)
3840e240
BA
727 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
728 setTimeout(() => { modalBox.checked = false; }, 2000);
1d184b4c
BA
729 if (this.mode == "human")
730 this.clearStorage();
3840e240 731 this.mode = "idle";
e64084da 732 this.cursor = this.vr.moves.length; //to navigate in finished game
1d184b4c
BA
733 this.oppid = "";
734 },
f3802fcd
BA
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 },
762b7c9c
BA
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));
1d184b4c 758 localStorage.setItem("fen", this.vr.getFen());
762b7c9c
BA
759 },
760 updateStorage: function() {
dfb4afc1 761 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
762b7c9c 762 localStorage.setItem("fen", this.vr.getFen());
1d184b4c
BA
763 },
764 clearStorage: function() {
765 delete localStorage["variant"];
766 delete localStorage["myid"];
767 delete localStorage["mycolor"];
768 delete localStorage["oppid"];
762b7c9c 769 delete localStorage["fenStart"];
1d184b4c 770 delete localStorage["fen"];
dfb4afc1 771 delete localStorage["moves"];
1d184b4c 772 },
c148615e
BA
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);
f3802fcd
BA
780 if (this.mode == "human")
781 return; //no newgame while playing
782 if (this.seek)
01a135e2 783 {
283d06a4 784 this.conn.send(JSON.stringify({code:"cancelnewgame"}));
f3802fcd 785 delete localStorage["newgame"]; //cancel game seek
01a135e2
BA
786 this.seek = false;
787 }
f3802fcd 788 else
f3802fcd 789 this.newGame("human");
f3802fcd 790 },
c148615e
BA
791 clickComputerGame: function(e) {
792 this.getRidOfTooltip(e.currentTarget);
f3802fcd
BA
793 if (this.mode == "human")
794 return; //no newgame while playing
795 this.newGame("computer");
796 },
2748531f
BA
797 clickFriendGame: function(e) {
798 this.getRidOfTooltip(e.currentTarget);
799 document.getElementById("modal-fenedit").checked = true;
800 },
c148615e
BA
801 toggleExpertMode: function(e) {
802 this.getRidOfTooltip(e.currentTarget);
803 this.expert = !this.expert;
b019d603 804 setCookie("expert", this.expert ? "1" : "0");
c148615e 805 },
2748531f
BA
806 resign: function(e) {
807 this.getRidOfTooltip(e.currentTarget);
c148615e
BA
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 },
dfb4afc1 818 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
55eb331d 819 const fen = fenInit || VariantRules.GenRandInitFen();
1d184b4c
BA
820 console.log(fen); //DEBUG
821 if (mode=="human" && !oppId)
822 {
cd3174c5
BA
823 const storageVariant = localStorage.getItem("variant");
824 if (!!storageVariant && storageVariant !== variant)
825 {
cd3174c5
BA
826 alert("Finish your " + storageVariant + " game first!");
827 return;
828 }
1d184b4c 829 // Send game request and wait..
01a135e2
BA
830 localStorage["newgame"] = variant;
831 this.seek = true;
1d184b4c 832 this.clearStorage(); //in case of
d35f20e4
BA
833 try {
834 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
835 } catch (INVALID_STATE_ERR) {
836 return; //nothing achieved
837 }
f3802fcd 838 if (continuation !== "reconnect") //TODO: bad HACK...
a68d899d 839 {
ecf44502 840 let modalBox = document.getElementById("modal-newgame");
a68d899d
BA
841 modalBox.checked = true;
842 setTimeout(() => { modalBox.checked = false; }, 2000);
843 }
1d184b4c
BA
844 return;
845 }
b019d603 846 this.gameId = getRandString();
dfb4afc1 847 this.vr = new VariantRules(fen, moves || []);
c148615e 848 this.score = "*";
3840e240 849 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1d184b4c 850 this.mode = mode;
1fcaa356 851 this.incheck = []; //in case of
2748531f 852 this.fenStart = (continuation ? localStorage.getItem("fenStart") : fen);
1d184b4c
BA
853 if (mode=="human")
854 {
855 // Opponent found!
856 if (!continuation)
857 {
ecf44502 858 // Not playing sound on game continuation:
ea8417ff 859 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
ecf44502 860 document.getElementById("modal-newgame").checked = false;
1d184b4c
BA
861 }
862 this.oppid = oppId;
863 this.oppConnected = true;
864 this.mycolor = color;
186516b8 865 this.seek = false;
e64a4eff
BA
866 if (!!moves && moves.length > 0) //imply continuation
867 {
e64a4eff 868 const lastMove = moves[moves.length-1];
cd4cad04 869 this.vr.undo(lastMove);
46302e64 870 this.incheck = this.vr.getCheckSquares(lastMove);
e64a4eff
BA
871 this.vr.play(lastMove, "ingame");
872 }
186516b8 873 delete localStorage["newgame"];
762b7c9c 874 this.setStorage(); //in case of interruptions
1d184b4c 875 }
2748531f 876 else if (mode == "computer")
1d184b4c 877 {
f3c10e18 878 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
1d184b4c
BA
879 if (this.mycolor == 'b')
880 setTimeout(this.playComputerMove, 500);
881 }
2748531f 882 //else: against a (IRL) friend: nothing more to do
1d184b4c
BA
883 },
884 playComputerMove: function() {
4b353936 885 const timeStart = Date.now();
3c09dc49 886 const nbMoves = this.vr.moves.length; //using played moves to know if search finished
efb20746 887 const gameId = this.gameId; //to know if game was reset before timer end
3c09dc49
BA
888 setTimeout(
889 () => {
efb20746
BA
890 if (gameId != this.gameId)
891 return; //game stopped
3c09dc49
BA
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);
46302e64 896 const compMove = this.vr.getComputerMove();
4b353936
BA
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);
1d184b4c
BA
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;
44461547
BA
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;
1d184b4c
BA
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);
2748531f
BA
942 const iCanPlay = this.mode!="idle"
943 && (this.mode=="friend" || this.vr.canIplay(this.mycolor,startSquare));
944 this.possibleMoves = iCanPlay ? this.vr.getPossibleMovesFrom(startSquare) : [];
5bd679d5
BA
945 // Next line add moving piece just after current image (required for Crazyhouse reserve)
946 e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
1d184b4c
BA
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 {
ffea77d9
BA
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";
1d184b4c
BA
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
ffea77d9
BA
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);
1d184b4c
BA
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};
92ff5bae
BA
1006 let movingPiece =
1007 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
1008 // HACK for animation (with positive translate, image slides "under background"...)
1d184b4c
BA
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) {
e64084da
BA
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 }
1d184b4c
BA
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)
a29d9d6b 1042 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
ea8417ff 1043 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
e64084da 1044 if (this.mode != "idle")
3300df38
BA
1045 {
1046 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
e64084da 1047 this.vr.play(move, "ingame");
3300df38 1048 }
e64084da 1049 else
3300df38 1050 {
e64084da 1051 VariantRules.PlayOnBoard(this.vr.board, move);
3300df38
BA
1052 this.$forceUpdate(); //TODO: ?!
1053 }
1d184b4c
BA
1054 if (this.mode == "human")
1055 this.updateStorage(); //after our moves and opponent moves
e64084da
BA
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)
1d184b4c
BA
1063 setTimeout(this.playComputerMove, 500);
1064 },
e64084da
BA
1065 undo: function() {
1066 // Navigate after game is over
1067 if (this.cursor == 0)
1068 return; //already at the beginning
3300df38
BA
1069 if (this.cursor == this.vr.moves.length)
1070 this.incheck = []; //in case of...
e64084da
BA
1071 const move = this.vr.moves[--this.cursor];
1072 VariantRules.UndoOnBoard(this.vr.board, move);
1073 this.$forceUpdate(); //TODO: ?!
2748531f
BA
1074 },
1075 undoInGame: function() {
1076 const lm = this.vr.lastMove;
1077 if (!!lm)
1078 this.vr.undo(lm);
1079 },
1d184b4c
BA
1080 },
1081})