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