fcae2f11571facd13ad90f55965209f1eeb9d2a0
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,
23 const [sizeX
,sizeY
] = VariantRules
.size
;
24 // Precompute hints squares to facilitate rendering
25 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
26 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
27 // Also precompute in-check squares
28 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
29 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
30 let elementArray
= [];
31 const playingHuman
= (this.mode
== "human");
32 const playingComp
= (this.mode
== "computer");
36 on: { click: this.clickGameSeek
},
37 attrs: { "aria-label": 'New game VS human' },
40 "bottom": true, //display below
42 "playing": playingHuman
,
45 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
48 on: { click: this.clickComputerGame
},
49 attrs: { "aria-label": 'New game VS computer' },
53 "playing": playingComp
,
56 [h('i', { 'class': { "material-icons": true } }, "computer")])
60 const square00
= document
.getElementById("sq-0-0");
61 const squareWidth
= !!square00
62 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
64 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
65 if (this.mode
== "human")
67 let connectedIndic
= h(
73 "connected": this.oppConnected
,
74 "disconnected": !this.oppConnected
,
77 "width": indicWidth
+ "px",
78 "height": indicWidth
+ "px",
82 elementArray
.push(connectedIndic
);
90 "white-turn": this.vr
.turn
=="w",
91 "black-turn": this.vr
.turn
=="b",
94 "width": indicWidth
+ "px",
95 "height": indicWidth
+ "px",
99 elementArray
.push(turnIndic
);
100 let expertSwitch
= h(
103 on: { click: this.toggleExpertMode
},
104 attrs: { "aria-label": 'Toggle expert mode' },
107 "topindicator": true,
109 "expert-switch": true,
110 "expert-mode": this.expert
,
113 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
115 elementArray
.push(expertSwitch
);
116 let choices
= h('div',
118 attrs: { "id": "choices" },
119 'class': { 'row': true },
121 "display": this.choices
.length
>0?"block":"none",
122 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
123 "width": (this.choices
.length
* squareWidth
) + "px",
124 "height": squareWidth
+ "px",
127 this.choices
.map( m
=> { //a "choice" is a move
132 ['board'+sizeX
]: true,
135 'width': (100/this.choices
.length
) + "%",
136 'padding-bottom': (100/this.choices
.length
) + "%",
141 attrs: { "src": '/images/pieces/' +
142 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
143 'class': { 'choice-piece': true },
144 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
150 // Create board element (+ reserves if needed by variant or mode)
151 let gameDiv
= h('div',
153 'class': { 'game': true },
155 [_
.range(sizeX
).map(i
=> {
156 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
163 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
165 _
.range(sizeY
).map(j
=> {
166 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
168 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
176 'ghost': !!this.selectedPiece
177 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
180 src: "/images/pieces/" +
181 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
187 if (!this.expert
&& hintSquares
[ci
][cj
])
197 src: "/images/mark.svg",
203 const lm
= this.vr
.lastMove
;
204 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
210 ['board'+sizeX
]: true,
211 'light-square': (i
+j
)%2==0 && (this.expert
|| !highlight
),
212 'dark-square': (i
+j
)%2==1 && (this.expert
|| !highlight
),
213 'highlight': !this.expert
&& highlight
,
214 'incheck': !this.expert
&& incheckSq
[ci
][cj
],
217 id: this.getSquareId({x:ci
,y:cj
}),
226 if (this.mode
!= "idle")
231 on: { click: this.resign
},
232 attrs: { "aria-label": 'Resign' },
238 [h('i', { 'class': { "material-icons": true } }, "flag")])
241 elementArray
.push(gameDiv
);
244 // let reserve = h('div',
245 // {'class':{'game':true}}, [
247 // { 'class': { 'row': true }},
250 // {'class':{'board':true}},
251 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
257 // elementArray.push(reserve);
259 const eogMessage
= this.getEndgameMessage(this.score
);
263 attrs: { "id": "modal-eog", type: "checkbox" },
264 "class": { "modal": true },
268 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
273 "class": { "card": true, "smallpad": true },
278 attrs: { "for": "modal-eog" },
279 "class": { "modal-close": true },
284 "class": { "section": true },
285 domProps: { innerHTML: eogMessage
},
293 elementArray
= elementArray
.concat(modalEog
);
295 const modalNewgame
= [
298 attrs: { "id": "modal-newgame", type: "checkbox" },
299 "class": { "modal": true },
303 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
308 "class": { "card": true, "smallpad": true },
313 attrs: { "id": "close-newgame", "for": "modal-newgame" },
314 "class": { "modal-close": true },
319 "class": { "section": true },
320 domProps: { innerHTML: "New game" },
325 "class": { "section": true },
326 domProps: { innerHTML: "Waiting for opponent..." },
334 elementArray
= elementArray
.concat(modalNewgame
);
335 const actions
= h('div',
337 attrs: { "id": "actions" },
338 'class': { 'text-center': true },
342 elementArray
.push(actions
);
343 if (this.score
!= "*")
347 { attrs: { id: "pgn-div" } },
359 attrs: { id: "pgn-game" },
360 on: { click: this.download
},
362 innerHTML: this.pgnTxt
376 "col-md-offset-2":true,
378 "col-lg-offset-3":true,
380 // NOTE: click = mousedown + mouseup --> what about smartphone?!
382 mousedown: this.mousedown
,
383 mousemove: this.mousemove
,
384 mouseup: this.mouseup
,
385 touchdown: this.mousedown
,
386 touchmove: this.mousemove
,
387 touchup: this.mouseup
,
393 created: function() {
394 const url
= socketUrl
;
395 const continuation
= (localStorage
.getItem("variant") === variant
);
396 this.myid
= continuation
397 ? localStorage
.getItem("myid")
398 // random enough (TODO: function)
399 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
402 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
403 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
405 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
406 const socketOpenListener
= () => {
409 const fen
= localStorage
.getItem("fen");
410 const mycolor
= localStorage
.getItem("mycolor");
411 const oppid
= localStorage
.getItem("oppid");
412 const moves
= JSON
.parse(localStorage
.getItem("moves"));
413 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
414 // Send ping to server (answer pong if opponent is connected)
415 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
417 else if (localStorage
.getItem("newgame") === variant
)
419 // New game request has been cancelled on disconnect
421 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
424 const socketMessageListener
= msg
=> {
425 const data
= JSON
.parse(msg
.data
);
428 case "newgame": //opponent found
429 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
431 case "newmove": //..he played!
432 this.play(data
.move, "animate");
434 case "pong": //received if we sent a ping (game still alive on our side)
435 this.oppConnected
= true;
436 const L
= this.vr
.moves
.length
;
437 // Send our "last state" informations to opponent
438 this.conn
.send(JSON
.stringify({
441 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
445 case "lastate": //got opponent infos about last move (we might have resigned)
446 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
449 this.conn
.send(JSON
.stringify({
456 else if (data
.movesCount
< 0)
459 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
461 else if (data
.movesCount
< this.vr
.moves
.length
)
463 // We must tell last move to opponent
464 const L
= this.vr
.moves
.length
;
465 this.conn
.send(JSON
.stringify({
468 lastMove:this.vr
.moves
[L
-1],
472 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
473 this.play(data
.lastMove
, "animate");
475 case "resign": //..you won!
476 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
478 // TODO: also use (dis)connect info to count online players?
481 if (this.mode
== "human" && this.oppid
== data
.id
)
482 this.oppConnected
= (data
.code
== "connect");
486 const socketCloseListener
= () => {
487 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
488 this.conn
.addEventListener('open', socketOpenListener
);
489 this.conn
.addEventListener('message', socketMessageListener
);
490 this.conn
.addEventListener('close', socketCloseListener
);
492 this.conn
.onopen
= socketOpenListener
;
493 this.conn
.onmessage
= socketMessageListener
;
494 this.conn
.onclose
= socketCloseListener
;
497 download: function() {
498 let content
= document
.getElementById("pgn-game").innerHTML
;
499 content
= content
.replace(/<br>/g, "\n");
500 // Prepare and trigger download link
501 let downloadAnchor
= document
.getElementById("download");
502 downloadAnchor
.setAttribute("download", "game.pgn");
503 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
504 downloadAnchor
.click();
506 endGame: function(score
) {
508 let modalBox
= document
.getElementById("modal-eog");
509 modalBox
.checked
= true;
510 // Variants may have special PGN structure (so next function isn't defined here)
511 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
512 setTimeout(() => { modalBox
.checked
= false; }, 2000);
513 if (this.mode
== "human")
518 getEndgameMessage: function(score
) {
519 let eogMessage
= "Unfinished";
523 eogMessage
= "White win";
526 eogMessage
= "Black win";
534 toggleExpertMode: function() {
535 this.expert
= !this.expert
;
536 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
539 if (this.mode
== "human" && this.oppConnected
)
542 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
543 } catch (INVALID_STATE_ERR
) {
544 return; //socket is not ready (and not yet reconnected)
547 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
549 setStorage: function() {
550 localStorage
.setItem("myid", this.myid
);
551 localStorage
.setItem("variant", variant
);
552 localStorage
.setItem("mycolor", this.mycolor
);
553 localStorage
.setItem("oppid", this.oppid
);
554 localStorage
.setItem("fenStart", this.fenStart
);
555 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
556 localStorage
.setItem("fen", this.vr
.getFen());
558 updateStorage: function() {
559 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
560 localStorage
.setItem("fen", this.vr
.getFen());
562 clearStorage: function() {
563 delete localStorage
["variant"];
564 delete localStorage
["myid"];
565 delete localStorage
["mycolor"];
566 delete localStorage
["oppid"];
567 delete localStorage
["fenStart"];
568 delete localStorage
["fen"];
569 delete localStorage
["moves"];
571 clickGameSeek: function() {
572 if (this.mode
== "human")
573 return; //no newgame while playing
576 delete localStorage
["newgame"]; //cancel game seek
580 this.newGame("human");
582 clickComputerGame: function() {
583 if (this.mode
== "human")
584 return; //no newgame while playing
585 this.newGame("computer");
587 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
588 //const fen = "1n2T1n0/p2pO2p/1s1k1s2/8/3S2p1/2U2cO1/P3PuPP/3K1BR1 0100";
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 this.vr
= new VariantRules(fen
, moves
|| []);
618 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
620 this.incheck
= []; //in case of
621 this.fenStart
= continuation
622 ? localStorage
.getItem("fenStart")
623 : fen
.split(" ")[0]; //Only the position matters
629 // Not playing sound on game continuation:
630 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
631 document
.getElementById("modal-newgame").checked
= false;
634 this.oppConnected
= true;
635 this.mycolor
= color
;
637 if (!!moves
&& moves
.length
> 0) //imply continuation
639 const lastMove
= moves
[moves
.length
-1];
640 this.vr
.undo(lastMove
);
641 this.incheck
= this.vr
.getCheckSquares(lastMove
);
642 this.vr
.play(lastMove
, "ingame");
644 delete localStorage
["newgame"];
645 this.setStorage(); //in case of interruptions
647 else //against computer
649 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
650 if (this.mycolor
== 'b')
651 setTimeout(this.playComputerMove
, 500);
654 playComputerMove: function() {
655 const timeStart
= Date
.now();
656 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
659 const L
= this.vr
.moves
.length
;
660 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
661 this.vr
.shouldReturn
= true;
663 const compMove
= this.vr
.getComputerMove();
664 // (first move) HACK: avoid selecting elements before they appear on page:
665 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
666 setTimeout(() => this.play(compMove
, "animate"), delay
);
668 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
669 getSquareId: function(o
) {
670 // NOTE: a separator is required to allow any size of board
671 return "sq-" + o
.x
+ "-" + o
.y
;
674 getSquareFromId: function(id
) {
675 let idParts
= id
.split('-');
676 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
678 mousedown: function(e
) {
679 e
= e
|| window
.event
;
680 e
.preventDefault(); //disable native drag & drop
681 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
683 // Next few lines to center the piece on mouse cursor
684 let rect
= e
.target
.parentNode
.getBoundingClientRect();
686 x: rect
.x
+ rect
.width
/2,
687 y: rect
.y
+ rect
.width
/2,
688 id: e
.target
.parentNode
.id
690 this.selectedPiece
= e
.target
.cloneNode();
691 this.selectedPiece
.style
.position
= "absolute";
692 this.selectedPiece
.style
.top
= 0;
693 this.selectedPiece
.style
.display
= "inline-block";
694 this.selectedPiece
.style
.zIndex
= 3000;
695 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
696 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
697 ? this.vr
.getPossibleMovesFrom(startSquare
)
699 e
.target
.parentNode
.appendChild(this.selectedPiece
);
702 mousemove: function(e
) {
703 if (!this.selectedPiece
)
705 e
= e
|| window
.event
;
706 // If there is an active element, move it around
707 if (!!this.selectedPiece
)
709 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
710 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
713 mouseup: function(e
) {
714 if (!this.selectedPiece
)
716 e
= e
|| window
.event
;
717 // Read drop target (or parentElement, parentNode... if type == "img")
718 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
719 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
720 this.selectedPiece
.style
.zIndex
= 3000;
721 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
722 landing
= landing
.parentNode
;
723 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
725 // OK: process move attempt
726 let endSquare
= this.getSquareFromId(landing
.id
);
727 let moves
= this.findMatchingMoves(endSquare
);
728 this.possibleMoves
= [];
729 if (moves
.length
> 1)
730 this.choices
= moves
;
731 else if (moves
.length
==1)
733 // Else: impossible move
734 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
735 delete this.selectedPiece
;
736 this.selectedPiece
= null;
738 findMatchingMoves: function(endSquare
) {
739 // Run through moves list and return the matching set (if promotions...)
741 this.possibleMoves
.forEach(function(m
) {
742 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
747 animateMove: function(move) {
748 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
749 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
750 let rectStart
= startSquare
.getBoundingClientRect();
751 let rectEnd
= endSquare
.getBoundingClientRect();
752 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
754 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
755 // HACK for animation (with positive translate, image slides "under background"...)
756 // Possible improvement: just alter squares on the piece's way...
757 squares
= document
.getElementsByClassName("board");
758 for (let i
=0; i
<squares
.length
; i
++)
760 let square
= squares
.item(i
);
761 if (square
.id
!= this.getSquareId(move.start
))
762 square
.style
.zIndex
= "-1";
764 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
765 movingPiece
.style
.transitionDuration
= "0.2s";
766 movingPiece
.style
.zIndex
= "3000";
768 for (let i
=0; i
<squares
.length
; i
++)
769 squares
.item(i
).style
.zIndex
= "auto";
770 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
774 play: function(move, programmatic
) {
775 if (!!programmatic
) //computer or human opponent
777 this.animateMove(move);
780 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
781 // Not programmatic, or animation is over
782 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
783 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
784 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
785 this.vr
.play(move, "ingame");
786 if (this.mode
== "human")
787 this.updateStorage(); //after our moves and opponent moves
788 const eog
= this.vr
.checkGameOver();
791 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
792 setTimeout(this.playComputerMove
, 500);