f5bef8effdeae9f4340862e8c0783302a7ff8054
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
);
243 if (!!this.vr
.reserve
)
245 let myReservePiecesArray
= [];
246 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
248 myReservePiecesArray
.push(h('div',
250 'class': {'board':true, ['board'+sizeY
]:true},
251 attrs: { id: this.getSquareId({x:sizeX
,y:i
}) }
256 'class': {"piece":true},
258 "src": "/images/pieces/" +
259 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
263 {style: { "padding-left":"40%"} },
264 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
268 let oppReservePiecesArray
= [];
269 const oppCol
= this.vr
.getOppCol(this.mycolor
);
270 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
272 oppReservePiecesArray
.push(h('div',
274 'class': {'board':true, ['board'+sizeY
]:true},
275 attrs: { id: this.getSquareId({x:sizeX
,y:i
}) }
280 'class': {"piece":true},
282 "src": "/images/pieces/" +
283 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
287 {style: { "padding-left":"40%"} },
288 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
292 let reserves
= h('div',
294 'class':{'game':true},
295 style: {"margin-bottom": "20px"},
300 'class': { 'row': true },
301 style: {"margin-bottom": "15px"},
306 { 'class': { 'row': true }},
307 oppReservePiecesArray
311 elementArray
.push(reserves
);
313 const eogMessage
= this.getEndgameMessage(this.score
);
317 attrs: { "id": "modal-eog", type: "checkbox" },
318 "class": { "modal": true },
322 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
327 "class": { "card": true, "smallpad": true },
332 attrs: { "for": "modal-eog" },
333 "class": { "modal-close": true },
338 "class": { "section": true },
339 domProps: { innerHTML: eogMessage
},
347 elementArray
= elementArray
.concat(modalEog
);
349 const modalNewgame
= [
352 attrs: { "id": "modal-newgame", type: "checkbox" },
353 "class": { "modal": true },
357 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
362 "class": { "card": true, "smallpad": true },
367 attrs: { "id": "close-newgame", "for": "modal-newgame" },
368 "class": { "modal-close": true },
373 "class": { "section": true },
374 domProps: { innerHTML: "New game" },
379 "class": { "section": true },
380 domProps: { innerHTML: "Waiting for opponent..." },
388 elementArray
= elementArray
.concat(modalNewgame
);
389 const actions
= h('div',
391 attrs: { "id": "actions" },
392 'class': { 'text-center': true },
396 elementArray
.push(actions
);
397 if (this.score
!= "*")
401 { attrs: { id: "pgn-div" } },
413 attrs: { id: "pgn-game" },
414 on: { click: this.download
},
416 innerHTML: this.pgnTxt
430 "col-md-offset-2":true,
432 "col-lg-offset-3":true,
434 // NOTE: click = mousedown + mouseup --> what about smartphone?!
436 mousedown: this.mousedown
,
437 mousemove: this.mousemove
,
438 mouseup: this.mouseup
,
439 touchdown: this.mousedown
,
440 touchmove: this.mousemove
,
441 touchup: this.mouseup
,
447 created: function() {
448 const url
= socketUrl
;
449 const continuation
= (localStorage
.getItem("variant") === variant
);
450 this.myid
= continuation
451 ? localStorage
.getItem("myid")
452 // random enough (TODO: function)
453 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
456 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
457 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
459 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
460 const socketOpenListener
= () => {
463 const fen
= localStorage
.getItem("fen");
464 const mycolor
= localStorage
.getItem("mycolor");
465 const oppid
= localStorage
.getItem("oppid");
466 const moves
= JSON
.parse(localStorage
.getItem("moves"));
467 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
468 // Send ping to server (answer pong if opponent is connected)
469 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
471 else if (localStorage
.getItem("newgame") === variant
)
473 // New game request has been cancelled on disconnect
475 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
478 const socketMessageListener
= msg
=> {
479 const data
= JSON
.parse(msg
.data
);
482 case "newgame": //opponent found
483 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
485 case "newmove": //..he played!
486 this.play(data
.move, "animate");
488 case "pong": //received if we sent a ping (game still alive on our side)
489 this.oppConnected
= true;
490 const L
= this.vr
.moves
.length
;
491 // Send our "last state" informations to opponent
492 this.conn
.send(JSON
.stringify({
495 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
499 case "lastate": //got opponent infos about last move (we might have resigned)
500 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
503 this.conn
.send(JSON
.stringify({
510 else if (data
.movesCount
< 0)
513 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
515 else if (data
.movesCount
< this.vr
.moves
.length
)
517 // We must tell last move to opponent
518 const L
= this.vr
.moves
.length
;
519 this.conn
.send(JSON
.stringify({
522 lastMove:this.vr
.moves
[L
-1],
526 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
527 this.play(data
.lastMove
, "animate");
529 case "resign": //..you won!
530 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
532 // TODO: also use (dis)connect info to count online players?
535 if (this.mode
== "human" && this.oppid
== data
.id
)
536 this.oppConnected
= (data
.code
== "connect");
540 const socketCloseListener
= () => {
541 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
542 this.conn
.addEventListener('open', socketOpenListener
);
543 this.conn
.addEventListener('message', socketMessageListener
);
544 this.conn
.addEventListener('close', socketCloseListener
);
546 this.conn
.onopen
= socketOpenListener
;
547 this.conn
.onmessage
= socketMessageListener
;
548 this.conn
.onclose
= socketCloseListener
;
551 download: function() {
552 let content
= document
.getElementById("pgn-game").innerHTML
;
553 content
= content
.replace(/<br>/g, "\n");
554 // Prepare and trigger download link
555 let downloadAnchor
= document
.getElementById("download");
556 downloadAnchor
.setAttribute("download", "game.pgn");
557 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
558 downloadAnchor
.click();
560 endGame: function(score
) {
562 let modalBox
= document
.getElementById("modal-eog");
563 modalBox
.checked
= true;
564 // Variants may have special PGN structure (so next function isn't defined here)
565 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
566 setTimeout(() => { modalBox
.checked
= false; }, 2000);
567 if (this.mode
== "human")
572 getEndgameMessage: function(score
) {
573 let eogMessage
= "Unfinished";
577 eogMessage
= "White win";
580 eogMessage
= "Black win";
588 toggleExpertMode: function() {
589 this.expert
= !this.expert
;
590 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
593 if (this.mode
== "human" && this.oppConnected
)
596 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
597 } catch (INVALID_STATE_ERR
) {
598 return; //socket is not ready (and not yet reconnected)
601 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
603 setStorage: function() {
604 localStorage
.setItem("myid", this.myid
);
605 localStorage
.setItem("variant", variant
);
606 localStorage
.setItem("mycolor", this.mycolor
);
607 localStorage
.setItem("oppid", this.oppid
);
608 localStorage
.setItem("fenStart", this.fenStart
);
609 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
610 localStorage
.setItem("fen", this.vr
.getFen());
612 updateStorage: function() {
613 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
614 localStorage
.setItem("fen", this.vr
.getFen());
616 clearStorage: function() {
617 delete localStorage
["variant"];
618 delete localStorage
["myid"];
619 delete localStorage
["mycolor"];
620 delete localStorage
["oppid"];
621 delete localStorage
["fenStart"];
622 delete localStorage
["fen"];
623 delete localStorage
["moves"];
625 clickGameSeek: function() {
626 if (this.mode
== "human")
627 return; //no newgame while playing
630 delete localStorage
["newgame"]; //cancel game seek
634 this.newGame("human");
636 clickComputerGame: function() {
637 if (this.mode
== "human")
638 return; //no newgame while playing
639 this.newGame("computer");
641 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
642 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
643 console
.log(fen
); //DEBUG
645 if (mode
=="human" && !oppId
)
647 const storageVariant
= localStorage
.getItem("variant");
648 if (!!storageVariant
&& storageVariant
!== variant
)
650 alert("Finish your " + storageVariant
+ " game first!");
653 // Send game request and wait..
654 localStorage
["newgame"] = variant
;
656 this.clearStorage(); //in case of
658 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
659 } catch (INVALID_STATE_ERR
) {
660 return; //nothing achieved
662 if (continuation
!== "reconnect") //TODO: bad HACK...
664 let modalBox
= document
.getElementById("modal-newgame");
665 modalBox
.checked
= true;
666 setTimeout(() => { modalBox
.checked
= false; }, 2000);
670 // random enough (TODO: function)
671 this.gameId
= (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
672 this.vr
= new VariantRules(fen
, moves
|| []);
673 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
675 this.incheck
= []; //in case of
676 this.fenStart
= continuation
677 ? localStorage
.getItem("fenStart")
678 : fen
.split(" ")[0]; //Only the position matters
684 // Not playing sound on game continuation:
685 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
686 document
.getElementById("modal-newgame").checked
= false;
689 this.oppConnected
= true;
690 this.mycolor
= color
;
692 if (!!moves
&& moves
.length
> 0) //imply continuation
694 const lastMove
= moves
[moves
.length
-1];
695 this.vr
.undo(lastMove
);
696 this.incheck
= this.vr
.getCheckSquares(lastMove
);
697 this.vr
.play(lastMove
, "ingame");
699 delete localStorage
["newgame"];
700 this.setStorage(); //in case of interruptions
702 else //against computer
704 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
705 if (this.mycolor
== 'b')
706 setTimeout(this.playComputerMove
, 500);
709 playComputerMove: function() {
710 const timeStart
= Date
.now();
711 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
712 const gameId
= this.gameId
; //to know if game was reset before timer end
715 if (gameId
!= this.gameId
)
716 return; //game stopped
717 const L
= this.vr
.moves
.length
;
718 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
719 this.vr
.shouldReturn
= true;
721 const compMove
= this.vr
.getComputerMove();
722 // (first move) HACK: avoid selecting elements before they appear on page:
723 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
724 setTimeout(() => this.play(compMove
, "animate"), delay
);
726 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
727 getSquareId: function(o
) {
728 // NOTE: a separator is required to allow any size of board
729 return "sq-" + o
.x
+ "-" + o
.y
;
732 getSquareFromId: function(id
) {
733 let idParts
= id
.split('-');
734 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
736 mousedown: function(e
) {
737 e
= e
|| window
.event
;
738 e
.preventDefault(); //disable native drag & drop
739 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
741 // Next few lines to center the piece on mouse cursor
742 let rect
= e
.target
.parentNode
.getBoundingClientRect();
744 x: rect
.x
+ rect
.width
/2,
745 y: rect
.y
+ rect
.width
/2,
746 id: e
.target
.parentNode
.id
748 this.selectedPiece
= e
.target
.cloneNode();
749 this.selectedPiece
.style
.position
= "absolute";
750 this.selectedPiece
.style
.top
= 0;
751 this.selectedPiece
.style
.display
= "inline-block";
752 this.selectedPiece
.style
.zIndex
= 3000;
753 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
754 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
755 ? this.vr
.getPossibleMovesFrom(startSquare
)
757 e
.target
.parentNode
.appendChild(this.selectedPiece
);
760 mousemove: function(e
) {
761 if (!this.selectedPiece
)
763 e
= e
|| window
.event
;
764 // If there is an active element, move it around
765 if (!!this.selectedPiece
)
767 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
768 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
771 mouseup: function(e
) {
772 if (!this.selectedPiece
)
774 e
= e
|| window
.event
;
775 // Read drop target (or parentElement, parentNode... if type == "img")
776 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
777 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
778 this.selectedPiece
.style
.zIndex
= 3000;
779 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
780 landing
= landing
.parentNode
;
781 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
783 // OK: process move attempt
784 let endSquare
= this.getSquareFromId(landing
.id
);
785 let moves
= this.findMatchingMoves(endSquare
);
786 this.possibleMoves
= [];
787 if (moves
.length
> 1)
788 this.choices
= moves
;
789 else if (moves
.length
==1)
791 // Else: impossible move
792 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
793 delete this.selectedPiece
;
794 this.selectedPiece
= null;
796 findMatchingMoves: function(endSquare
) {
797 // Run through moves list and return the matching set (if promotions...)
799 this.possibleMoves
.forEach(function(m
) {
800 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
805 animateMove: function(move) {
806 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
807 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
808 let rectStart
= startSquare
.getBoundingClientRect();
809 let rectEnd
= endSquare
.getBoundingClientRect();
810 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
812 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
813 // HACK for animation (with positive translate, image slides "under background"...)
814 // Possible improvement: just alter squares on the piece's way...
815 squares
= document
.getElementsByClassName("board");
816 for (let i
=0; i
<squares
.length
; i
++)
818 let square
= squares
.item(i
);
819 if (square
.id
!= this.getSquareId(move.start
))
820 square
.style
.zIndex
= "-1";
822 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
823 movingPiece
.style
.transitionDuration
= "0.2s";
824 movingPiece
.style
.zIndex
= "3000";
826 for (let i
=0; i
<squares
.length
; i
++)
827 squares
.item(i
).style
.zIndex
= "auto";
828 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
832 play: function(move, programmatic
) {
833 if (!!programmatic
) //computer or human opponent
835 this.animateMove(move);
838 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
839 // Not programmatic, or animation is over
840 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
841 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
842 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
843 this.vr
.play(move, "ingame");
844 if (this.mode
== "human")
845 this.updateStorage(); //after our moves and opponent moves
846 const eog
= this.vr
.checkGameOver();
849 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
850 setTimeout(this.playComputerMove
, 500);