[cosmetics] Slightly rephrase bug report instructions
[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'
1d184b4c
BA
12 mode: "idle", //human, computer or idle (when not playing)
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: "",
3ed62725 19 expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false,
efb20746 20 gameId: "", //used to limit computer moves' time
1d184b4c
BA
21 };
22 },
23 render(h) {
c94bc812 24 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
25 // Precompute hints squares to facilitate rendering
26 let hintSquares = doubleArray(sizeX, sizeY, false);
27 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
4b5fe306
BA
28 // Also precompute in-check squares
29 let incheckSq = doubleArray(sizeX, sizeY, false);
30 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
1d184b4c 31 let elementArray = [];
186516b8
BA
32 const playingHuman = (this.mode == "human");
33 const playingComp = (this.mode == "computer");
1d184b4c
BA
34 let actionArray = [
35 h('button',
36 {
f3802fcd 37 on: { click: this.clickGameSeek },
1d184b4c 38 attrs: { "aria-label": 'New game VS human' },
186516b8
BA
39 'class': {
40 "tooltip": true,
0706ea91 41 "bottom": true, //display below
186516b8
BA
42 "seek": this.seek,
43 "playing": playingHuman,
44 },
1d184b4c
BA
45 },
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
47 h('button',
48 {
f3802fcd 49 on: { click: this.clickComputerGame },
1d184b4c 50 attrs: { "aria-label": 'New game VS computer' },
186516b8
BA
51 'class': {
52 "tooltip":true,
0706ea91 53 "bottom": true,
186516b8
BA
54 "playing": playingComp,
55 },
1d184b4c
BA
56 },
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
58 ];
59 if (!!this.vr)
60 {
bdb1f12d
BA
61 const square00 = document.getElementById("sq-0-0");
62 const squareWidth = !!square00
63 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
64 : 0;
65 const indicWidth = (squareWidth>0 ? squareWidth/2 : 20);
1d184b4c
BA
66 if (this.mode == "human")
67 {
68 let connectedIndic = h(
69 'div',
70 {
71 "class": {
bdb1f12d
BA
72 "topindicator": true,
73 "indic-left": true,
1d184b4c
BA
74 "connected": this.oppConnected,
75 "disconnected": !this.oppConnected,
76 },
bdb1f12d
BA
77 style: {
78 "width": indicWidth + "px",
79 "height": indicWidth + "px",
80 },
1d184b4c
BA
81 }
82 );
83 elementArray.push(connectedIndic);
84 }
bdb1f12d
BA
85 let turnIndic = h(
86 'div',
87 {
88 "class": {
89 "topindicator": true,
90 "indic-right": true,
91 "white-turn": this.vr.turn=="w",
92 "black-turn": this.vr.turn=="b",
93 },
94 style: {
95 "width": indicWidth + "px",
96 "height": indicWidth + "px",
97 },
98 }
99 );
100 elementArray.push(turnIndic);
3ed62725
BA
101 let expertSwitch = h(
102 'button',
103 {
104 on: { click: this.toggleExpertMode },
105 attrs: { "aria-label": 'Toggle expert mode' },
106 'class': {
107 "tooltip":true,
108 "topindicator": true,
109 "indic-right": true,
110 "expert-switch": true,
111 "expert-mode": this.expert,
112 },
113 },
114 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
115 );
116 elementArray.push(expertSwitch);
1d184b4c
BA
117 let choices = h('div',
118 {
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
121 style: {
1d184b4c
BA
122 "display": this.choices.length>0?"block":"none",
123 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
124 "width": (this.choices.length * squareWidth) + "px",
125 "height": squareWidth + "px",
126 },
127 },
128 this.choices.map( m => { //a "choice" is a move
129 return h('div',
130 {
c94bc812
BA
131 'class': {
132 'board': true,
8a196305 133 ['board'+sizeY]: true,
c94bc812 134 },
1d184b4c
BA
135 style: {
136 'width': (100/this.choices.length) + "%",
137 'padding-bottom': (100/this.choices.length) + "%",
138 },
139 },
140 [h('img',
141 {
4b353936
BA
142 attrs: { "src": '/images/pieces/' +
143 VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
c94bc812 144 'class': { 'choice-piece': true },
1d184b4c
BA
145 on: { "click": e => { this.play(m); this.choices=[]; } },
146 })
147 ]
148 );
149 })
150 );
151 // Create board element (+ reserves if needed by variant or mode)
152 let gameDiv = h('div',
153 {
154 'class': { 'game': true },
155 },
156 [_.range(sizeX).map(i => {
157 let ci = this.mycolor=='w' ? i : sizeX-i-1;
158 return h(
159 'div',
160 {
161 'class': {
162 'row': true,
163 },
164 style: { 'opacity': this.choices.length>0?"0.5":"1" },
165 },
166 _.range(sizeY).map(j => {
167 let cj = this.mycolor=='w' ? j : sizeY-j-1;
168 let elems = [];
169 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
170 {
171 elems.push(
172 h(
173 'img',
174 {
175 'class': {
176 'piece': true,
4b353936
BA
177 'ghost': !!this.selectedPiece
178 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
1d184b4c
BA
179 },
180 attrs: {
4b353936
BA
181 src: "/images/pieces/" +
182 VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
1d184b4c
BA
183 },
184 }
185 )
186 );
187 }
3ed62725 188 if (!this.expert && hintSquares[ci][cj])
1d184b4c
BA
189 {
190 elems.push(
191 h(
192 'img',
193 {
194 'class': {
195 'mark-square': true,
196 },
197 attrs: {
198 src: "/images/mark.svg",
199 },
200 }
201 )
202 );
203 }
30ff6e04 204 const lm = this.vr.lastMove;
e64a4eff 205 const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
1d184b4c
BA
206 return h(
207 'div',
208 {
209 'class': {
210 'board': true,
8a196305 211 ['board'+sizeY]: true,
3ed62725
BA
212 'light-square': (i+j)%2==0 && (this.expert || !highlight),
213 'dark-square': (i+j)%2==1 && (this.expert || !highlight),
214 'highlight': !this.expert && highlight,
215 'incheck': !this.expert && incheckSq[ci][cj],
1d184b4c
BA
216 },
217 attrs: {
218 id: this.getSquareId({x:ci,y:cj}),
219 },
220 },
221 elems
222 );
223 })
224 );
225 }), choices]
226 );
204e289b
BA
227 if (this.mode != "idle")
228 {
229 actionArray.push(
230 h('button',
231 {
232 on: { click: this.resign },
233 attrs: { "aria-label": 'Resign' },
234 'class': {
235 "tooltip":true,
236 "bottom": true,
237 },
0706ea91 238 },
204e289b
BA
239 [h('i', { 'class': { "material-icons": true } }, "flag")])
240 );
241 }
1d184b4c 242 elementArray.push(gameDiv);
5c42c64e 243 if (!!this.vr.reserve)
1221ac47 244 {
6752407b 245 const shiftIdx = (this.mycolor=="w" ? 0 : 1);
5c42c64e 246 let myReservePiecesArray = [];
1221ac47
BA
247 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
248 {
5c42c64e
BA
249 myReservePiecesArray.push(h('div',
250 {
251 'class': {'board':true, ['board'+sizeY]:true},
6752407b 252 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
5c42c64e
BA
253 },
254 [
255 h('img',
1221ac47
BA
256 {
257 'class': {"piece":true},
258 attrs: {
259 "src": "/images/pieces/" +
260 this.vr.getReservePpath(this.mycolor,i) + ".svg",
1221ac47 261 }
5c42c64e
BA
262 }),
263 h('sup',
264 {style: { "padding-left":"40%"} },
265 [ this.vr.reserve[this.mycolor][VariantRules.RESERVE_PIECES[i]] ]
266 )
267 ]));
268 }
269 let oppReservePiecesArray = [];
270 const oppCol = this.vr.getOppCol(this.mycolor);
271 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
272 {
273 oppReservePiecesArray.push(h('div',
274 {
275 'class': {'board':true, ['board'+sizeY]:true},
6752407b 276 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
5c42c64e
BA
277 },
278 [
279 h('img',
280 {
281 'class': {"piece":true},
282 attrs: {
283 "src": "/images/pieces/" +
284 this.vr.getReservePpath(oppCol,i) + ".svg",
285 }
286 }),
287 h('sup',
288 {style: { "padding-left":"40%"} },
289 [ this.vr.reserve[oppCol][VariantRules.RESERVE_PIECES[i]] ]
290 )
291 ]));
1221ac47 292 }
5c42c64e
BA
293 let reserves = h('div',
294 {
295 'class':{'game':true},
296 style: {"margin-bottom": "20px"},
297 },
298 [
299 h('div',
300 {
301 'class': { 'row': true },
302 style: {"margin-bottom": "15px"},
303 },
304 myReservePiecesArray
305 ),
1221ac47
BA
306 h('div',
307 { 'class': { 'row': true }},
5c42c64e 308 oppReservePiecesArray
1221ac47 309 )
5c42c64e 310 ]
1221ac47 311 );
5c42c64e 312 elementArray.push(reserves);
1221ac47 313 }
f3802fcd 314 const eogMessage = this.getEndgameMessage(this.score);
1d184b4c
BA
315 const modalEog = [
316 h('input',
317 {
ecf44502 318 attrs: { "id": "modal-eog", type: "checkbox" },
1d184b4c
BA
319 "class": { "modal": true },
320 }),
321 h('div',
322 {
323 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
324 },
325 [
326 h('div',
327 {
328 "class": { "card": true, "smallpad": true },
329 },
01a135e2
BA
330 [
331 h('label',
332 {
333 attrs: { "for": "modal-eog" },
334 "class": { "modal-close": true },
335 }
336 ),
337 h('h3',
338 {
339 "class": { "section": true },
340 domProps: { innerHTML: eogMessage },
341 }
342 )
343 ]
1d184b4c
BA
344 )
345 ]
346 )
347 ];
348 elementArray = elementArray.concat(modalEog);
349 }
350 const modalNewgame = [
351 h('input',
352 {
ecf44502 353 attrs: { "id": "modal-newgame", type: "checkbox" },
1d184b4c
BA
354 "class": { "modal": true },
355 }),
356 h('div',
357 {
358 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
359 },
360 [
361 h('div',
362 {
363 "class": { "card": true, "smallpad": true },
364 },
365 [
366 h('label',
367 {
ecf44502 368 attrs: { "id": "close-newgame", "for": "modal-newgame" },
1d184b4c
BA
369 "class": { "modal-close": true },
370 }
371 ),
372 h('h3',
373 {
374 "class": { "section": true },
375 domProps: { innerHTML: "New game" },
376 }
377 ),
378 h('p',
379 {
380 "class": { "section": true },
381 domProps: { innerHTML: "Waiting for opponent..." },
382 }
383 )
384 ]
385 )
386 ]
387 )
388 ];
389 elementArray = elementArray.concat(modalNewgame);
390 const actions = h('div',
391 {
392 attrs: { "id": "actions" },
393 'class': { 'text-center': true },
394 },
395 actionArray
396 );
397 elementArray.push(actions);
01a135e2
BA
398 if (this.score != "*")
399 {
400 elementArray.push(
401 h('div',
01ca2adc 402 { attrs: { id: "pgn-div" } },
01a135e2 403 [
01ca2adc
BA
404 h('a',
405 {
406 attrs: {
407 id: "download",
408 href: "#",
409 }
410 }
411 ),
01a135e2
BA
412 h('p',
413 {
01ca2adc
BA
414 attrs: { id: "pgn-game" },
415 on: { click: this.download },
85be503d
BA
416 domProps: { innerHTML: this.pgnTxt }
417 }
418 )
419 ]
420 )
421 );
422 }
423 else if (this.mode != "idle")
424 {
425 // Show current FEN (at least for debug)
426 elementArray.push(
427 h('div',
428 { attrs: { id: "fen-div" } },
429 [
430 h('p',
431 {
432 attrs: { id: "fen-string" },
433 domProps: { innerHTML: this.vr.getBaseFen() }
01a135e2
BA
434 }
435 )
436 ]
437 )
438 );
439 }
1d184b4c
BA
440 return h(
441 'div',
442 {
443 'class': {
444 "col-sm-12":true,
445 "col-md-8":true,
446 "col-md-offset-2":true,
447 "col-lg-6":true,
448 "col-lg-offset-3":true,
449 },
dda21a71 450 // NOTE: click = mousedown + mouseup
1d184b4c
BA
451 on: {
452 mousedown: this.mousedown,
453 mousemove: this.mousemove,
454 mouseup: this.mouseup,
b204a262
BA
455// touchstart: this.mousedown, //TODO...
456// touchmove: this.mousemove,
457// touchend: this.mouseup,
1d184b4c
BA
458 },
459 },
460 elementArray
461 );
462 },
463 created: function() {
464 const url = socketUrl;
465 const continuation = (localStorage.getItem("variant") === variant);
466 this.myid = continuation
467 ? localStorage.getItem("myid")
468 // random enough (TODO: function)
469 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
92ff5bae
BA
470 if (!continuation)
471 {
472 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
473 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {});
474 }
1d184b4c 475 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
d35f20e4 476 const socketOpenListener = () => {
1d184b4c
BA
477 if (continuation)
478 {
dfb4afc1
BA
479 const fen = localStorage.getItem("fen");
480 const mycolor = localStorage.getItem("mycolor");
481 const oppid = localStorage.getItem("oppid");
482 const moves = JSON.parse(localStorage.getItem("moves"));
483 this.newGame("human", fen, mycolor, oppid, moves, true);
a29d9d6b 484 // Send ping to server (answer pong if opponent is connected)
ecf44502 485 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
1d184b4c 486 }
30ff6e04
BA
487 else if (localStorage.getItem("newgame") === variant)
488 {
489 // New game request has been cancelled on disconnect
186516b8 490 this.seek = true;
001344b9 491 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
30ff6e04 492 }
1d184b4c 493 };
d35f20e4 494 const socketMessageListener = msg => {
1d184b4c
BA
495 const data = JSON.parse(msg.data);
496 switch (data.code)
497 {
498 case "newgame": //opponent found
499 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
500 break;
501 case "newmove": //..he played!
502 this.play(data.move, "animate");
503 break;
f3802fcd 504 case "pong": //received if we sent a ping (game still alive on our side)
1d184b4c 505 this.oppConnected = true;
a29d9d6b 506 const L = this.vr.moves.length;
f3802fcd 507 // Send our "last state" informations to opponent
a29d9d6b
BA
508 this.conn.send(JSON.stringify({
509 code:"lastate",
f3802fcd 510 oppid:this.oppid,
a29d9d6b
BA
511 lastMove:L>0?this.vr.moves[L-1]:undefined,
512 movesCount:L,
513 }));
1d184b4c 514 break;
a29d9d6b
BA
515 case "lastate": //got opponent infos about last move (we might have resigned)
516 if (this.mode!="human" || this.oppid!=data.oppid)
517 {
518 // OK, we resigned
519 this.conn.send(JSON.stringify({
520 code:"lastate",
f3802fcd 521 oppid:this.oppid,
a29d9d6b
BA
522 lastMove:undefined,
523 movesCount:-1,
524 }));
525 }
526 else if (data.movesCount < 0)
527 {
528 // OK, he resigned
529 this.endGame(this.mycolor=="w"?"1-0":"0-1");
530 }
531 else if (data.movesCount < this.vr.moves.length)
532 {
533 // We must tell last move to opponent
534 const L = this.vr.moves.length;
535 this.conn.send(JSON.stringify({
536 code:"lastate",
f3802fcd 537 oppid:this.oppid,
a29d9d6b
BA
538 lastMove:this.vr.moves[L-1],
539 movesCount:L,
540 }));
541 }
542 else if (data.movesCount > this.vr.moves.length) //just got last move from him
543 this.play(data.lastMove, "animate");
ecf44502 544 break;
1d184b4c 545 case "resign": //..you won!
dfb4afc1 546 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 547 break;
f3802fcd 548 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
549 case "connect":
550 case "disconnect":
551 if (this.mode == "human" && this.oppid == data.id)
552 this.oppConnected = (data.code == "connect");
553 break;
554 }
555 };
d35f20e4 556 const socketCloseListener = () => {
d35f20e4
BA
557 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
558 this.conn.addEventListener('open', socketOpenListener);
559 this.conn.addEventListener('message', socketMessageListener);
560 this.conn.addEventListener('close', socketCloseListener);
561 };
562 this.conn.onopen = socketOpenListener;
563 this.conn.onmessage = socketMessageListener;
564 this.conn.onclose = socketCloseListener;
1d184b4c
BA
565 },
566 methods: {
01ca2adc
BA
567 download: function() {
568 let content = document.getElementById("pgn-game").innerHTML;
569 content = content.replace(/<br>/g, "\n");
570 // Prepare and trigger download link
571 let downloadAnchor = document.getElementById("download");
572 downloadAnchor.setAttribute("download", "game.pgn");
573 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
574 downloadAnchor.click();
575 },
dfb4afc1
BA
576 endGame: function(score) {
577 this.score = score;
ecf44502 578 let modalBox = document.getElementById("modal-eog");
186516b8 579 modalBox.checked = true;
204e289b 580 // Variants may have special PGN structure (so next function isn't defined here)
3840e240
BA
581 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
582 setTimeout(() => { modalBox.checked = false; }, 2000);
1d184b4c
BA
583 if (this.mode == "human")
584 this.clearStorage();
3840e240 585 this.mode = "idle";
1d184b4c
BA
586 this.oppid = "";
587 },
f3802fcd
BA
588 getEndgameMessage: function(score) {
589 let eogMessage = "Unfinished";
590 switch (this.score)
591 {
592 case "1-0":
593 eogMessage = "White win";
594 break;
595 case "0-1":
596 eogMessage = "Black win";
597 break;
598 case "1/2":
599 eogMessage = "Draw";
600 break;
601 }
602 return eogMessage;
603 },
3ed62725
BA
604 toggleExpertMode: function() {
605 this.expert = !this.expert;
606 document.cookie = "expert=" + (this.expert ? "1" : "0");
607 },
1d184b4c
BA
608 resign: function() {
609 if (this.mode == "human" && this.oppConnected)
d35f20e4
BA
610 {
611 try {
612 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
613 } catch (INVALID_STATE_ERR) {
a29d9d6b 614 return; //socket is not ready (and not yet reconnected)
d35f20e4
BA
615 }
616 }
dfb4afc1 617 this.endGame(this.mycolor=="w"?"0-1":"1-0");
1d184b4c 618 },
762b7c9c
BA
619 setStorage: function() {
620 localStorage.setItem("myid", this.myid);
621 localStorage.setItem("variant", variant);
622 localStorage.setItem("mycolor", this.mycolor);
623 localStorage.setItem("oppid", this.oppid);
624 localStorage.setItem("fenStart", this.fenStart);
625 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
1d184b4c 626 localStorage.setItem("fen", this.vr.getFen());
762b7c9c
BA
627 },
628 updateStorage: function() {
dfb4afc1 629 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
762b7c9c 630 localStorage.setItem("fen", this.vr.getFen());
1d184b4c
BA
631 },
632 clearStorage: function() {
633 delete localStorage["variant"];
634 delete localStorage["myid"];
635 delete localStorage["mycolor"];
636 delete localStorage["oppid"];
762b7c9c 637 delete localStorage["fenStart"];
1d184b4c 638 delete localStorage["fen"];
dfb4afc1 639 delete localStorage["moves"];
1d184b4c 640 },
f3802fcd
BA
641 clickGameSeek: function() {
642 if (this.mode == "human")
643 return; //no newgame while playing
644 if (this.seek)
01a135e2 645 {
f3802fcd 646 delete localStorage["newgame"]; //cancel game seek
01a135e2
BA
647 this.seek = false;
648 }
f3802fcd 649 else
f3802fcd 650 this.newGame("human");
f3802fcd
BA
651 },
652 clickComputerGame: function() {
653 if (this.mode == "human")
654 return; //no newgame while playing
655 this.newGame("computer");
656 },
dfb4afc1 657 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
55eb331d 658 const fen = fenInit || VariantRules.GenRandInitFen();
1d184b4c 659 console.log(fen); //DEBUG
dfb4afc1 660 this.score = "*";
1d184b4c
BA
661 if (mode=="human" && !oppId)
662 {
cd3174c5
BA
663 const storageVariant = localStorage.getItem("variant");
664 if (!!storageVariant && storageVariant !== variant)
665 {
cd3174c5
BA
666 alert("Finish your " + storageVariant + " game first!");
667 return;
668 }
1d184b4c 669 // Send game request and wait..
01a135e2
BA
670 localStorage["newgame"] = variant;
671 this.seek = true;
1d184b4c 672 this.clearStorage(); //in case of
d35f20e4
BA
673 try {
674 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
675 } catch (INVALID_STATE_ERR) {
676 return; //nothing achieved
677 }
f3802fcd 678 if (continuation !== "reconnect") //TODO: bad HACK...
a68d899d 679 {
ecf44502 680 let modalBox = document.getElementById("modal-newgame");
a68d899d
BA
681 modalBox.checked = true;
682 setTimeout(() => { modalBox.checked = false; }, 2000);
683 }
1d184b4c
BA
684 return;
685 }
efb20746
BA
686 // random enough (TODO: function)
687 this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
dfb4afc1 688 this.vr = new VariantRules(fen, moves || []);
3840e240 689 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1d184b4c 690 this.mode = mode;
1fcaa356 691 this.incheck = []; //in case of
762b7c9c
BA
692 this.fenStart = continuation
693 ? localStorage.getItem("fenStart")
694 : fen.split(" ")[0]; //Only the position matters
1d184b4c
BA
695 if (mode=="human")
696 {
697 // Opponent found!
698 if (!continuation)
699 {
ecf44502 700 // Not playing sound on game continuation:
ea8417ff 701 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
ecf44502 702 document.getElementById("modal-newgame").checked = false;
1d184b4c
BA
703 }
704 this.oppid = oppId;
705 this.oppConnected = true;
706 this.mycolor = color;
186516b8 707 this.seek = false;
e64a4eff
BA
708 if (!!moves && moves.length > 0) //imply continuation
709 {
e64a4eff 710 const lastMove = moves[moves.length-1];
cd4cad04 711 this.vr.undo(lastMove);
46302e64 712 this.incheck = this.vr.getCheckSquares(lastMove);
e64a4eff
BA
713 this.vr.play(lastMove, "ingame");
714 }
186516b8 715 delete localStorage["newgame"];
762b7c9c 716 this.setStorage(); //in case of interruptions
1d184b4c
BA
717 }
718 else //against computer
719 {
f3c10e18 720 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
1d184b4c
BA
721 if (this.mycolor == 'b')
722 setTimeout(this.playComputerMove, 500);
723 }
724 },
725 playComputerMove: function() {
4b353936 726 const timeStart = Date.now();
3c09dc49 727 const nbMoves = this.vr.moves.length; //using played moves to know if search finished
efb20746 728 const gameId = this.gameId; //to know if game was reset before timer end
3c09dc49
BA
729 setTimeout(
730 () => {
efb20746
BA
731 if (gameId != this.gameId)
732 return; //game stopped
3c09dc49
BA
733 const L = this.vr.moves.length;
734 if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish
735 this.vr.shouldReturn = true;
736 }, 5000);
46302e64 737 const compMove = this.vr.getComputerMove();
4b353936
BA
738 // (first move) HACK: avoid selecting elements before they appear on page:
739 const delay = Math.max(500-(Date.now()-timeStart), 0);
740 setTimeout(() => this.play(compMove, "animate"), delay);
1d184b4c
BA
741 },
742 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
743 getSquareId: function(o) {
744 // NOTE: a separator is required to allow any size of board
745 return "sq-" + o.x + "-" + o.y;
746 },
747 // Inverse function
748 getSquareFromId: function(id) {
749 let idParts = id.split('-');
750 return [parseInt(idParts[1]), parseInt(idParts[2])];
751 },
752 mousedown: function(e) {
753 e = e || window.event;
44461547
BA
754 let ingame = false;
755 let elem = e.target;
756 while (!ingame && elem !== null)
757 {
758 if (elem.classList.contains("game"))
759 {
760 ingame = true;
761 break;
762 }
763 elem = elem.parentElement;
764 }
765 if (!ingame) //let default behavior (click on button...)
766 return;
1d184b4c
BA
767 e.preventDefault(); //disable native drag & drop
768 if (!this.selectedPiece && e.target.classList.contains("piece"))
769 {
770 // Next few lines to center the piece on mouse cursor
771 let rect = e.target.parentNode.getBoundingClientRect();
772 this.start = {
773 x: rect.x + rect.width/2,
774 y: rect.y + rect.width/2,
775 id: e.target.parentNode.id
776 };
777 this.selectedPiece = e.target.cloneNode();
778 this.selectedPiece.style.position = "absolute";
779 this.selectedPiece.style.top = 0;
780 this.selectedPiece.style.display = "inline-block";
781 this.selectedPiece.style.zIndex = 3000;
782 let startSquare = this.getSquareFromId(e.target.parentNode.id);
55eb331d 783 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
1d184b4c
BA
784 ? this.vr.getPossibleMovesFrom(startSquare)
785 : [];
5bd679d5
BA
786 // Next line add moving piece just after current image (required for Crazyhouse reserve)
787 e.target.parentNode.insertBefore(this.selectedPiece, e.target.nextSibling);
1d184b4c
BA
788 }
789 },
790 mousemove: function(e) {
791 if (!this.selectedPiece)
792 return;
793 e = e || window.event;
794 // If there is an active element, move it around
795 if (!!this.selectedPiece)
796 {
797 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
798 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
799 }
800 },
801 mouseup: function(e) {
802 if (!this.selectedPiece)
803 return;
804 e = e || window.event;
805 // Read drop target (or parentElement, parentNode... if type == "img")
806 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
807 let landing = document.elementFromPoint(e.clientX, e.clientY);
808 this.selectedPiece.style.zIndex = 3000;
809 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
810 landing = landing.parentNode;
811 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
812 return;
813 // OK: process move attempt
814 let endSquare = this.getSquareFromId(landing.id);
815 let moves = this.findMatchingMoves(endSquare);
816 this.possibleMoves = [];
817 if (moves.length > 1)
818 this.choices = moves;
819 else if (moves.length==1)
820 this.play(moves[0]);
821 // Else: impossible move
822 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
823 delete this.selectedPiece;
824 this.selectedPiece = null;
825 },
826 findMatchingMoves: function(endSquare) {
827 // Run through moves list and return the matching set (if promotions...)
828 let moves = [];
829 this.possibleMoves.forEach(function(m) {
830 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
831 moves.push(m);
832 });
833 return moves;
834 },
835 animateMove: function(move) {
836 let startSquare = document.getElementById(this.getSquareId(move.start));
837 let endSquare = document.getElementById(this.getSquareId(move.end));
838 let rectStart = startSquare.getBoundingClientRect();
839 let rectEnd = endSquare.getBoundingClientRect();
840 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
92ff5bae
BA
841 let movingPiece =
842 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
843 // HACK for animation (with positive translate, image slides "under background"...)
1d184b4c
BA
844 // Possible improvement: just alter squares on the piece's way...
845 squares = document.getElementsByClassName("board");
846 for (let i=0; i<squares.length; i++)
847 {
848 let square = squares.item(i);
849 if (square.id != this.getSquareId(move.start))
850 square.style.zIndex = "-1";
851 }
852 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
853 movingPiece.style.transitionDuration = "0.2s";
854 movingPiece.style.zIndex = "3000";
855 setTimeout( () => {
856 for (let i=0; i<squares.length; i++)
857 squares.item(i).style.zIndex = "auto";
858 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
859 this.play(move);
860 }, 200);
861 },
862 play: function(move, programmatic) {
863 if (!!programmatic) //computer or human opponent
864 {
865 this.animateMove(move);
866 return;
867 }
46302e64 868 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
1d184b4c
BA
869 // Not programmatic, or animation is over
870 if (this.mode == "human" && this.vr.turn == this.mycolor)
a29d9d6b 871 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
ea8417ff 872 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
1d184b4c
BA
873 this.vr.play(move, "ingame");
874 if (this.mode == "human")
875 this.updateStorage(); //after our moves and opponent moves
46302e64 876 const eog = this.vr.checkGameOver();
1d184b4c
BA
877 if (eog != "*")
878 this.endGame(eog);
879 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
880 setTimeout(this.playComputerMove, 500);
881 },
882 },
883})