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
22 let [sizeX
,sizeY
] = VariantRules
.size
;
23 // Precompute hints squares to facilitate rendering
24 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
25 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
26 // Also precompute in-check squares
27 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
28 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
29 let elementArray
= [];
30 const playingHuman
= (this.mode
== "human");
31 const playingComp
= (this.mode
== "computer");
35 on: { click: this.clickGameSeek
},
36 attrs: { "aria-label": 'New game VS human' },
39 "bottom": true, //display below
41 "playing": playingHuman
,
44 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
47 on: { click: this.clickComputerGame
},
48 attrs: { "aria-label": 'New game VS computer' },
52 "playing": playingComp
,
55 [h('i', { 'class': { "material-icons": true } }, "computer")])
59 const square00
= document
.getElementById("sq-0-0");
60 const squareWidth
= !!square00
61 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
63 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
64 if (this.mode
== "human")
66 let connectedIndic
= h(
72 "connected": this.oppConnected
,
73 "disconnected": !this.oppConnected
,
76 "width": indicWidth
+ "px",
77 "height": indicWidth
+ "px",
81 elementArray
.push(connectedIndic
);
89 "white-turn": this.vr
.turn
=="w",
90 "black-turn": this.vr
.turn
=="b",
93 "width": indicWidth
+ "px",
94 "height": indicWidth
+ "px",
98 elementArray
.push(turnIndic
);
99 let choices
= h('div',
101 attrs: { "id": "choices" },
102 'class': { 'row': true },
104 "display": this.choices
.length
>0?"block":"none",
105 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
106 "width": (this.choices
.length
* squareWidth
) + "px",
107 "height": squareWidth
+ "px",
110 this.choices
.map( m
=> { //a "choice" is a move
113 'class': { 'board': true },
115 'width': (100/this.choices
.length
) + "%",
116 'padding-bottom': (100/this.choices
.length
) + "%",
121 attrs: { "src": '/images/pieces/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
122 'class': { 'choice-piece': true, 'board': true },
123 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
129 // Create board element (+ reserves if needed by variant or mode)
130 let gameDiv
= h('div',
132 'class': { 'game': true },
134 [_
.range(sizeX
).map(i
=> {
135 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
142 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
144 _
.range(sizeY
).map(j
=> {
145 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
147 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
155 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
158 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
164 if (hintSquares
[ci
][cj
])
174 src: "/images/mark.svg",
180 const lm
= this.vr
.lastMove
;
181 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
187 'light-square': !highlight
&& (i
+j
)%2==0,
188 'dark-square': !highlight
&& (i
+j
)%2==1,
189 'highlight': highlight
,
190 'incheck': incheckSq
[ci
][cj
],
193 id: this.getSquareId({x:ci
,y:cj
}),
205 on: { click: this.resign
},
206 attrs: { "aria-label": 'Resign' },
212 [h('i', { 'class': { "material-icons": true } }, "flag")])
214 elementArray
.push(gameDiv
);
217 // let reserve = h('div',
218 // {'class':{'game':true}}, [
220 // { 'class': { 'row': true }},
223 // {'class':{'board':true}},
224 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
230 // elementArray.push(reserve);
232 const eogMessage
= this.getEndgameMessage(this.score
);
236 attrs: { "id": "modal-eog", type: "checkbox" },
237 "class": { "modal": true },
241 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
246 "class": { "card": true, "smallpad": true },
251 attrs: { "for": "modal-eog" },
252 "class": { "modal-close": true },
257 "class": { "section": true },
258 domProps: { innerHTML: eogMessage
},
266 elementArray
= elementArray
.concat(modalEog
);
268 const modalNewgame
= [
271 attrs: { "id": "modal-newgame", type: "checkbox" },
272 "class": { "modal": true },
276 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
281 "class": { "card": true, "smallpad": true },
286 attrs: { "id": "close-newgame", "for": "modal-newgame" },
287 "class": { "modal-close": true },
292 "class": { "section": true },
293 domProps: { innerHTML: "New game" },
298 "class": { "section": true },
299 domProps: { innerHTML: "Waiting for opponent..." },
307 elementArray
= elementArray
.concat(modalNewgame
);
308 const actions
= h('div',
310 attrs: { "id": "actions" },
311 'class': { 'text-center': true },
315 elementArray
.push(actions
);
316 if (this.score
!= "*")
325 innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
)
339 "col-md-offset-2":true,
341 "col-lg-offset-3":true,
343 // NOTE: click = mousedown + mouseup --> what about smartphone?!
345 mousedown: this.mousedown
,
346 mousemove: this.mousemove
,
347 mouseup: this.mouseup
,
348 touchdown: this.mousedown
,
349 touchmove: this.mousemove
,
350 touchup: this.mouseup
,
356 created: function() {
357 const url
= socketUrl
;
358 const continuation
= (localStorage
.getItem("variant") === variant
);
359 this.myid
= continuation
360 ? localStorage
.getItem("myid")
361 // random enough (TODO: function)
362 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
363 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
364 const socketOpenListener
= () => {
367 const fen
= localStorage
.getItem("fen");
368 const mycolor
= localStorage
.getItem("mycolor");
369 const oppid
= localStorage
.getItem("oppid");
370 const moves
= JSON
.parse(localStorage
.getItem("moves"));
371 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
372 // Send ping to server (answer pong if opponent is connected)
373 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
375 else if (localStorage
.getItem("newgame") === variant
)
377 // New game request has been cancelled on disconnect
379 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
382 const socketMessageListener
= msg
=> {
383 const data
= JSON
.parse(msg
.data
);
384 console
.log("Receive message: " + data
.code
);
387 case "newgame": //opponent found
388 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
390 case "newmove": //..he played!
391 this.play(data
.move, "animate");
393 case "pong": //received if we sent a ping (game still alive on our side)
394 this.oppConnected
= true;
395 const L
= this.vr
.moves
.length
;
396 // Send our "last state" informations to opponent
397 this.conn
.send(JSON
.stringify({
400 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
404 case "lastate": //got opponent infos about last move (we might have resigned)
405 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
408 this.conn
.send(JSON
.stringify({
415 else if (data
.movesCount
< 0)
418 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
420 else if (data
.movesCount
< this.vr
.moves
.length
)
422 // We must tell last move to opponent
423 const L
= this.vr
.moves
.length
;
424 this.conn
.send(JSON
.stringify({
427 lastMove:this.vr
.moves
[L
-1],
431 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
432 this.play(data
.lastMove
, "animate");
434 case "resign": //..you won!
435 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
437 // TODO: also use (dis)connect info to count online players?
440 if (this.mode
== "human" && this.oppid
== data
.id
)
441 this.oppConnected
= (data
.code
== "connect");
445 const socketCloseListener
= () => {
446 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
447 this.conn
.addEventListener('open', socketOpenListener
);
448 this.conn
.addEventListener('message', socketMessageListener
);
449 this.conn
.addEventListener('close', socketCloseListener
);
451 this.conn
.onopen
= socketOpenListener
;
452 this.conn
.onmessage
= socketMessageListener
;
453 this.conn
.onclose
= socketCloseListener
;
456 endGame: function(score
) {
458 let modalBox
= document
.getElementById("modal-eog");
459 modalBox
.checked
= true;
460 setTimeout(() => { modalBox
.checked
= false; }, 2000);
461 if (this.mode
== "human")
466 getEndgameMessage: function(score
) {
467 let eogMessage
= "Unfinished";
471 eogMessage
= "White win";
474 eogMessage
= "Black win";
483 if (this.mode
== "human" && this.oppConnected
)
486 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
487 } catch (INVALID_STATE_ERR
) {
488 return; //socket is not ready (and not yet reconnected)
491 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
493 setStorage: function() {
494 localStorage
.setItem("myid", this.myid
);
495 localStorage
.setItem("variant", variant
);
496 localStorage
.setItem("mycolor", this.mycolor
);
497 localStorage
.setItem("oppid", this.oppid
);
498 localStorage
.setItem("fenStart", this.fenStart
);
499 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
500 localStorage
.setItem("fen", this.vr
.getFen());
502 updateStorage: function() {
503 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
504 localStorage
.setItem("fen", this.vr
.getFen());
506 clearStorage: function() {
507 delete localStorage
["variant"];
508 delete localStorage
["myid"];
509 delete localStorage
["mycolor"];
510 delete localStorage
["oppid"];
511 delete localStorage
["fenStart"];
512 delete localStorage
["fen"];
513 delete localStorage
["moves"];
515 clickGameSeek: function() {
516 if (this.mode
== "human")
517 return; //no newgame while playing
520 delete localStorage
["newgame"]; //cancel game seek
524 this.newGame("human");
526 clickComputerGame: function() {
527 if (this.mode
== "human")
528 return; //no newgame while playing
529 this.newGame("computer");
531 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
532 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
533 console
.log(fen
); //DEBUG
535 if (mode
=="human" && !oppId
)
537 const storageVariant
= localStorage
.getItem("variant");
538 if (!!storageVariant
&& storageVariant
!== variant
)
540 alert("Finish your " + storageVariant
+ " game first!");
543 // Send game request and wait..
544 localStorage
["newgame"] = variant
;
546 this.clearStorage(); //in case of
548 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
549 } catch (INVALID_STATE_ERR
) {
550 return; //nothing achieved
552 if (continuation
!== "reconnect") //TODO: bad HACK...
554 let modalBox
= document
.getElementById("modal-newgame");
555 modalBox
.checked
= true;
556 setTimeout(() => { modalBox
.checked
= false; }, 2000);
560 this.vr
= new VariantRules(fen
, moves
|| []);
562 this.incheck
= []; //in case of
563 this.fenStart
= continuation
564 ? localStorage
.getItem("fenStart")
565 : fen
.split(" ")[0]; //Only the position matters
571 // Not playing sound on game continuation:
572 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
573 document
.getElementById("modal-newgame").checked
= false;
576 this.oppConnected
= true;
577 this.mycolor
= color
;
579 if (!!moves
&& moves
.length
> 0) //imply continuation
581 const oppCol
= this.vr
.turn
;
582 const lastMove
= moves
[moves
.length
-1];
583 this.vr
.undo(lastMove
);
584 this.incheck
= this.vr
.getCheckSquares(lastMove
, oppCol
);
585 this.vr
.play(lastMove
, "ingame");
587 delete localStorage
["newgame"];
588 this.setStorage(); //in case of interruptions
590 else //against computer
592 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
593 if (this.mycolor
== 'b')
594 setTimeout(this.playComputerMove
, 500);
597 playComputerMove: function() {
598 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
599 const compMove
= this.vr
.getComputerMove(compColor
);
600 // HACK: avoid selecting elements before they appear on page:
601 setTimeout(() => this.play(compMove
, "animate"), 500);
603 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
604 getSquareId: function(o
) {
605 // NOTE: a separator is required to allow any size of board
606 return "sq-" + o
.x
+ "-" + o
.y
;
609 getSquareFromId: function(id
) {
610 let idParts
= id
.split('-');
611 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
613 mousedown: function(e
) {
614 e
= e
|| window
.event
;
615 e
.preventDefault(); //disable native drag & drop
616 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
618 // Next few lines to center the piece on mouse cursor
619 let rect
= e
.target
.parentNode
.getBoundingClientRect();
621 x: rect
.x
+ rect
.width
/2,
622 y: rect
.y
+ rect
.width
/2,
623 id: e
.target
.parentNode
.id
625 this.selectedPiece
= e
.target
.cloneNode();
626 this.selectedPiece
.style
.position
= "absolute";
627 this.selectedPiece
.style
.top
= 0;
628 this.selectedPiece
.style
.display
= "inline-block";
629 this.selectedPiece
.style
.zIndex
= 3000;
630 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
631 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
632 ? this.vr
.getPossibleMovesFrom(startSquare
)
634 e
.target
.parentNode
.appendChild(this.selectedPiece
);
637 mousemove: function(e
) {
638 if (!this.selectedPiece
)
640 e
= e
|| window
.event
;
641 // If there is an active element, move it around
642 if (!!this.selectedPiece
)
644 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
645 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
648 mouseup: function(e
) {
649 if (!this.selectedPiece
)
651 e
= e
|| window
.event
;
652 // Read drop target (or parentElement, parentNode... if type == "img")
653 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
654 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
655 this.selectedPiece
.style
.zIndex
= 3000;
656 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
657 landing
= landing
.parentNode
;
658 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
660 // OK: process move attempt
661 let endSquare
= this.getSquareFromId(landing
.id
);
662 let moves
= this.findMatchingMoves(endSquare
);
663 this.possibleMoves
= [];
664 if (moves
.length
> 1)
665 this.choices
= moves
;
666 else if (moves
.length
==1)
668 // Else: impossible move
669 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
670 delete this.selectedPiece
;
671 this.selectedPiece
= null;
673 findMatchingMoves: function(endSquare
) {
674 // Run through moves list and return the matching set (if promotions...)
676 this.possibleMoves
.forEach(function(m
) {
677 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
682 animateMove: function(move) {
683 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
684 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
685 let rectStart
= startSquare
.getBoundingClientRect();
686 let rectEnd
= endSquare
.getBoundingClientRect();
687 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
688 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
689 // HACK for animation (otherwise with positive translate, image slides "under background"...)
690 // Possible improvement: just alter squares on the piece's way...
691 squares
= document
.getElementsByClassName("board");
692 for (let i
=0; i
<squares
.length
; i
++)
694 let square
= squares
.item(i
);
695 if (square
.id
!= this.getSquareId(move.start
))
696 square
.style
.zIndex
= "-1";
698 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
699 movingPiece
.style
.transitionDuration
= "0.2s";
700 movingPiece
.style
.zIndex
= "3000";
702 for (let i
=0; i
<squares
.length
; i
++)
703 squares
.item(i
).style
.zIndex
= "auto";
704 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
708 play: function(move, programmatic
) {
709 if (!!programmatic
) //computer or human opponent
711 this.animateMove(move);
714 const oppCol
= this.vr
.getOppCol(this.vr
.turn
);
715 this.incheck
= this.vr
.getCheckSquares(move, oppCol
); //is opponent in check?
716 // Not programmatic, or animation is over
717 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
718 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
719 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
720 this.vr
.play(move, "ingame");
721 if (this.mode
== "human")
722 this.updateStorage(); //after our moves and opponent moves
723 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
726 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
727 setTimeout(this.playComputerMove
, 500);