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