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
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/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
139 'class': { 'choice-piece': true, 'board': true },
140 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
146 // Create board element (+ reserves if needed by variant or mode)
147 let gameDiv
= h('div',
149 'class': { 'game': true },
151 [_
.range(sizeX
).map(i
=> {
152 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
159 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
161 _
.range(sizeY
).map(j
=> {
162 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
164 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
172 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
175 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
181 if (!this.expert
&& hintSquares
[ci
][cj
])
191 src: "/images/mark.svg",
197 const lm
= this.vr
.lastMove
;
198 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
204 'light-square': (i
+j
)%2==0 && (this.expert
|| !highlight
),
205 'dark-square': (i
+j
)%2==1 && (this.expert
|| !highlight
),
206 'highlight': !this.expert
&& highlight
,
207 'incheck': !this.expert
&& incheckSq
[ci
][cj
],
210 id: this.getSquareId({x:ci
,y:cj
}),
222 on: { click: this.resign
},
223 attrs: { "aria-label": 'Resign' },
229 [h('i', { 'class': { "material-icons": true } }, "flag")])
231 elementArray
.push(gameDiv
);
234 // let reserve = h('div',
235 // {'class':{'game':true}}, [
237 // { 'class': { 'row': true }},
240 // {'class':{'board':true}},
241 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
247 // elementArray.push(reserve);
249 const eogMessage
= this.getEndgameMessage(this.score
);
253 attrs: { "id": "modal-eog", type: "checkbox" },
254 "class": { "modal": true },
258 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
263 "class": { "card": true, "smallpad": true },
268 attrs: { "for": "modal-eog" },
269 "class": { "modal-close": true },
274 "class": { "section": true },
275 domProps: { innerHTML: eogMessage
},
283 elementArray
= elementArray
.concat(modalEog
);
285 const modalNewgame
= [
288 attrs: { "id": "modal-newgame", type: "checkbox" },
289 "class": { "modal": true },
293 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
298 "class": { "card": true, "smallpad": true },
303 attrs: { "id": "close-newgame", "for": "modal-newgame" },
304 "class": { "modal-close": true },
309 "class": { "section": true },
310 domProps: { innerHTML: "New game" },
315 "class": { "section": true },
316 domProps: { innerHTML: "Waiting for opponent..." },
324 elementArray
= elementArray
.concat(modalNewgame
);
325 const actions
= h('div',
327 attrs: { "id": "actions" },
328 'class': { 'text-center': true },
332 elementArray
.push(actions
);
333 if (this.score
!= "*")
337 { attrs: { id: "pgn-div" } },
349 attrs: { id: "pgn-game" },
350 on: { click: this.download
},
352 innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
)
366 "col-md-offset-2":true,
368 "col-lg-offset-3":true,
370 // NOTE: click = mousedown + mouseup --> what about smartphone?!
372 mousedown: this.mousedown
,
373 mousemove: this.mousemove
,
374 mouseup: this.mouseup
,
375 touchdown: this.mousedown
,
376 touchmove: this.mousemove
,
377 touchup: this.mouseup
,
383 created: function() {
384 const url
= socketUrl
;
385 const continuation
= (localStorage
.getItem("variant") === variant
);
386 this.myid
= continuation
387 ? localStorage
.getItem("myid")
388 // random enough (TODO: function)
389 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
390 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
391 const socketOpenListener
= () => {
394 const fen
= localStorage
.getItem("fen");
395 const mycolor
= localStorage
.getItem("mycolor");
396 const oppid
= localStorage
.getItem("oppid");
397 const moves
= JSON
.parse(localStorage
.getItem("moves"));
398 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
399 // Send ping to server (answer pong if opponent is connected)
400 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
402 else if (localStorage
.getItem("newgame") === variant
)
404 // New game request has been cancelled on disconnect
406 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
409 const socketMessageListener
= msg
=> {
410 const data
= JSON
.parse(msg
.data
);
411 console
.log("Receive message: " + data
.code
);
414 case "newgame": //opponent found
415 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
417 case "newmove": //..he played!
418 this.play(data
.move, "animate");
420 case "pong": //received if we sent a ping (game still alive on our side)
421 this.oppConnected
= true;
422 const L
= this.vr
.moves
.length
;
423 // Send our "last state" informations to opponent
424 this.conn
.send(JSON
.stringify({
427 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
431 case "lastate": //got opponent infos about last move (we might have resigned)
432 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
435 this.conn
.send(JSON
.stringify({
442 else if (data
.movesCount
< 0)
445 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
447 else if (data
.movesCount
< this.vr
.moves
.length
)
449 // We must tell last move to opponent
450 const L
= this.vr
.moves
.length
;
451 this.conn
.send(JSON
.stringify({
454 lastMove:this.vr
.moves
[L
-1],
458 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
459 this.play(data
.lastMove
, "animate");
461 case "resign": //..you won!
462 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
464 // TODO: also use (dis)connect info to count online players?
467 if (this.mode
== "human" && this.oppid
== data
.id
)
468 this.oppConnected
= (data
.code
== "connect");
472 const socketCloseListener
= () => {
473 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
474 this.conn
.addEventListener('open', socketOpenListener
);
475 this.conn
.addEventListener('message', socketMessageListener
);
476 this.conn
.addEventListener('close', socketCloseListener
);
478 this.conn
.onopen
= socketOpenListener
;
479 this.conn
.onmessage
= socketMessageListener
;
480 this.conn
.onclose
= socketCloseListener
;
483 download: function() {
484 let content
= document
.getElementById("pgn-game").innerHTML
;
485 content
= content
.replace(/<br>/g, "\n");
486 // Prepare and trigger download link
487 let downloadAnchor
= document
.getElementById("download");
488 downloadAnchor
.setAttribute("download", "game.pgn");
489 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
490 downloadAnchor
.click();
492 endGame: function(score
) {
494 let modalBox
= document
.getElementById("modal-eog");
495 modalBox
.checked
= true;
496 setTimeout(() => { modalBox
.checked
= false; }, 2000);
497 if (this.mode
== "human")
502 getEndgameMessage: function(score
) {
503 let eogMessage
= "Unfinished";
507 eogMessage
= "White win";
510 eogMessage
= "Black win";
518 toggleExpertMode: function() {
519 this.expert
= !this.expert
;
520 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
523 if (this.mode
== "human" && this.oppConnected
)
526 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
527 } catch (INVALID_STATE_ERR
) {
528 return; //socket is not ready (and not yet reconnected)
531 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
533 setStorage: function() {
534 localStorage
.setItem("myid", this.myid
);
535 localStorage
.setItem("variant", variant
);
536 localStorage
.setItem("mycolor", this.mycolor
);
537 localStorage
.setItem("oppid", this.oppid
);
538 localStorage
.setItem("fenStart", this.fenStart
);
539 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
540 localStorage
.setItem("fen", this.vr
.getFen());
542 updateStorage: function() {
543 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
544 localStorage
.setItem("fen", this.vr
.getFen());
546 clearStorage: function() {
547 delete localStorage
["variant"];
548 delete localStorage
["myid"];
549 delete localStorage
["mycolor"];
550 delete localStorage
["oppid"];
551 delete localStorage
["fenStart"];
552 delete localStorage
["fen"];
553 delete localStorage
["moves"];
555 clickGameSeek: function() {
556 if (this.mode
== "human")
557 return; //no newgame while playing
560 delete localStorage
["newgame"]; //cancel game seek
564 this.newGame("human");
566 clickComputerGame: function() {
567 if (this.mode
== "human")
568 return; //no newgame while playing
569 this.newGame("computer");
571 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
572 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
573 console
.log(fen
); //DEBUG
575 if (mode
=="human" && !oppId
)
577 const storageVariant
= localStorage
.getItem("variant");
578 if (!!storageVariant
&& storageVariant
!== variant
)
580 alert("Finish your " + storageVariant
+ " game first!");
583 // Send game request and wait..
584 localStorage
["newgame"] = variant
;
586 this.clearStorage(); //in case of
588 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
589 } catch (INVALID_STATE_ERR
) {
590 return; //nothing achieved
592 if (continuation
!== "reconnect") //TODO: bad HACK...
594 let modalBox
= document
.getElementById("modal-newgame");
595 modalBox
.checked
= true;
596 setTimeout(() => { modalBox
.checked
= false; }, 2000);
600 this.vr
= new VariantRules(fen
, moves
|| []);
602 this.incheck
= []; //in case of
603 this.fenStart
= continuation
604 ? localStorage
.getItem("fenStart")
605 : fen
.split(" ")[0]; //Only the position matters
611 // Not playing sound on game continuation:
612 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
613 document
.getElementById("modal-newgame").checked
= false;
616 this.oppConnected
= true;
617 this.mycolor
= color
;
619 if (!!moves
&& moves
.length
> 0) //imply continuation
621 const oppCol
= this.vr
.turn
;
622 const lastMove
= moves
[moves
.length
-1];
623 this.vr
.undo(lastMove
);
624 this.incheck
= this.vr
.getCheckSquares(lastMove
, oppCol
);
625 this.vr
.play(lastMove
, "ingame");
627 delete localStorage
["newgame"];
628 this.setStorage(); //in case of interruptions
630 else //against computer
632 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
633 if (this.mycolor
== 'b')
634 setTimeout(this.playComputerMove
, 500);
637 playComputerMove: function() {
638 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
639 const compMove
= this.vr
.getComputerMove(compColor
);
640 // HACK: avoid selecting elements before they appear on page:
641 setTimeout(() => this.play(compMove
, "animate"), 500);
643 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
644 getSquareId: function(o
) {
645 // NOTE: a separator is required to allow any size of board
646 return "sq-" + o
.x
+ "-" + o
.y
;
649 getSquareFromId: function(id
) {
650 let idParts
= id
.split('-');
651 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
653 mousedown: function(e
) {
654 e
= e
|| window
.event
;
655 e
.preventDefault(); //disable native drag & drop
656 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
658 // Next few lines to center the piece on mouse cursor
659 let rect
= e
.target
.parentNode
.getBoundingClientRect();
661 x: rect
.x
+ rect
.width
/2,
662 y: rect
.y
+ rect
.width
/2,
663 id: e
.target
.parentNode
.id
665 this.selectedPiece
= e
.target
.cloneNode();
666 this.selectedPiece
.style
.position
= "absolute";
667 this.selectedPiece
.style
.top
= 0;
668 this.selectedPiece
.style
.display
= "inline-block";
669 this.selectedPiece
.style
.zIndex
= 3000;
670 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
671 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
672 ? this.vr
.getPossibleMovesFrom(startSquare
)
674 e
.target
.parentNode
.appendChild(this.selectedPiece
);
677 mousemove: function(e
) {
678 if (!this.selectedPiece
)
680 e
= e
|| window
.event
;
681 // If there is an active element, move it around
682 if (!!this.selectedPiece
)
684 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
685 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
688 mouseup: function(e
) {
689 if (!this.selectedPiece
)
691 e
= e
|| window
.event
;
692 // Read drop target (or parentElement, parentNode... if type == "img")
693 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
694 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
695 this.selectedPiece
.style
.zIndex
= 3000;
696 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
697 landing
= landing
.parentNode
;
698 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
700 // OK: process move attempt
701 let endSquare
= this.getSquareFromId(landing
.id
);
702 let moves
= this.findMatchingMoves(endSquare
);
703 this.possibleMoves
= [];
704 if (moves
.length
> 1)
705 this.choices
= moves
;
706 else if (moves
.length
==1)
708 // Else: impossible move
709 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
710 delete this.selectedPiece
;
711 this.selectedPiece
= null;
713 findMatchingMoves: function(endSquare
) {
714 // Run through moves list and return the matching set (if promotions...)
716 this.possibleMoves
.forEach(function(m
) {
717 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
722 animateMove: function(move) {
723 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
724 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
725 let rectStart
= startSquare
.getBoundingClientRect();
726 let rectEnd
= endSquare
.getBoundingClientRect();
727 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
728 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
729 // HACK for animation (otherwise with positive translate, image slides "under background"...)
730 // Possible improvement: just alter squares on the piece's way...
731 squares
= document
.getElementsByClassName("board");
732 for (let i
=0; i
<squares
.length
; i
++)
734 let square
= squares
.item(i
);
735 if (square
.id
!= this.getSquareId(move.start
))
736 square
.style
.zIndex
= "-1";
738 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
739 movingPiece
.style
.transitionDuration
= "0.2s";
740 movingPiece
.style
.zIndex
= "3000";
742 for (let i
=0; i
<squares
.length
; i
++)
743 squares
.item(i
).style
.zIndex
= "auto";
744 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
748 play: function(move, programmatic
) {
749 if (!!programmatic
) //computer or human opponent
751 this.animateMove(move);
754 const oppCol
= this.vr
.getOppCol(this.vr
.turn
);
755 this.incheck
= this.vr
.getCheckSquares(move, oppCol
); //is opponent in check?
756 // Not programmatic, or animation is over
757 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
758 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
759 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
760 this.vr
.play(move, "ingame");
761 if (this.mode
== "human")
762 this.updateStorage(); //after our moves and opponent moves
763 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
766 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
767 setTimeout(this.playComputerMove
, 500);