Implemented turn indicator
[vchess.git] / public / javascripts / components / game.js
1 // TODO: use indexedDB instead of localStorage? (more flexible: allow several games)
2 Vue.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
8 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket messages
12 score: "*", //'*' means 'unfinished'
13 mode: "idle", //human, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
15 oppConnected: false,
16 seek: false,
17 fenStart: "",
18 incheck: [],
19 };
20 },
21 render(h) {
22 let [sizeX,sizeY] = VariantRules.size;
23 // Precompute hints squares to facilitate rendering
24 let hintSquares = doubleArray(sizeX, sizeY, false);
25 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
26 // Also precompute in-check squares
27 let incheckSq = doubleArray(sizeX, sizeY, false);
28 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
29 let elementArray = [];
30 const playingHuman = (this.mode == "human");
31 const playingComp = (this.mode == "computer");
32 let actionArray = [
33 h('button',
34 {
35 on: { click: this.clickGameSeek },
36 attrs: { "aria-label": 'New game VS human' },
37 'class': {
38 "tooltip": true,
39 "bottom": true, //display below
40 "seek": this.seek,
41 "playing": playingHuman,
42 },
43 },
44 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
45 h('button',
46 {
47 on: { click: this.clickComputerGame },
48 attrs: { "aria-label": 'New game VS computer' },
49 'class': {
50 "tooltip":true,
51 "bottom": true,
52 "playing": playingComp,
53 },
54 },
55 [h('i', { 'class': { "material-icons": true } }, "computer")])
56 ];
57 if (!!this.vr)
58 {
59 const square00 = document.getElementById("sq-0-0");
60 const squareWidth = !!square00
61 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
62 : 0;
63 const indicWidth = (squareWidth>0 ? squareWidth/2 : 20);
64 if (this.mode == "human")
65 {
66 let connectedIndic = h(
67 'div',
68 {
69 "class": {
70 "topindicator": true,
71 "indic-left": true,
72 "connected": this.oppConnected,
73 "disconnected": !this.oppConnected,
74 },
75 style: {
76 "width": indicWidth + "px",
77 "height": indicWidth + "px",
78 },
79 }
80 );
81 elementArray.push(connectedIndic);
82 }
83 let turnIndic = h(
84 'div',
85 {
86 "class": {
87 "topindicator": true,
88 "indic-right": true,
89 "white-turn": this.vr.turn=="w",
90 "black-turn": this.vr.turn=="b",
91 },
92 style: {
93 "width": indicWidth + "px",
94 "height": indicWidth + "px",
95 },
96 }
97 );
98 elementArray.push(turnIndic);
99 let choices = h('div',
100 {
101 attrs: { "id": "choices" },
102 'class': { 'row': true },
103 style: {
104 "display": this.choices.length>0?"block":"none",
105 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
106 "width": (this.choices.length * squareWidth) + "px",
107 "height": squareWidth + "px",
108 },
109 },
110 this.choices.map( m => { //a "choice" is a move
111 return h('div',
112 {
113 'class': { 'board': true },
114 style: {
115 'width': (100/this.choices.length) + "%",
116 'padding-bottom': (100/this.choices.length) + "%",
117 },
118 },
119 [h('img',
120 {
121 attrs: { "src": '/images/pieces/' + VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
122 'class': { 'choice-piece': true, 'board': true },
123 on: { "click": e => { this.play(m); this.choices=[]; } },
124 })
125 ]
126 );
127 })
128 );
129 // Create board element (+ reserves if needed by variant or mode)
130 let gameDiv = h('div',
131 {
132 'class': { 'game': true },
133 },
134 [_.range(sizeX).map(i => {
135 let ci = this.mycolor=='w' ? i : sizeX-i-1;
136 return h(
137 'div',
138 {
139 'class': {
140 'row': true,
141 },
142 style: { 'opacity': this.choices.length>0?"0.5":"1" },
143 },
144 _.range(sizeY).map(j => {
145 let cj = this.mycolor=='w' ? j : sizeY-j-1;
146 let elems = [];
147 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
148 {
149 elems.push(
150 h(
151 'img',
152 {
153 'class': {
154 'piece': true,
155 'ghost': !!this.selectedPiece && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
156 },
157 attrs: {
158 src: "/images/pieces/" + VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
159 },
160 }
161 )
162 );
163 }
164 if (hintSquares[ci][cj])
165 {
166 elems.push(
167 h(
168 'img',
169 {
170 'class': {
171 'mark-square': true,
172 },
173 attrs: {
174 src: "/images/mark.svg",
175 },
176 }
177 )
178 );
179 }
180 const lm = this.vr.lastMove;
181 const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
182 return h(
183 'div',
184 {
185 'class': {
186 'board': true,
187 'light-square': !highlight && (i+j)%2==0,
188 'dark-square': !highlight && (i+j)%2==1,
189 'highlight': highlight,
190 'incheck': incheckSq[ci][cj],
191 },
192 attrs: {
193 id: this.getSquareId({x:ci,y:cj}),
194 },
195 },
196 elems
197 );
198 })
199 );
200 }), choices]
201 );
202 actionArray.push(
203 h('button',
204 {
205 on: { click: this.resign },
206 attrs: { "aria-label": 'Resign' },
207 'class': {
208 "tooltip":true,
209 "bottom": true,
210 },
211 },
212 [h('i', { 'class': { "material-icons": true } }, "flag")])
213 );
214 elementArray.push(gameDiv);
215 // if (!!vr.reserve)
216 // {
217 // let reserve = h('div',
218 // {'class':{'game':true}}, [
219 // h('div',
220 // { 'class': { 'row': true }},
221 // [
222 // h('div',
223 // {'class':{'board':true}},
224 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
225 // )
226 // ]
227 // )
228 // ],
229 // );
230 // elementArray.push(reserve);
231 // }
232 const eogMessage = this.getEndgameMessage(this.score);
233 const modalEog = [
234 h('input',
235 {
236 attrs: { "id": "modal-eog", type: "checkbox" },
237 "class": { "modal": true },
238 }),
239 h('div',
240 {
241 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
242 },
243 [
244 h('div',
245 {
246 "class": { "card": true, "smallpad": true },
247 },
248 [
249 h('label',
250 {
251 attrs: { "for": "modal-eog" },
252 "class": { "modal-close": true },
253 }
254 ),
255 h('h3',
256 {
257 "class": { "section": true },
258 domProps: { innerHTML: eogMessage },
259 }
260 )
261 ]
262 )
263 ]
264 )
265 ];
266 elementArray = elementArray.concat(modalEog);
267 }
268 const modalNewgame = [
269 h('input',
270 {
271 attrs: { "id": "modal-newgame", type: "checkbox" },
272 "class": { "modal": true },
273 }),
274 h('div',
275 {
276 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
277 },
278 [
279 h('div',
280 {
281 "class": { "card": true, "smallpad": true },
282 },
283 [
284 h('label',
285 {
286 attrs: { "id": "close-newgame", "for": "modal-newgame" },
287 "class": { "modal-close": true },
288 }
289 ),
290 h('h3',
291 {
292 "class": { "section": true },
293 domProps: { innerHTML: "New game" },
294 }
295 ),
296 h('p',
297 {
298 "class": { "section": true },
299 domProps: { innerHTML: "Waiting for opponent..." },
300 }
301 )
302 ]
303 )
304 ]
305 )
306 ];
307 elementArray = elementArray.concat(modalNewgame);
308 const actions = h('div',
309 {
310 attrs: { "id": "actions" },
311 'class': { 'text-center': true },
312 },
313 actionArray
314 );
315 elementArray.push(actions);
316 if (this.score != "*")
317 {
318 elementArray.push(
319 h('div',
320 { },
321 [
322 h('p',
323 {
324 domProps: {
325 innerHTML: this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode)
326 }
327 }
328 )
329 ]
330 )
331 );
332 }
333 return h(
334 'div',
335 {
336 'class': {
337 "col-sm-12":true,
338 "col-md-8":true,
339 "col-md-offset-2":true,
340 "col-lg-6":true,
341 "col-lg-offset-3":true,
342 },
343 // NOTE: click = mousedown + mouseup --> what about smartphone?!
344 on: {
345 mousedown: this.mousedown,
346 mousemove: this.mousemove,
347 mouseup: this.mouseup,
348 touchdown: this.mousedown,
349 touchmove: this.mousemove,
350 touchup: this.mouseup,
351 },
352 },
353 elementArray
354 );
355 },
356 created: function() {
357 const url = socketUrl;
358 const continuation = (localStorage.getItem("variant") === variant);
359 this.myid = continuation
360 ? localStorage.getItem("myid")
361 // random enough (TODO: function)
362 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
363 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
364 const socketOpenListener = () => {
365 if (continuation)
366 {
367 const fen = localStorage.getItem("fen");
368 const mycolor = localStorage.getItem("mycolor");
369 const oppid = localStorage.getItem("oppid");
370 const moves = JSON.parse(localStorage.getItem("moves"));
371 this.newGame("human", fen, mycolor, oppid, moves, true);
372 // Send ping to server (answer pong if opponent is connected)
373 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
374 }
375 else if (localStorage.getItem("newgame") === variant)
376 {
377 // New game request has been cancelled on disconnect
378 this.seek = true;
379 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
380 }
381 };
382 const socketMessageListener = msg => {
383 const data = JSON.parse(msg.data);
384 console.log("Receive message: " + data.code);
385 switch (data.code)
386 {
387 case "newgame": //opponent found
388 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
389 break;
390 case "newmove": //..he played!
391 this.play(data.move, "animate");
392 break;
393 case "pong": //received if we sent a ping (game still alive on our side)
394 this.oppConnected = true;
395 const L = this.vr.moves.length;
396 // Send our "last state" informations to opponent
397 this.conn.send(JSON.stringify({
398 code:"lastate",
399 oppid:this.oppid,
400 lastMove:L>0?this.vr.moves[L-1]:undefined,
401 movesCount:L,
402 }));
403 break;
404 case "lastate": //got opponent infos about last move (we might have resigned)
405 if (this.mode!="human" || this.oppid!=data.oppid)
406 {
407 // OK, we resigned
408 this.conn.send(JSON.stringify({
409 code:"lastate",
410 oppid:this.oppid,
411 lastMove:undefined,
412 movesCount:-1,
413 }));
414 }
415 else if (data.movesCount < 0)
416 {
417 // OK, he resigned
418 this.endGame(this.mycolor=="w"?"1-0":"0-1");
419 }
420 else if (data.movesCount < this.vr.moves.length)
421 {
422 // We must tell last move to opponent
423 const L = this.vr.moves.length;
424 this.conn.send(JSON.stringify({
425 code:"lastate",
426 oppid:this.oppid,
427 lastMove:this.vr.moves[L-1],
428 movesCount:L,
429 }));
430 }
431 else if (data.movesCount > this.vr.moves.length) //just got last move from him
432 this.play(data.lastMove, "animate");
433 break;
434 case "resign": //..you won!
435 this.endGame(this.mycolor=="w"?"1-0":"0-1");
436 break;
437 // TODO: also use (dis)connect info to count online players?
438 case "connect":
439 case "disconnect":
440 if (this.mode == "human" && this.oppid == data.id)
441 this.oppConnected = (data.code == "connect");
442 break;
443 }
444 };
445 const socketCloseListener = () => {
446 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
447 this.conn.addEventListener('open', socketOpenListener);
448 this.conn.addEventListener('message', socketMessageListener);
449 this.conn.addEventListener('close', socketCloseListener);
450 };
451 this.conn.onopen = socketOpenListener;
452 this.conn.onmessage = socketMessageListener;
453 this.conn.onclose = socketCloseListener;
454 },
455 methods: {
456 endGame: function(score) {
457 this.score = score;
458 let modalBox = document.getElementById("modal-eog");
459 modalBox.checked = true;
460 setTimeout(() => { modalBox.checked = false; }, 2000);
461 if (this.mode == "human")
462 this.clearStorage();
463 this.mode = "idle";
464 this.oppid = "";
465 },
466 getEndgameMessage: function(score) {
467 let eogMessage = "Unfinished";
468 switch (this.score)
469 {
470 case "1-0":
471 eogMessage = "White win";
472 break;
473 case "0-1":
474 eogMessage = "Black win";
475 break;
476 case "1/2":
477 eogMessage = "Draw";
478 break;
479 }
480 return eogMessage;
481 },
482 resign: function() {
483 if (this.mode == "human" && this.oppConnected)
484 {
485 try {
486 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
487 } catch (INVALID_STATE_ERR) {
488 return; //socket is not ready (and not yet reconnected)
489 }
490 }
491 this.endGame(this.mycolor=="w"?"0-1":"1-0");
492 },
493 setStorage: function() {
494 localStorage.setItem("myid", this.myid);
495 localStorage.setItem("variant", variant);
496 localStorage.setItem("mycolor", this.mycolor);
497 localStorage.setItem("oppid", this.oppid);
498 localStorage.setItem("fenStart", this.fenStart);
499 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
500 localStorage.setItem("fen", this.vr.getFen());
501 },
502 updateStorage: function() {
503 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
504 localStorage.setItem("fen", this.vr.getFen());
505 },
506 clearStorage: function() {
507 delete localStorage["variant"];
508 delete localStorage["myid"];
509 delete localStorage["mycolor"];
510 delete localStorage["oppid"];
511 delete localStorage["fenStart"];
512 delete localStorage["fen"];
513 delete localStorage["moves"];
514 },
515 clickGameSeek: function() {
516 if (this.mode == "human")
517 return; //no newgame while playing
518 if (this.seek)
519 {
520 delete localStorage["newgame"]; //cancel game seek
521 this.seek = false;
522 }
523 else
524 this.newGame("human");
525 },
526 clickComputerGame: function() {
527 if (this.mode == "human")
528 return; //no newgame while playing
529 this.newGame("computer");
530 },
531 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
532 const fen = fenInit || VariantRules.GenRandInitFen();
533 console.log(fen); //DEBUG
534 this.score = "*";
535 if (mode=="human" && !oppId)
536 {
537 const storageVariant = localStorage.getItem("variant");
538 if (!!storageVariant && storageVariant !== variant)
539 {
540 alert("Finish your " + storageVariant + " game first!");
541 return;
542 }
543 // Send game request and wait..
544 localStorage["newgame"] = variant;
545 this.seek = true;
546 this.clearStorage(); //in case of
547 try {
548 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
549 } catch (INVALID_STATE_ERR) {
550 return; //nothing achieved
551 }
552 if (continuation !== "reconnect") //TODO: bad HACK...
553 {
554 let modalBox = document.getElementById("modal-newgame");
555 modalBox.checked = true;
556 setTimeout(() => { modalBox.checked = false; }, 2000);
557 }
558 return;
559 }
560 this.vr = new VariantRules(fen, moves || []);
561 this.mode = mode;
562 this.incheck = []; //in case of
563 this.fenStart = continuation
564 ? localStorage.getItem("fenStart")
565 : fen.split(" ")[0]; //Only the position matters
566 if (mode=="human")
567 {
568 // Opponent found!
569 if (!continuation)
570 {
571 // Not playing sound on game continuation:
572 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
573 document.getElementById("modal-newgame").checked = false;
574 }
575 this.oppid = oppId;
576 this.oppConnected = true;
577 this.mycolor = color;
578 this.seek = false;
579 if (!!moves && moves.length > 0) //imply continuation
580 {
581 const oppCol = this.vr.turn;
582 const lastMove = moves[moves.length-1];
583 this.vr.undo(lastMove);
584 this.incheck = this.vr.getCheckSquares(lastMove, oppCol);
585 this.vr.play(lastMove, "ingame");
586 }
587 delete localStorage["newgame"];
588 this.setStorage(); //in case of interruptions
589 }
590 else //against computer
591 {
592 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
593 if (this.mycolor == 'b')
594 setTimeout(this.playComputerMove, 500);
595 }
596 },
597 playComputerMove: function() {
598 const compColor = this.mycolor=='w' ? 'b' : 'w';
599 const compMove = this.vr.getComputerMove(compColor);
600 // HACK: avoid selecting elements before they appear on page:
601 setTimeout(() => this.play(compMove, "animate"), 500);
602 },
603 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
604 getSquareId: function(o) {
605 // NOTE: a separator is required to allow any size of board
606 return "sq-" + o.x + "-" + o.y;
607 },
608 // Inverse function
609 getSquareFromId: function(id) {
610 let idParts = id.split('-');
611 return [parseInt(idParts[1]), parseInt(idParts[2])];
612 },
613 mousedown: function(e) {
614 e = e || window.event;
615 e.preventDefault(); //disable native drag & drop
616 if (!this.selectedPiece && e.target.classList.contains("piece"))
617 {
618 // Next few lines to center the piece on mouse cursor
619 let rect = e.target.parentNode.getBoundingClientRect();
620 this.start = {
621 x: rect.x + rect.width/2,
622 y: rect.y + rect.width/2,
623 id: e.target.parentNode.id
624 };
625 this.selectedPiece = e.target.cloneNode();
626 this.selectedPiece.style.position = "absolute";
627 this.selectedPiece.style.top = 0;
628 this.selectedPiece.style.display = "inline-block";
629 this.selectedPiece.style.zIndex = 3000;
630 let startSquare = this.getSquareFromId(e.target.parentNode.id);
631 this.possibleMoves = this.vr.canIplay(this.mycolor,startSquare)
632 ? this.vr.getPossibleMovesFrom(startSquare)
633 : [];
634 e.target.parentNode.appendChild(this.selectedPiece);
635 }
636 },
637 mousemove: function(e) {
638 if (!this.selectedPiece)
639 return;
640 e = e || window.event;
641 // If there is an active element, move it around
642 if (!!this.selectedPiece)
643 {
644 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
645 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
646 }
647 },
648 mouseup: function(e) {
649 if (!this.selectedPiece)
650 return;
651 e = e || window.event;
652 // Read drop target (or parentElement, parentNode... if type == "img")
653 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
654 let landing = document.elementFromPoint(e.clientX, e.clientY);
655 this.selectedPiece.style.zIndex = 3000;
656 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
657 landing = landing.parentNode;
658 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
659 return;
660 // OK: process move attempt
661 let endSquare = this.getSquareFromId(landing.id);
662 let moves = this.findMatchingMoves(endSquare);
663 this.possibleMoves = [];
664 if (moves.length > 1)
665 this.choices = moves;
666 else if (moves.length==1)
667 this.play(moves[0]);
668 // Else: impossible move
669 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
670 delete this.selectedPiece;
671 this.selectedPiece = null;
672 },
673 findMatchingMoves: function(endSquare) {
674 // Run through moves list and return the matching set (if promotions...)
675 let moves = [];
676 this.possibleMoves.forEach(function(m) {
677 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
678 moves.push(m);
679 });
680 return moves;
681 },
682 animateMove: function(move) {
683 let startSquare = document.getElementById(this.getSquareId(move.start));
684 let endSquare = document.getElementById(this.getSquareId(move.end));
685 let rectStart = startSquare.getBoundingClientRect();
686 let rectEnd = endSquare.getBoundingClientRect();
687 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
688 let movingPiece = document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
689 // HACK for animation (otherwise with positive translate, image slides "under background"...)
690 // Possible improvement: just alter squares on the piece's way...
691 squares = document.getElementsByClassName("board");
692 for (let i=0; i<squares.length; i++)
693 {
694 let square = squares.item(i);
695 if (square.id != this.getSquareId(move.start))
696 square.style.zIndex = "-1";
697 }
698 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
699 movingPiece.style.transitionDuration = "0.2s";
700 movingPiece.style.zIndex = "3000";
701 setTimeout( () => {
702 for (let i=0; i<squares.length; i++)
703 squares.item(i).style.zIndex = "auto";
704 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
705 this.play(move);
706 }, 200);
707 },
708 play: function(move, programmatic) {
709 if (!!programmatic) //computer or human opponent
710 {
711 this.animateMove(move);
712 return;
713 }
714 const oppCol = this.vr.getOppCol(this.vr.turn);
715 this.incheck = this.vr.getCheckSquares(move, oppCol); //is opponent in check?
716 // Not programmatic, or animation is over
717 if (this.mode == "human" && this.vr.turn == this.mycolor)
718 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
719 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
720 this.vr.play(move, "ingame");
721 if (this.mode == "human")
722 this.updateStorage(); //after our moves and opponent moves
723 const eog = this.vr.checkGameOver(this.vr.turn);
724 if (eog != "*")
725 this.endGame(eog);
726 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
727 setTimeout(this.playComputerMove, 500);
728 },
729 },
730 })