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 let [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
130 'class': { 'board': true },
132 'width': (100/this.choices
.length
) + "%",
133 'padding-bottom': (100/this.choices
.length
) + "%",
138 attrs: { "src": '/images/pieces/' +
139 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
140 'class': { 'choice-piece': true, 'board': true },
141 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
147 // Create board element (+ reserves if needed by variant or mode)
148 let gameDiv
= h('div',
150 'class': { 'game': true },
152 [_
.range(sizeX
).map(i
=> {
153 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
160 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
162 _
.range(sizeY
).map(j
=> {
163 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
165 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
173 'ghost': !!this.selectedPiece
174 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
177 src: "/images/pieces/" +
178 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
184 if (!this.expert
&& hintSquares
[ci
][cj
])
194 src: "/images/mark.svg",
200 const lm
= this.vr
.lastMove
;
201 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
207 'light-square': (i
+j
)%2==0 && (this.expert
|| !highlight
),
208 'dark-square': (i
+j
)%2==1 && (this.expert
|| !highlight
),
209 'highlight': !this.expert
&& highlight
,
210 'incheck': !this.expert
&& incheckSq
[ci
][cj
],
213 id: this.getSquareId({x:ci
,y:cj
}),
222 if (this.mode
!= "idle")
227 on: { click: this.resign
},
228 attrs: { "aria-label": 'Resign' },
234 [h('i', { 'class': { "material-icons": true } }, "flag")])
237 elementArray
.push(gameDiv
);
240 // let reserve = h('div',
241 // {'class':{'game':true}}, [
243 // { 'class': { 'row': true }},
246 // {'class':{'board':true}},
247 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
253 // elementArray.push(reserve);
255 const eogMessage
= this.getEndgameMessage(this.score
);
259 attrs: { "id": "modal-eog", type: "checkbox" },
260 "class": { "modal": true },
264 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
269 "class": { "card": true, "smallpad": true },
274 attrs: { "for": "modal-eog" },
275 "class": { "modal-close": true },
280 "class": { "section": true },
281 domProps: { innerHTML: eogMessage
},
289 elementArray
= elementArray
.concat(modalEog
);
291 const modalNewgame
= [
294 attrs: { "id": "modal-newgame", type: "checkbox" },
295 "class": { "modal": true },
299 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
304 "class": { "card": true, "smallpad": true },
309 attrs: { "id": "close-newgame", "for": "modal-newgame" },
310 "class": { "modal-close": true },
315 "class": { "section": true },
316 domProps: { innerHTML: "New game" },
321 "class": { "section": true },
322 domProps: { innerHTML: "Waiting for opponent..." },
330 elementArray
= elementArray
.concat(modalNewgame
);
331 const actions
= h('div',
333 attrs: { "id": "actions" },
334 'class': { 'text-center': true },
338 elementArray
.push(actions
);
339 if (this.score
!= "*")
343 { attrs: { id: "pgn-div" } },
355 attrs: { id: "pgn-game" },
356 on: { click: this.download
},
358 innerHTML: this.pgnTxt
372 "col-md-offset-2":true,
374 "col-lg-offset-3":true,
376 // NOTE: click = mousedown + mouseup --> what about smartphone?!
378 mousedown: this.mousedown
,
379 mousemove: this.mousemove
,
380 mouseup: this.mouseup
,
381 touchdown: this.mousedown
,
382 touchmove: this.mousemove
,
383 touchup: this.mouseup
,
389 created: function() {
390 const url
= socketUrl
;
391 const continuation
= (localStorage
.getItem("variant") === variant
);
392 this.myid
= continuation
393 ? localStorage
.getItem("myid")
394 // random enough (TODO: function)
395 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
396 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
397 const socketOpenListener
= () => {
400 const fen
= localStorage
.getItem("fen");
401 const mycolor
= localStorage
.getItem("mycolor");
402 const oppid
= localStorage
.getItem("oppid");
403 const moves
= JSON
.parse(localStorage
.getItem("moves"));
404 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
405 // Send ping to server (answer pong if opponent is connected)
406 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
408 else if (localStorage
.getItem("newgame") === variant
)
410 // New game request has been cancelled on disconnect
412 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
415 const socketMessageListener
= msg
=> {
416 const data
= JSON
.parse(msg
.data
);
419 case "newgame": //opponent found
420 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
422 case "newmove": //..he played!
423 this.play(data
.move, "animate");
425 case "pong": //received if we sent a ping (game still alive on our side)
426 this.oppConnected
= true;
427 const L
= this.vr
.moves
.length
;
428 // Send our "last state" informations to opponent
429 this.conn
.send(JSON
.stringify({
432 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
436 case "lastate": //got opponent infos about last move (we might have resigned)
437 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
440 this.conn
.send(JSON
.stringify({
447 else if (data
.movesCount
< 0)
450 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
452 else if (data
.movesCount
< this.vr
.moves
.length
)
454 // We must tell last move to opponent
455 const L
= this.vr
.moves
.length
;
456 this.conn
.send(JSON
.stringify({
459 lastMove:this.vr
.moves
[L
-1],
463 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
464 this.play(data
.lastMove
, "animate");
466 case "resign": //..you won!
467 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
469 // TODO: also use (dis)connect info to count online players?
472 if (this.mode
== "human" && this.oppid
== data
.id
)
473 this.oppConnected
= (data
.code
== "connect");
477 const socketCloseListener
= () => {
478 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
479 this.conn
.addEventListener('open', socketOpenListener
);
480 this.conn
.addEventListener('message', socketMessageListener
);
481 this.conn
.addEventListener('close', socketCloseListener
);
483 this.conn
.onopen
= socketOpenListener
;
484 this.conn
.onmessage
= socketMessageListener
;
485 this.conn
.onclose
= socketCloseListener
;
488 download: function() {
489 let content
= document
.getElementById("pgn-game").innerHTML
;
490 content
= content
.replace(/<br>/g, "\n");
491 // Prepare and trigger download link
492 let downloadAnchor
= document
.getElementById("download");
493 downloadAnchor
.setAttribute("download", "game.pgn");
494 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
495 downloadAnchor
.click();
497 endGame: function(score
) {
499 let modalBox
= document
.getElementById("modal-eog");
500 modalBox
.checked
= true;
501 // Variants may have special PGN structure (so next function isn't defined here)
502 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
503 setTimeout(() => { modalBox
.checked
= false; }, 2000);
504 if (this.mode
== "human")
509 getEndgameMessage: function(score
) {
510 let eogMessage
= "Unfinished";
514 eogMessage
= "White win";
517 eogMessage
= "Black win";
525 toggleExpertMode: function() {
526 this.expert
= !this.expert
;
527 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
530 if (this.mode
== "human" && this.oppConnected
)
533 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
534 } catch (INVALID_STATE_ERR
) {
535 return; //socket is not ready (and not yet reconnected)
538 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
540 setStorage: function() {
541 localStorage
.setItem("myid", this.myid
);
542 localStorage
.setItem("variant", variant
);
543 localStorage
.setItem("mycolor", this.mycolor
);
544 localStorage
.setItem("oppid", this.oppid
);
545 localStorage
.setItem("fenStart", this.fenStart
);
546 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
547 localStorage
.setItem("fen", this.vr
.getFen());
549 updateStorage: function() {
550 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
551 localStorage
.setItem("fen", this.vr
.getFen());
553 clearStorage: function() {
554 delete localStorage
["variant"];
555 delete localStorage
["myid"];
556 delete localStorage
["mycolor"];
557 delete localStorage
["oppid"];
558 delete localStorage
["fenStart"];
559 delete localStorage
["fen"];
560 delete localStorage
["moves"];
562 clickGameSeek: function() {
563 if (this.mode
== "human")
564 return; //no newgame while playing
567 delete localStorage
["newgame"]; //cancel game seek
571 this.newGame("human");
573 clickComputerGame: function() {
574 if (this.mode
== "human")
575 return; //no newgame while playing
576 this.newGame("computer");
578 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
579 //const fen = "1n2T1n0/p2pO2p/1s1k1s2/8/3S2p1/2U2cO1/P3PuPP/3K1BR1 0100";
580 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
581 console
.log(fen
); //DEBUG
583 if (mode
=="human" && !oppId
)
585 const storageVariant
= localStorage
.getItem("variant");
586 if (!!storageVariant
&& storageVariant
!== variant
)
588 alert("Finish your " + storageVariant
+ " game first!");
591 // Send game request and wait..
592 localStorage
["newgame"] = variant
;
594 this.clearStorage(); //in case of
596 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
597 } catch (INVALID_STATE_ERR
) {
598 return; //nothing achieved
600 if (continuation
!== "reconnect") //TODO: bad HACK...
602 let modalBox
= document
.getElementById("modal-newgame");
603 modalBox
.checked
= true;
604 setTimeout(() => { modalBox
.checked
= false; }, 2000);
608 this.vr
= new VariantRules(fen
, moves
|| []);
609 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
611 this.incheck
= []; //in case of
612 this.fenStart
= continuation
613 ? localStorage
.getItem("fenStart")
614 : fen
.split(" ")[0]; //Only the position matters
620 // Not playing sound on game continuation:
621 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
622 document
.getElementById("modal-newgame").checked
= false;
625 this.oppConnected
= true;
626 this.mycolor
= color
;
628 if (!!moves
&& moves
.length
> 0) //imply continuation
630 const lastMove
= moves
[moves
.length
-1];
631 this.vr
.undo(lastMove
);
632 this.incheck
= this.vr
.getCheckSquares(lastMove
);
633 this.vr
.play(lastMove
, "ingame");
635 delete localStorage
["newgame"];
636 this.setStorage(); //in case of interruptions
638 else //against computer
640 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
641 if (this.mycolor
== 'b')
642 setTimeout(this.playComputerMove
, 500);
645 playComputerMove: function() {
646 const timeStart
= Date
.now();
647 const compMove
= this.vr
.getComputerMove();
648 // (first move) HACK: avoid selecting elements before they appear on page:
649 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
650 setTimeout(() => this.play(compMove
, "animate"), delay
);
652 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
653 getSquareId: function(o
) {
654 // NOTE: a separator is required to allow any size of board
655 return "sq-" + o
.x
+ "-" + o
.y
;
658 getSquareFromId: function(id
) {
659 let idParts
= id
.split('-');
660 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
662 mousedown: function(e
) {
663 e
= e
|| window
.event
;
664 e
.preventDefault(); //disable native drag & drop
665 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
667 // Next few lines to center the piece on mouse cursor
668 let rect
= e
.target
.parentNode
.getBoundingClientRect();
670 x: rect
.x
+ rect
.width
/2,
671 y: rect
.y
+ rect
.width
/2,
672 id: e
.target
.parentNode
.id
674 this.selectedPiece
= e
.target
.cloneNode();
675 this.selectedPiece
.style
.position
= "absolute";
676 this.selectedPiece
.style
.top
= 0;
677 this.selectedPiece
.style
.display
= "inline-block";
678 this.selectedPiece
.style
.zIndex
= 3000;
679 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
680 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
681 ? this.vr
.getPossibleMovesFrom(startSquare
)
683 e
.target
.parentNode
.appendChild(this.selectedPiece
);
686 mousemove: function(e
) {
687 if (!this.selectedPiece
)
689 e
= e
|| window
.event
;
690 // If there is an active element, move it around
691 if (!!this.selectedPiece
)
693 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
694 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
697 mouseup: function(e
) {
698 if (!this.selectedPiece
)
700 e
= e
|| window
.event
;
701 // Read drop target (or parentElement, parentNode... if type == "img")
702 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
703 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
704 this.selectedPiece
.style
.zIndex
= 3000;
705 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
706 landing
= landing
.parentNode
;
707 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
709 // OK: process move attempt
710 let endSquare
= this.getSquareFromId(landing
.id
);
711 let moves
= this.findMatchingMoves(endSquare
);
712 this.possibleMoves
= [];
713 if (moves
.length
> 1)
714 this.choices
= moves
;
715 else if (moves
.length
==1)
717 // Else: impossible move
718 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
719 delete this.selectedPiece
;
720 this.selectedPiece
= null;
722 findMatchingMoves: function(endSquare
) {
723 // Run through moves list and return the matching set (if promotions...)
725 this.possibleMoves
.forEach(function(m
) {
726 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
731 animateMove: function(move) {
732 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
733 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
734 let rectStart
= startSquare
.getBoundingClientRect();
735 let rectEnd
= endSquare
.getBoundingClientRect();
736 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
737 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
738 // HACK for animation (otherwise with positive translate, image slides "under background"...)
739 // Possible improvement: just alter squares on the piece's way...
740 squares
= document
.getElementsByClassName("board");
741 for (let i
=0; i
<squares
.length
; i
++)
743 let square
= squares
.item(i
);
744 if (square
.id
!= this.getSquareId(move.start
))
745 square
.style
.zIndex
= "-1";
747 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
748 movingPiece
.style
.transitionDuration
= "0.2s";
749 movingPiece
.style
.zIndex
= "3000";
751 for (let i
=0; i
<squares
.length
; i
++)
752 squares
.item(i
).style
.zIndex
= "auto";
753 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
757 play: function(move, programmatic
) {
758 if (!!programmatic
) //computer or human opponent
760 this.animateMove(move);
763 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
764 // Not programmatic, or animation is over
765 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
766 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
767 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
768 this.vr
.play(move, "ingame");
769 if (this.mode
== "human")
770 this.updateStorage(); //after our moves and opponent moves
771 const eog
= this.vr
.checkGameOver();
774 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
775 setTimeout(this.playComputerMove
, 500);