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