1 // TODO: use indexedDB instead of localStorage? (more flexible: allow several games)
2 Vue
.component('my-game', {
5 vr: null, //object to check moves, store them, FEN..
7 possibleMoves: [], //filled after each valid click/dragstart
8 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket messages
12 score: "*", //'*' means 'unfinished'
13 mode: "idle", //human, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
20 expert: document
.cookie
.length
>0 ? document
.cookie
.substr(-1)=="1" : false,
24 let [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
131 'class': { 'board': true },
133 'width': (100/this.choices
.length
) + "%",
134 'padding-bottom': (100/this.choices
.length
) + "%",
139 attrs: { "src": '/images/pieces/' + 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
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
176 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
182 if (!this.expert
&& hintSquares
[ci
][cj
])
192 src: "/images/mark.svg",
198 const lm
= this.vr
.lastMove
;
199 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
205 'light-square': (i
+j
)%2==0 && (this.expert
|| !highlight
),
206 'dark-square': (i
+j
)%2==1 && (this.expert
|| !highlight
),
207 'highlight': !this.expert
&& highlight
,
208 'incheck': !this.expert
&& incheckSq
[ci
][cj
],
211 id: this.getSquareId({x:ci
,y:cj
}),
220 if (this.mode
!= "idle")
225 on: { click: this.resign
},
226 attrs: { "aria-label": 'Resign' },
232 [h('i', { 'class': { "material-icons": true } }, "flag")])
235 elementArray
.push(gameDiv
);
238 // let reserve = h('div',
239 // {'class':{'game':true}}, [
241 // { 'class': { 'row': true }},
244 // {'class':{'board':true}},
245 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
251 // elementArray.push(reserve);
253 const eogMessage
= this.getEndgameMessage(this.score
);
257 attrs: { "id": "modal-eog", type: "checkbox" },
258 "class": { "modal": true },
262 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
267 "class": { "card": true, "smallpad": true },
272 attrs: { "for": "modal-eog" },
273 "class": { "modal-close": true },
278 "class": { "section": true },
279 domProps: { innerHTML: eogMessage
},
287 elementArray
= elementArray
.concat(modalEog
);
289 const modalNewgame
= [
292 attrs: { "id": "modal-newgame", type: "checkbox" },
293 "class": { "modal": true },
297 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
302 "class": { "card": true, "smallpad": true },
307 attrs: { "id": "close-newgame", "for": "modal-newgame" },
308 "class": { "modal-close": true },
313 "class": { "section": true },
314 domProps: { innerHTML: "New game" },
319 "class": { "section": true },
320 domProps: { innerHTML: "Waiting for opponent..." },
328 elementArray
= elementArray
.concat(modalNewgame
);
329 const actions
= h('div',
331 attrs: { "id": "actions" },
332 'class': { 'text-center': true },
336 elementArray
.push(actions
);
337 if (this.score
!= "*")
341 { attrs: { id: "pgn-div" } },
353 attrs: { id: "pgn-game" },
354 on: { click: this.download
},
356 innerHTML: this.pgnTxt
370 "col-md-offset-2":true,
372 "col-lg-offset-3":true,
374 // NOTE: click = mousedown + mouseup --> what about smartphone?!
376 mousedown: this.mousedown
,
377 mousemove: this.mousemove
,
378 mouseup: this.mouseup
,
379 touchdown: this.mousedown
,
380 touchmove: this.mousemove
,
381 touchup: this.mouseup
,
387 created: function() {
388 const url
= socketUrl
;
389 const continuation
= (localStorage
.getItem("variant") === variant
);
390 this.myid
= continuation
391 ? localStorage
.getItem("myid")
392 // random enough (TODO: function)
393 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
394 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
395 const socketOpenListener
= () => {
398 const fen
= localStorage
.getItem("fen");
399 const mycolor
= localStorage
.getItem("mycolor");
400 const oppid
= localStorage
.getItem("oppid");
401 const moves
= JSON
.parse(localStorage
.getItem("moves"));
402 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
403 // Send ping to server (answer pong if opponent is connected)
404 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
406 else if (localStorage
.getItem("newgame") === variant
)
408 // New game request has been cancelled on disconnect
410 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
413 const socketMessageListener
= msg
=> {
414 const data
= JSON
.parse(msg
.data
);
415 console
.log("Receive message: " + data
.code
);
418 case "newgame": //opponent found
419 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
421 case "newmove": //..he played!
422 this.play(data
.move, "animate");
424 case "pong": //received if we sent a ping (game still alive on our side)
425 this.oppConnected
= true;
426 const L
= this.vr
.moves
.length
;
427 // Send our "last state" informations to opponent
428 this.conn
.send(JSON
.stringify({
431 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
435 case "lastate": //got opponent infos about last move (we might have resigned)
436 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
439 this.conn
.send(JSON
.stringify({
446 else if (data
.movesCount
< 0)
449 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
451 else if (data
.movesCount
< this.vr
.moves
.length
)
453 // We must tell last move to opponent
454 const L
= this.vr
.moves
.length
;
455 this.conn
.send(JSON
.stringify({
458 lastMove:this.vr
.moves
[L
-1],
462 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
463 this.play(data
.lastMove
, "animate");
465 case "resign": //..you won!
466 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
468 // TODO: also use (dis)connect info to count online players?
471 if (this.mode
== "human" && this.oppid
== data
.id
)
472 this.oppConnected
= (data
.code
== "connect");
476 const socketCloseListener
= () => {
477 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
478 this.conn
.addEventListener('open', socketOpenListener
);
479 this.conn
.addEventListener('message', socketMessageListener
);
480 this.conn
.addEventListener('close', socketCloseListener
);
482 this.conn
.onopen
= socketOpenListener
;
483 this.conn
.onmessage
= socketMessageListener
;
484 this.conn
.onclose
= socketCloseListener
;
487 download: function() {
488 let content
= document
.getElementById("pgn-game").innerHTML
;
489 content
= content
.replace(/<br>/g, "\n");
490 // Prepare and trigger download link
491 let downloadAnchor
= document
.getElementById("download");
492 downloadAnchor
.setAttribute("download", "game.pgn");
493 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
494 downloadAnchor
.click();
496 endGame: function(score
) {
498 let modalBox
= document
.getElementById("modal-eog");
499 modalBox
.checked
= true;
500 // Variants may have special PGN structure (so next function isn't defined here)
501 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
502 setTimeout(() => { modalBox
.checked
= false; }, 2000);
503 if (this.mode
== "human")
508 getEndgameMessage: function(score
) {
509 let eogMessage
= "Unfinished";
513 eogMessage
= "White win";
516 eogMessage
= "Black win";
524 toggleExpertMode: function() {
525 this.expert
= !this.expert
;
526 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
529 if (this.mode
== "human" && this.oppConnected
)
532 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
533 } catch (INVALID_STATE_ERR
) {
534 return; //socket is not ready (and not yet reconnected)
537 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
539 setStorage: function() {
540 localStorage
.setItem("myid", this.myid
);
541 localStorage
.setItem("variant", variant
);
542 localStorage
.setItem("mycolor", this.mycolor
);
543 localStorage
.setItem("oppid", this.oppid
);
544 localStorage
.setItem("fenStart", this.fenStart
);
545 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
546 localStorage
.setItem("fen", this.vr
.getFen());
548 updateStorage: function() {
549 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
550 localStorage
.setItem("fen", this.vr
.getFen());
552 clearStorage: function() {
553 delete localStorage
["variant"];
554 delete localStorage
["myid"];
555 delete localStorage
["mycolor"];
556 delete localStorage
["oppid"];
557 delete localStorage
["fenStart"];
558 delete localStorage
["fen"];
559 delete localStorage
["moves"];
561 clickGameSeek: function() {
562 if (this.mode
== "human")
563 return; //no newgame while playing
566 delete localStorage
["newgame"]; //cancel game seek
570 this.newGame("human");
572 clickComputerGame: function() {
573 if (this.mode
== "human")
574 return; //no newgame while playing
575 this.newGame("computer");
577 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
578 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
579 console
.log(fen
); //DEBUG
581 if (mode
=="human" && !oppId
)
583 const storageVariant
= localStorage
.getItem("variant");
584 if (!!storageVariant
&& storageVariant
!== variant
)
586 alert("Finish your " + storageVariant
+ " game first!");
589 // Send game request and wait..
590 localStorage
["newgame"] = variant
;
592 this.clearStorage(); //in case of
594 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
595 } catch (INVALID_STATE_ERR
) {
596 return; //nothing achieved
598 if (continuation
!== "reconnect") //TODO: bad HACK...
600 let modalBox
= document
.getElementById("modal-newgame");
601 modalBox
.checked
= true;
602 setTimeout(() => { modalBox
.checked
= false; }, 2000);
606 this.vr
= new VariantRules(fen
, moves
|| []);
607 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
609 this.incheck
= []; //in case of
610 this.fenStart
= continuation
611 ? localStorage
.getItem("fenStart")
612 : fen
.split(" ")[0]; //Only the position matters
618 // Not playing sound on game continuation:
619 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
620 document
.getElementById("modal-newgame").checked
= false;
623 this.oppConnected
= true;
624 this.mycolor
= color
;
626 if (!!moves
&& moves
.length
> 0) //imply continuation
628 const lastMove
= moves
[moves
.length
-1];
629 this.vr
.undo(lastMove
);
630 this.incheck
= this.vr
.getCheckSquares(lastMove
);
631 this.vr
.play(lastMove
, "ingame");
633 delete localStorage
["newgame"];
634 this.setStorage(); //in case of interruptions
636 else //against computer
638 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
639 if (this.mycolor
== 'b')
640 setTimeout(this.playComputerMove
, 500);
643 playComputerMove: function() {
644 const compMove
= this.vr
.getComputerMove();
645 // HACK: avoid selecting elements before they appear on page:
646 setTimeout(() => this.play(compMove
, "animate"), 500);
648 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
649 getSquareId: function(o
) {
650 // NOTE: a separator is required to allow any size of board
651 return "sq-" + o
.x
+ "-" + o
.y
;
654 getSquareFromId: function(id
) {
655 let idParts
= id
.split('-');
656 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
658 mousedown: function(e
) {
659 e
= e
|| window
.event
;
660 e
.preventDefault(); //disable native drag & drop
661 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
663 // Next few lines to center the piece on mouse cursor
664 let rect
= e
.target
.parentNode
.getBoundingClientRect();
666 x: rect
.x
+ rect
.width
/2,
667 y: rect
.y
+ rect
.width
/2,
668 id: e
.target
.parentNode
.id
670 this.selectedPiece
= e
.target
.cloneNode();
671 this.selectedPiece
.style
.position
= "absolute";
672 this.selectedPiece
.style
.top
= 0;
673 this.selectedPiece
.style
.display
= "inline-block";
674 this.selectedPiece
.style
.zIndex
= 3000;
675 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
676 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
677 ? this.vr
.getPossibleMovesFrom(startSquare
)
679 e
.target
.parentNode
.appendChild(this.selectedPiece
);
682 mousemove: function(e
) {
683 if (!this.selectedPiece
)
685 e
= e
|| window
.event
;
686 // If there is an active element, move it around
687 if (!!this.selectedPiece
)
689 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
690 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
693 mouseup: function(e
) {
694 if (!this.selectedPiece
)
696 e
= e
|| window
.event
;
697 // Read drop target (or parentElement, parentNode... if type == "img")
698 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
699 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
700 this.selectedPiece
.style
.zIndex
= 3000;
701 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
702 landing
= landing
.parentNode
;
703 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
705 // OK: process move attempt
706 let endSquare
= this.getSquareFromId(landing
.id
);
707 let moves
= this.findMatchingMoves(endSquare
);
708 this.possibleMoves
= [];
709 if (moves
.length
> 1)
710 this.choices
= moves
;
711 else if (moves
.length
==1)
713 // Else: impossible move
714 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
715 delete this.selectedPiece
;
716 this.selectedPiece
= null;
718 findMatchingMoves: function(endSquare
) {
719 // Run through moves list and return the matching set (if promotions...)
721 this.possibleMoves
.forEach(function(m
) {
722 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
727 animateMove: function(move) {
728 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
729 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
730 let rectStart
= startSquare
.getBoundingClientRect();
731 let rectEnd
= endSquare
.getBoundingClientRect();
732 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
733 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
734 // HACK for animation (otherwise with positive translate, image slides "under background"...)
735 // Possible improvement: just alter squares on the piece's way...
736 squares
= document
.getElementsByClassName("board");
737 for (let i
=0; i
<squares
.length
; i
++)
739 let square
= squares
.item(i
);
740 if (square
.id
!= this.getSquareId(move.start
))
741 square
.style
.zIndex
= "-1";
743 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
744 movingPiece
.style
.transitionDuration
= "0.2s";
745 movingPiece
.style
.zIndex
= "3000";
747 for (let i
=0; i
<squares
.length
; i
++)
748 squares
.item(i
).style
.zIndex
= "auto";
749 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
753 play: function(move, programmatic
) {
754 if (!!programmatic
) //computer or human opponent
756 this.animateMove(move);
759 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
760 // Not programmatic, or animation is over
761 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
762 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
763 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
764 this.vr
.play(move, "ingame");
765 if (this.mode
== "human")
766 this.updateStorage(); //after our moves and opponent moves
767 const eog
= this.vr
.checkGameOver();
770 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
771 setTimeout(this.playComputerMove
, 500);