1 Vue
.component('my-game', {
4 vr: null, //object to check moves, store them, FEN..
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
11 score: "*", //'*' means 'unfinished'
12 mode: "idle", //human, computer or idle (when not playing)
13 oppid: "", //opponent ID in case of HH game
19 expert: document
.cookie
.length
>0 ? document
.cookie
.substr(-1)=="1" : false,
20 gameId: "", //used to limit computer moves' time
24 const [sizeX
,sizeY
] = VariantRules
.size
;
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; });
28 // Also precompute in-check squares
29 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
30 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
31 let elementArray
= [];
32 const playingHuman
= (this.mode
== "human");
33 const playingComp
= (this.mode
== "computer");
37 on: { click: this.clickGameSeek
},
38 attrs: { "aria-label": 'New game VS human' },
41 "bottom": true, //display below
43 "playing": playingHuman
,
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
49 on: { click: this.clickComputerGame
},
50 attrs: { "aria-label": 'New game VS computer' },
54 "playing": playingComp
,
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
61 const square00
= document
.getElementById("sq-0-0");
62 const squareWidth
= !!square00
63 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
65 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
66 if (this.mode
== "human")
68 let connectedIndic
= h(
74 "connected": this.oppConnected
,
75 "disconnected": !this.oppConnected
,
78 "width": indicWidth
+ "px",
79 "height": indicWidth
+ "px",
83 elementArray
.push(connectedIndic
);
91 "white-turn": this.vr
.turn
=="w",
92 "black-turn": this.vr
.turn
=="b",
95 "width": indicWidth
+ "px",
96 "height": indicWidth
+ "px",
100 elementArray
.push(turnIndic
);
101 let expertSwitch
= h(
104 on: { click: this.toggleExpertMode
},
105 attrs: { "aria-label": 'Toggle expert mode' },
108 "topindicator": true,
110 "expert-switch": true,
111 "expert-mode": this.expert
,
114 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
116 elementArray
.push(expertSwitch
);
117 let choices
= h('div',
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
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",
128 this.choices
.map( m
=> { //a "choice" is a move
133 ['board'+sizeY
]: true,
136 'width': (100/this.choices
.length
) + "%",
137 'padding-bottom': (100/this.choices
.length
) + "%",
142 attrs: { "src": '/images/pieces/' +
143 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
144 'class': { 'choice-piece': true },
145 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
151 // Create board element (+ reserves if needed by variant or mode)
152 let gameDiv
= h('div',
154 'class': { 'game': true },
156 [_
.range(sizeX
).map(i
=> {
157 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
164 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
166 _
.range(sizeY
).map(j
=> {
167 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
169 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
177 'ghost': !!this.selectedPiece
178 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
181 src: "/images/pieces/" +
182 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
188 if (!this.expert
&& hintSquares
[ci
][cj
])
198 src: "/images/mark.svg",
204 const lm
= this.vr
.lastMove
;
205 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
211 ['board'+sizeY
]: true,
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
],
218 id: this.getSquareId({x:ci
,y:cj
}),
227 if (this.mode
!= "idle")
232 on: { click: this.resign
},
233 attrs: { "aria-label": 'Resign' },
239 [h('i', { 'class': { "material-icons": true } }, "flag")])
242 elementArray
.push(gameDiv
);
245 // let reserve = h('div',
246 // {'class':{'game':true}}, [
248 // { 'class': { 'row': true }},
251 // {'class':{'board':true}},
252 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
258 // elementArray.push(reserve);
260 const eogMessage
= this.getEndgameMessage(this.score
);
264 attrs: { "id": "modal-eog", type: "checkbox" },
265 "class": { "modal": true },
269 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
274 "class": { "card": true, "smallpad": true },
279 attrs: { "for": "modal-eog" },
280 "class": { "modal-close": true },
285 "class": { "section": true },
286 domProps: { innerHTML: eogMessage
},
294 elementArray
= elementArray
.concat(modalEog
);
296 const modalNewgame
= [
299 attrs: { "id": "modal-newgame", type: "checkbox" },
300 "class": { "modal": true },
304 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
309 "class": { "card": true, "smallpad": true },
314 attrs: { "id": "close-newgame", "for": "modal-newgame" },
315 "class": { "modal-close": true },
320 "class": { "section": true },
321 domProps: { innerHTML: "New game" },
326 "class": { "section": true },
327 domProps: { innerHTML: "Waiting for opponent..." },
335 elementArray
= elementArray
.concat(modalNewgame
);
336 const actions
= h('div',
338 attrs: { "id": "actions" },
339 'class': { 'text-center': true },
343 elementArray
.push(actions
);
344 if (this.score
!= "*")
348 { attrs: { id: "pgn-div" } },
360 attrs: { id: "pgn-game" },
361 on: { click: this.download
},
363 innerHTML: this.pgnTxt
377 "col-md-offset-2":true,
379 "col-lg-offset-3":true,
381 // NOTE: click = mousedown + mouseup --> what about smartphone?!
383 mousedown: this.mousedown
,
384 mousemove: this.mousemove
,
385 mouseup: this.mouseup
,
386 touchdown: this.mousedown
,
387 touchmove: this.mousemove
,
388 touchup: this.mouseup
,
394 created: function() {
395 const url
= socketUrl
;
396 const continuation
= (localStorage
.getItem("variant") === variant
);
397 this.myid
= continuation
398 ? localStorage
.getItem("myid")
399 // random enough (TODO: function)
400 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
403 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
404 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
406 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
407 const socketOpenListener
= () => {
410 const fen
= localStorage
.getItem("fen");
411 const mycolor
= localStorage
.getItem("mycolor");
412 const oppid
= localStorage
.getItem("oppid");
413 const moves
= JSON
.parse(localStorage
.getItem("moves"));
414 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
415 // Send ping to server (answer pong if opponent is connected)
416 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
418 else if (localStorage
.getItem("newgame") === variant
)
420 // New game request has been cancelled on disconnect
422 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
425 const socketMessageListener
= msg
=> {
426 const data
= JSON
.parse(msg
.data
);
429 case "newgame": //opponent found
430 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
432 case "newmove": //..he played!
433 this.play(data
.move, "animate");
435 case "pong": //received if we sent a ping (game still alive on our side)
436 this.oppConnected
= true;
437 const L
= this.vr
.moves
.length
;
438 // Send our "last state" informations to opponent
439 this.conn
.send(JSON
.stringify({
442 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
446 case "lastate": //got opponent infos about last move (we might have resigned)
447 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
450 this.conn
.send(JSON
.stringify({
457 else if (data
.movesCount
< 0)
460 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
462 else if (data
.movesCount
< this.vr
.moves
.length
)
464 // We must tell last move to opponent
465 const L
= this.vr
.moves
.length
;
466 this.conn
.send(JSON
.stringify({
469 lastMove:this.vr
.moves
[L
-1],
473 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
474 this.play(data
.lastMove
, "animate");
476 case "resign": //..you won!
477 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
479 // TODO: also use (dis)connect info to count online players?
482 if (this.mode
== "human" && this.oppid
== data
.id
)
483 this.oppConnected
= (data
.code
== "connect");
487 const socketCloseListener
= () => {
488 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
489 this.conn
.addEventListener('open', socketOpenListener
);
490 this.conn
.addEventListener('message', socketMessageListener
);
491 this.conn
.addEventListener('close', socketCloseListener
);
493 this.conn
.onopen
= socketOpenListener
;
494 this.conn
.onmessage
= socketMessageListener
;
495 this.conn
.onclose
= socketCloseListener
;
498 download: function() {
499 let content
= document
.getElementById("pgn-game").innerHTML
;
500 content
= content
.replace(/<br>/g, "\n");
501 // Prepare and trigger download link
502 let downloadAnchor
= document
.getElementById("download");
503 downloadAnchor
.setAttribute("download", "game.pgn");
504 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
505 downloadAnchor
.click();
507 endGame: function(score
) {
509 let modalBox
= document
.getElementById("modal-eog");
510 modalBox
.checked
= true;
511 // Variants may have special PGN structure (so next function isn't defined here)
512 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
513 setTimeout(() => { modalBox
.checked
= false; }, 2000);
514 if (this.mode
== "human")
519 getEndgameMessage: function(score
) {
520 let eogMessage
= "Unfinished";
524 eogMessage
= "White win";
527 eogMessage
= "Black win";
535 toggleExpertMode: function() {
536 this.expert
= !this.expert
;
537 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
540 if (this.mode
== "human" && this.oppConnected
)
543 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
544 } catch (INVALID_STATE_ERR
) {
545 return; //socket is not ready (and not yet reconnected)
548 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
550 setStorage: function() {
551 localStorage
.setItem("myid", this.myid
);
552 localStorage
.setItem("variant", variant
);
553 localStorage
.setItem("mycolor", this.mycolor
);
554 localStorage
.setItem("oppid", this.oppid
);
555 localStorage
.setItem("fenStart", this.fenStart
);
556 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
557 localStorage
.setItem("fen", this.vr
.getFen());
559 updateStorage: function() {
560 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
561 localStorage
.setItem("fen", this.vr
.getFen());
563 clearStorage: function() {
564 delete localStorage
["variant"];
565 delete localStorage
["myid"];
566 delete localStorage
["mycolor"];
567 delete localStorage
["oppid"];
568 delete localStorage
["fenStart"];
569 delete localStorage
["fen"];
570 delete localStorage
["moves"];
572 clickGameSeek: function() {
573 if (this.mode
== "human")
574 return; //no newgame while playing
577 delete localStorage
["newgame"]; //cancel game seek
581 this.newGame("human");
583 clickComputerGame: function() {
584 if (this.mode
== "human")
585 return; //no newgame while playing
586 this.newGame("computer");
588 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
589 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
590 console
.log(fen
); //DEBUG
592 if (mode
=="human" && !oppId
)
594 const storageVariant
= localStorage
.getItem("variant");
595 if (!!storageVariant
&& storageVariant
!== variant
)
597 alert("Finish your " + storageVariant
+ " game first!");
600 // Send game request and wait..
601 localStorage
["newgame"] = variant
;
603 this.clearStorage(); //in case of
605 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
606 } catch (INVALID_STATE_ERR
) {
607 return; //nothing achieved
609 if (continuation
!== "reconnect") //TODO: bad HACK...
611 let modalBox
= document
.getElementById("modal-newgame");
612 modalBox
.checked
= true;
613 setTimeout(() => { modalBox
.checked
= false; }, 2000);
617 // random enough (TODO: function)
618 this.gameId
= (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
619 this.vr
= new VariantRules(fen
, moves
|| []);
620 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
622 this.incheck
= []; //in case of
623 this.fenStart
= continuation
624 ? localStorage
.getItem("fenStart")
625 : fen
.split(" ")[0]; //Only the position matters
631 // Not playing sound on game continuation:
632 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
633 document
.getElementById("modal-newgame").checked
= false;
636 this.oppConnected
= true;
637 this.mycolor
= color
;
639 if (!!moves
&& moves
.length
> 0) //imply continuation
641 const lastMove
= moves
[moves
.length
-1];
642 this.vr
.undo(lastMove
);
643 this.incheck
= this.vr
.getCheckSquares(lastMove
);
644 this.vr
.play(lastMove
, "ingame");
646 delete localStorage
["newgame"];
647 this.setStorage(); //in case of interruptions
649 else //against computer
651 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
652 if (this.mycolor
== 'b')
653 setTimeout(this.playComputerMove
, 500);
656 playComputerMove: function() {
657 const timeStart
= Date
.now();
658 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
659 const gameId
= this.gameId
; //to know if game was reset before timer end
662 if (gameId
!= this.gameId
)
663 return; //game stopped
664 const L
= this.vr
.moves
.length
;
665 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
666 this.vr
.shouldReturn
= true;
668 const compMove
= this.vr
.getComputerMove();
669 // (first move) HACK: avoid selecting elements before they appear on page:
670 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
671 setTimeout(() => this.play(compMove
, "animate"), delay
);
673 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
674 getSquareId: function(o
) {
675 // NOTE: a separator is required to allow any size of board
676 return "sq-" + o
.x
+ "-" + o
.y
;
679 getSquareFromId: function(id
) {
680 let idParts
= id
.split('-');
681 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
683 mousedown: function(e
) {
684 e
= e
|| window
.event
;
685 e
.preventDefault(); //disable native drag & drop
686 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
688 // Next few lines to center the piece on mouse cursor
689 let rect
= e
.target
.parentNode
.getBoundingClientRect();
691 x: rect
.x
+ rect
.width
/2,
692 y: rect
.y
+ rect
.width
/2,
693 id: e
.target
.parentNode
.id
695 this.selectedPiece
= e
.target
.cloneNode();
696 this.selectedPiece
.style
.position
= "absolute";
697 this.selectedPiece
.style
.top
= 0;
698 this.selectedPiece
.style
.display
= "inline-block";
699 this.selectedPiece
.style
.zIndex
= 3000;
700 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
701 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
702 ? this.vr
.getPossibleMovesFrom(startSquare
)
704 e
.target
.parentNode
.appendChild(this.selectedPiece
);
707 mousemove: function(e
) {
708 if (!this.selectedPiece
)
710 e
= e
|| window
.event
;
711 // If there is an active element, move it around
712 if (!!this.selectedPiece
)
714 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
715 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
718 mouseup: function(e
) {
719 if (!this.selectedPiece
)
721 e
= e
|| window
.event
;
722 // Read drop target (or parentElement, parentNode... if type == "img")
723 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
724 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
725 this.selectedPiece
.style
.zIndex
= 3000;
726 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
727 landing
= landing
.parentNode
;
728 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
730 // OK: process move attempt
731 let endSquare
= this.getSquareFromId(landing
.id
);
732 let moves
= this.findMatchingMoves(endSquare
);
733 this.possibleMoves
= [];
734 if (moves
.length
> 1)
735 this.choices
= moves
;
736 else if (moves
.length
==1)
738 // Else: impossible move
739 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
740 delete this.selectedPiece
;
741 this.selectedPiece
= null;
743 findMatchingMoves: function(endSquare
) {
744 // Run through moves list and return the matching set (if promotions...)
746 this.possibleMoves
.forEach(function(m
) {
747 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
752 animateMove: function(move) {
753 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
754 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
755 let rectStart
= startSquare
.getBoundingClientRect();
756 let rectEnd
= endSquare
.getBoundingClientRect();
757 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
759 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
760 // HACK for animation (with positive translate, image slides "under background"...)
761 // Possible improvement: just alter squares on the piece's way...
762 squares
= document
.getElementsByClassName("board");
763 for (let i
=0; i
<squares
.length
; i
++)
765 let square
= squares
.item(i
);
766 if (square
.id
!= this.getSquareId(move.start
))
767 square
.style
.zIndex
= "-1";
769 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
770 movingPiece
.style
.transitionDuration
= "0.2s";
771 movingPiece
.style
.zIndex
= "3000";
773 for (let i
=0; i
<squares
.length
; i
++)
774 squares
.item(i
).style
.zIndex
= "auto";
775 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
779 play: function(move, programmatic
) {
780 if (!!programmatic
) //computer or human opponent
782 this.animateMove(move);
785 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
786 // Not programmatic, or animation is over
787 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
788 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
789 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
790 this.vr
.play(move, "ingame");
791 if (this.mode
== "human")
792 this.updateStorage(); //after our moves and opponent moves
793 const eog
= this.vr
.checkGameOver();
796 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
797 setTimeout(this.playComputerMove
, 500);