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 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
246 let myReservePiecesArray
= [];
247 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
249 myReservePiecesArray
.push(h('div',
251 'class': {'board':true, ['board'+sizeY
]:true},
252 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
257 'class': {"piece":true},
259 "src": "/images/pieces/" +
260 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
264 {style: { "padding-left":"40%"} },
265 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
269 let oppReservePiecesArray
= [];
270 const oppCol
= this.vr
.getOppCol(this.mycolor
);
271 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
273 oppReservePiecesArray
.push(h('div',
275 'class': {'board':true, ['board'+sizeY
]:true},
276 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
281 'class': {"piece":true},
283 "src": "/images/pieces/" +
284 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
288 {style: { "padding-left":"40%"} },
289 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
293 let reserves
= h('div',
295 'class':{'game':true},
296 style: {"margin-bottom": "20px"},
301 'class': { 'row': true },
302 style: {"margin-bottom": "15px"},
307 { 'class': { 'row': true }},
308 oppReservePiecesArray
312 elementArray
.push(reserves
);
314 const eogMessage
= this.getEndgameMessage(this.score
);
318 attrs: { "id": "modal-eog", type: "checkbox" },
319 "class": { "modal": true },
323 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
328 "class": { "card": true, "smallpad": true },
333 attrs: { "for": "modal-eog" },
334 "class": { "modal-close": true },
339 "class": { "section": true },
340 domProps: { innerHTML: eogMessage
},
348 elementArray
= elementArray
.concat(modalEog
);
350 const modalNewgame
= [
353 attrs: { "id": "modal-newgame", type: "checkbox" },
354 "class": { "modal": true },
358 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
363 "class": { "card": true, "smallpad": true },
368 attrs: { "id": "close-newgame", "for": "modal-newgame" },
369 "class": { "modal-close": true },
374 "class": { "section": true },
375 domProps: { innerHTML: "New game" },
380 "class": { "section": true },
381 domProps: { innerHTML: "Waiting for opponent..." },
389 elementArray
= elementArray
.concat(modalNewgame
);
390 const actions
= h('div',
392 attrs: { "id": "actions" },
393 'class': { 'text-center': true },
397 elementArray
.push(actions
);
398 if (this.score
!= "*")
402 { attrs: { id: "pgn-div" } },
414 attrs: { id: "pgn-game" },
415 on: { click: this.download
},
416 domProps: { innerHTML: this.pgnTxt
}
423 else if (this.mode
!= "idle")
425 // Show current FEN (at least for debug)
428 { attrs: { id: "fen-div" } },
432 attrs: { id: "fen-string" },
433 domProps: { innerHTML: this.vr
.getBaseFen() }
446 "col-md-offset-2":true,
448 "col-lg-offset-3":true,
450 // NOTE: click = mousedown + mouseup
452 mousedown: this.mousedown
,
453 mousemove: this.mousemove
,
454 mouseup: this.mouseup
,
455 touchstart: this.mousedown
,
456 touchmove: this.mousemove
,
457 touchend: this.mouseup
,
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();
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
=> {});
475 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
476 const socketOpenListener
= () => {
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);
484 // Send ping to server (answer pong if opponent is connected)
485 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
487 else if (localStorage
.getItem("newgame") === variant
)
489 // New game request has been cancelled on disconnect
491 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
494 const socketMessageListener
= msg
=> {
495 const data
= JSON
.parse(msg
.data
);
498 case "newgame": //opponent found
499 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
501 case "newmove": //..he played!
502 this.play(data
.move, "animate");
504 case "pong": //received if we sent a ping (game still alive on our side)
505 this.oppConnected
= true;
506 const L
= this.vr
.moves
.length
;
507 // Send our "last state" informations to opponent
508 this.conn
.send(JSON
.stringify({
511 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
515 case "lastate": //got opponent infos about last move (we might have resigned)
516 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
519 this.conn
.send(JSON
.stringify({
526 else if (data
.movesCount
< 0)
529 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
531 else if (data
.movesCount
< this.vr
.moves
.length
)
533 // We must tell last move to opponent
534 const L
= this.vr
.moves
.length
;
535 this.conn
.send(JSON
.stringify({
538 lastMove:this.vr
.moves
[L
-1],
542 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
543 this.play(data
.lastMove
, "animate");
545 case "resign": //..you won!
546 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
548 // TODO: also use (dis)connect info to count online players?
551 if (this.mode
== "human" && this.oppid
== data
.id
)
552 this.oppConnected
= (data
.code
== "connect");
556 const socketCloseListener
= () => {
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
);
562 this.conn
.onopen
= socketOpenListener
;
563 this.conn
.onmessage
= socketMessageListener
;
564 this.conn
.onclose
= socketCloseListener
;
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();
576 endGame: function(score
) {
578 let modalBox
= document
.getElementById("modal-eog");
579 modalBox
.checked
= true;
580 // Variants may have special PGN structure (so next function isn't defined here)
581 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
582 setTimeout(() => { modalBox
.checked
= false; }, 2000);
583 if (this.mode
== "human")
588 getEndgameMessage: function(score
) {
589 let eogMessage
= "Unfinished";
593 eogMessage
= "White win";
596 eogMessage
= "Black win";
604 toggleExpertMode: function() {
605 this.expert
= !this.expert
;
606 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
609 if (this.mode
== "human" && this.oppConnected
)
612 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
613 } catch (INVALID_STATE_ERR
) {
614 return; //socket is not ready (and not yet reconnected)
617 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
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
));
626 localStorage
.setItem("fen", this.vr
.getFen());
628 updateStorage: function() {
629 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
630 localStorage
.setItem("fen", this.vr
.getFen());
632 clearStorage: function() {
633 delete localStorage
["variant"];
634 delete localStorage
["myid"];
635 delete localStorage
["mycolor"];
636 delete localStorage
["oppid"];
637 delete localStorage
["fenStart"];
638 delete localStorage
["fen"];
639 delete localStorage
["moves"];
641 clickGameSeek: function() {
642 if (this.mode
== "human")
643 return; //no newgame while playing
646 delete localStorage
["newgame"]; //cancel game seek
650 this.newGame("human");
652 clickComputerGame: function() {
653 if (this.mode
== "human")
654 return; //no newgame while playing
655 this.newGame("computer");
657 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
658 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
659 console
.log(fen
); //DEBUG
661 if (mode
=="human" && !oppId
)
663 const storageVariant
= localStorage
.getItem("variant");
664 if (!!storageVariant
&& storageVariant
!== variant
)
666 alert("Finish your " + storageVariant
+ " game first!");
669 // Send game request and wait..
670 localStorage
["newgame"] = variant
;
672 this.clearStorage(); //in case of
674 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
675 } catch (INVALID_STATE_ERR
) {
676 return; //nothing achieved
678 if (continuation
!== "reconnect") //TODO: bad HACK...
680 let modalBox
= document
.getElementById("modal-newgame");
681 modalBox
.checked
= true;
682 setTimeout(() => { modalBox
.checked
= false; }, 2000);
686 // random enough (TODO: function)
687 this.gameId
= (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
688 this.vr
= new VariantRules(fen
, moves
|| []);
689 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
691 this.incheck
= []; //in case of
692 this.fenStart
= continuation
693 ? localStorage
.getItem("fenStart")
694 : fen
.split(" ")[0]; //Only the position matters
700 // Not playing sound on game continuation:
701 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
702 document
.getElementById("modal-newgame").checked
= false;
705 this.oppConnected
= true;
706 this.mycolor
= color
;
708 if (!!moves
&& moves
.length
> 0) //imply continuation
710 const lastMove
= moves
[moves
.length
-1];
711 this.vr
.undo(lastMove
);
712 this.incheck
= this.vr
.getCheckSquares(lastMove
);
713 this.vr
.play(lastMove
, "ingame");
715 delete localStorage
["newgame"];
716 this.setStorage(); //in case of interruptions
718 else //against computer
720 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
721 if (this.mycolor
== 'b')
722 setTimeout(this.playComputerMove
, 500);
725 playComputerMove: function() {
726 const timeStart
= Date
.now();
727 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
728 const gameId
= this.gameId
; //to know if game was reset before timer end
731 if (gameId
!= this.gameId
)
732 return; //game stopped
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;
737 const compMove
= this.vr
.getComputerMove();
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
);
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
;
748 getSquareFromId: function(id
) {
749 let idParts
= id
.split('-');
750 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
752 mousedown: function(e
) {
753 e
= e
|| window
.event
;
756 while (!ingame
&& elem
!== null)
758 if (elem
.classList
.contains("game"))
763 elem
= elem
.parentElement
;
765 if (!ingame
) //let default behavior (click on button...)
767 e
.preventDefault(); //disable native drag & drop
768 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
770 // Next few lines to center the piece on mouse cursor
771 let rect
= e
.target
.parentNode
.getBoundingClientRect();
773 x: rect
.x
+ rect
.width
/2,
774 y: rect
.y
+ rect
.width
/2,
775 id: e
.target
.parentNode
.id
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
);
783 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
784 ? this.vr
.getPossibleMovesFrom(startSquare
)
786 // Next line add moving piece just after current image (required for Crazyhouse reserve)
787 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
790 mousemove: function(e
) {
791 if (!this.selectedPiece
)
793 e
= e
|| window
.event
;
794 // If there is an active element, move it around
795 if (!!this.selectedPiece
)
797 const [offsetX
,offsetY
] = !!e
.clientX
798 ? [e
.clientX
,e
.clientY
] //desktop browser
799 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
800 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
801 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
804 mouseup: function(e
) {
805 if (!this.selectedPiece
)
807 e
= e
|| window
.event
;
808 // Read drop target (or parentElement, parentNode... if type == "img")
809 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
810 const [offsetX
,offsetY
] = !!e
.clientX
811 ? [e
.clientX
,e
.clientY
]
812 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
813 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
814 this.selectedPiece
.style
.zIndex
= 3000;
815 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
816 landing
= landing
.parentNode
;
817 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
819 // OK: process move attempt
820 let endSquare
= this.getSquareFromId(landing
.id
);
821 let moves
= this.findMatchingMoves(endSquare
);
822 this.possibleMoves
= [];
823 if (moves
.length
> 1)
824 this.choices
= moves
;
825 else if (moves
.length
==1)
827 // Else: impossible move
828 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
829 delete this.selectedPiece
;
830 this.selectedPiece
= null;
832 findMatchingMoves: function(endSquare
) {
833 // Run through moves list and return the matching set (if promotions...)
835 this.possibleMoves
.forEach(function(m
) {
836 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
841 animateMove: function(move) {
842 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
843 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
844 let rectStart
= startSquare
.getBoundingClientRect();
845 let rectEnd
= endSquare
.getBoundingClientRect();
846 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
848 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
849 // HACK for animation (with positive translate, image slides "under background"...)
850 // Possible improvement: just alter squares on the piece's way...
851 squares
= document
.getElementsByClassName("board");
852 for (let i
=0; i
<squares
.length
; i
++)
854 let square
= squares
.item(i
);
855 if (square
.id
!= this.getSquareId(move.start
))
856 square
.style
.zIndex
= "-1";
858 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
859 movingPiece
.style
.transitionDuration
= "0.2s";
860 movingPiece
.style
.zIndex
= "3000";
862 for (let i
=0; i
<squares
.length
; i
++)
863 squares
.item(i
).style
.zIndex
= "auto";
864 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
868 play: function(move, programmatic
) {
869 if (!!programmatic
) //computer or human opponent
871 this.animateMove(move);
874 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
875 // Not programmatic, or animation is over
876 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
877 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
878 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
879 this.vr
.play(move, "ingame");
880 if (this.mode
== "human")
881 this.updateStorage(); //after our moves and opponent moves
882 const eog
= this.vr
.checkGameOver();
885 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
886 setTimeout(this.playComputerMove
, 500);