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 let square00
= document
.getElementById("sq-0-0");
31 let squareWidth
= !!square00
32 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
34 const playingHuman
= (this.mode
== "human");
35 const playingComp
= (this.mode
== "computer");
39 on: { click: this.clickGameSeek
},
40 attrs: { "aria-label": 'New game VS human' },
44 "playing": playingHuman
,
47 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
50 on: { click: this.clickComputerGame
},
51 attrs: { "aria-label": 'New game VS computer' },
54 "playing": playingComp
,
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
61 if (this.mode
== "human")
63 let connectedIndic
= h(
67 "connected": this.oppConnected
,
68 "disconnected": !this.oppConnected
,
72 elementArray
.push(connectedIndic
);
74 let choices
= h('div',
76 attrs: { "id": "choices" },
77 'class': { 'row': true },
79 //"position": "relative",
80 "display": this.choices
.length
>0?"block":"none",
81 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
82 "width": (this.choices
.length
* squareWidth
) + "px",
83 "height": squareWidth
+ "px",
86 this.choices
.map( m
=> { //a "choice" is a move
89 'class': { 'board': true },
91 'width': (100/this.choices
.length
) + "%",
92 'padding-bottom': (100/this.choices
.length
) + "%",
97 attrs: { "src": '/images/pieces/' + VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
98 'class': { 'choice-piece': true, 'board': true },
99 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
105 // Create board element (+ reserves if needed by variant or mode)
106 let gameDiv
= h('div',
108 'class': { 'game': true },
110 [_
.range(sizeX
).map(i
=> {
111 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
118 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
120 _
.range(sizeY
).map(j
=> {
121 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
123 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
131 'ghost': !!this.selectedPiece
&& this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
134 src: "/images/pieces/" + VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
140 if (hintSquares
[ci
][cj
])
150 src: "/images/mark.svg",
156 const lm
= this.vr
.lastMove
;
157 const highlight
= !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
});
163 'light-square': !highlight
&& (i
+j
)%2==0,
164 'dark-square': !highlight
&& (i
+j
)%2==1,
165 'highlight': highlight
,
166 'incheck': incheckSq
[ci
][cj
],
169 id: this.getSquareId({x:ci
,y:cj
}),
181 on: { click: this.resign
},
182 attrs: { "aria-label": 'Resign' },
183 'class': { "tooltip":true },
185 [h('i', { 'class': { "material-icons": true } }, "flag")])
187 elementArray
.push(gameDiv
);
190 // let reserve = h('div',
191 // {'class':{'game':true}}, [
193 // { 'class': { 'row': true }},
196 // {'class':{'board':true}},
197 // [h('img',{'class':{"piece":true},attrs:{"src":"/images/pieces/wb.svg"}})]
203 // elementArray.push(reserve);
205 const eogMessage
= this.getEndgameMessage(this.score
);
209 attrs: { "id": "modal-eog", type: "checkbox" },
210 "class": { "modal": true },
214 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
219 "class": { "card": true, "smallpad": true },
224 attrs: { "for": "modal-eog" },
225 "class": { "modal-close": true },
230 "class": { "section": true },
231 domProps: { innerHTML: eogMessage
},
239 elementArray
= elementArray
.concat(modalEog
);
241 const modalNewgame
= [
244 attrs: { "id": "modal-newgame", type: "checkbox" },
245 "class": { "modal": true },
249 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
254 "class": { "card": true, "smallpad": true },
259 attrs: { "id": "close-newgame", "for": "modal-newgame" },
260 "class": { "modal-close": true },
265 "class": { "section": true },
266 domProps: { innerHTML: "New game" },
271 "class": { "section": true },
272 domProps: { innerHTML: "Waiting for opponent..." },
280 elementArray
= elementArray
.concat(modalNewgame
);
281 const actions
= h('div',
283 attrs: { "id": "actions" },
284 'class': { 'text-center': true },
288 elementArray
.push(actions
);
289 if (this.score
!= "*")
298 innerHTML: this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
)
312 "col-md-offset-2":true,
314 "col-lg-offset-3":true,
316 // NOTE: click = mousedown + mouseup --> what about smartphone?!
318 mousedown: this.mousedown
,
319 mousemove: this.mousemove
,
320 mouseup: this.mouseup
,
321 touchdown: this.mousedown
,
322 touchmove: this.mousemove
,
323 touchup: this.mouseup
,
329 created: function() {
330 const url
= socketUrl
;
331 const continuation
= (localStorage
.getItem("variant") === variant
);
332 this.myid
= continuation
333 ? localStorage
.getItem("myid")
334 // random enough (TODO: function)
335 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
336 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
337 const socketOpenListener
= () => {
340 const fen
= localStorage
.getItem("fen");
341 const mycolor
= localStorage
.getItem("mycolor");
342 const oppid
= localStorage
.getItem("oppid");
343 const moves
= JSON
.parse(localStorage
.getItem("moves"));
344 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
345 // Send ping to server (answer pong if opponent is connected)
346 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
348 else if (localStorage
.getItem("newgame") === variant
)
350 // New game request has been cancelled on disconnect
352 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
355 const socketMessageListener
= msg
=> {
356 const data
= JSON
.parse(msg
.data
);
357 console
.log("Receive message: " + data
.code
);
360 case "newgame": //opponent found
361 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
363 case "newmove": //..he played!
364 this.play(data
.move, "animate");
366 case "pong": //received if we sent a ping (game still alive on our side)
367 this.oppConnected
= true;
368 const L
= this.vr
.moves
.length
;
369 // Send our "last state" informations to opponent
370 this.conn
.send(JSON
.stringify({
373 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
377 case "lastate": //got opponent infos about last move (we might have resigned)
378 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
381 this.conn
.send(JSON
.stringify({
388 else if (data
.movesCount
< 0)
391 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
393 else if (data
.movesCount
< this.vr
.moves
.length
)
395 // We must tell last move to opponent
396 const L
= this.vr
.moves
.length
;
397 this.conn
.send(JSON
.stringify({
400 lastMove:this.vr
.moves
[L
-1],
404 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
405 this.play(data
.lastMove
, "animate");
407 case "resign": //..you won!
408 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
410 // TODO: also use (dis)connect info to count online players?
413 if (this.mode
== "human" && this.oppid
== data
.id
)
414 this.oppConnected
= (data
.code
== "connect");
418 const socketCloseListener
= () => {
419 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
420 this.conn
.addEventListener('open', socketOpenListener
);
421 this.conn
.addEventListener('message', socketMessageListener
);
422 this.conn
.addEventListener('close', socketCloseListener
);
424 this.conn
.onopen
= socketOpenListener
;
425 this.conn
.onmessage
= socketMessageListener
;
426 this.conn
.onclose
= socketCloseListener
;
429 endGame: function(score
) {
431 let modalBox
= document
.getElementById("modal-eog");
432 modalBox
.checked
= true;
433 setTimeout(() => { modalBox
.checked
= false; }, 2000);
434 if (this.mode
== "human")
439 getEndgameMessage: function(score
) {
440 let eogMessage
= "Unfinished";
444 eogMessage
= "White win";
447 eogMessage
= "Black win";
456 if (this.mode
== "human" && this.oppConnected
)
459 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
460 } catch (INVALID_STATE_ERR
) {
461 return; //socket is not ready (and not yet reconnected)
464 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
466 setStorage: function() {
467 localStorage
.setItem("myid", this.myid
);
468 localStorage
.setItem("variant", variant
);
469 localStorage
.setItem("mycolor", this.mycolor
);
470 localStorage
.setItem("oppid", this.oppid
);
471 localStorage
.setItem("fenStart", this.fenStart
);
472 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
473 localStorage
.setItem("fen", this.vr
.getFen());
475 updateStorage: function() {
476 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
477 localStorage
.setItem("fen", this.vr
.getFen());
479 clearStorage: function() {
480 delete localStorage
["variant"];
481 delete localStorage
["myid"];
482 delete localStorage
["mycolor"];
483 delete localStorage
["oppid"];
484 delete localStorage
["fenStart"];
485 delete localStorage
["fen"];
486 delete localStorage
["moves"];
488 clickGameSeek: function() {
489 if (this.mode
== "human")
490 return; //no newgame while playing
493 delete localStorage
["newgame"]; //cancel game seek
497 this.newGame("human");
499 clickComputerGame: function() {
500 if (this.mode
== "human")
501 return; //no newgame while playing
502 this.newGame("computer");
504 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
505 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
506 console
.log(fen
); //DEBUG
508 if (mode
=="human" && !oppId
)
510 const storageVariant
= localStorage
.getItem("variant");
511 if (!!storageVariant
&& storageVariant
!== variant
)
513 alert("Finish your " + storageVariant
+ " game first!");
516 // Send game request and wait..
517 localStorage
["newgame"] = variant
;
519 this.clearStorage(); //in case of
521 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
522 } catch (INVALID_STATE_ERR
) {
523 return; //nothing achieved
525 if (continuation
!== "reconnect") //TODO: bad HACK...
527 let modalBox
= document
.getElementById("modal-newgame");
528 modalBox
.checked
= true;
529 setTimeout(() => { modalBox
.checked
= false; }, 2000);
533 this.vr
= new VariantRules(fen
, moves
|| []);
535 this.incheck
= []; //in case of
536 this.fenStart
= continuation
537 ? localStorage
.getItem("fenStart")
538 : fen
.split(" ")[0]; //Only the position matters
544 // Not playing sound on game continuation:
545 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
546 document
.getElementById("modal-newgame").checked
= false;
549 this.oppConnected
= true;
550 this.mycolor
= color
;
552 if (!!moves
&& moves
.length
> 0) //imply continuation
554 const oppCol
= this.vr
.turn
;
555 const lastMove
= moves
[moves
.length
-1];
556 this.vr
.undo(lastMove
);
557 this.incheck
= this.vr
.getCheckSquares(lastMove
, oppCol
);
558 this.vr
.play(lastMove
, "ingame");
560 delete localStorage
["newgame"];
561 this.setStorage(); //in case of interruptions
563 else //against computer
565 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
566 if (this.mycolor
== 'b')
567 setTimeout(this.playComputerMove
, 500);
570 playComputerMove: function() {
571 const compColor
= this.mycolor
=='w' ? 'b' : 'w';
572 const compMove
= this.vr
.getComputerMove(compColor
);
573 // HACK: avoid selecting elements before they appear on page:
574 setTimeout(() => this.play(compMove
, "animate"), 500);
576 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
577 getSquareId: function(o
) {
578 // NOTE: a separator is required to allow any size of board
579 return "sq-" + o
.x
+ "-" + o
.y
;
582 getSquareFromId: function(id
) {
583 let idParts
= id
.split('-');
584 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
586 mousedown: function(e
) {
587 e
= e
|| window
.event
;
588 e
.preventDefault(); //disable native drag & drop
589 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
591 // Next few lines to center the piece on mouse cursor
592 let rect
= e
.target
.parentNode
.getBoundingClientRect();
594 x: rect
.x
+ rect
.width
/2,
595 y: rect
.y
+ rect
.width
/2,
596 id: e
.target
.parentNode
.id
598 this.selectedPiece
= e
.target
.cloneNode();
599 this.selectedPiece
.style
.position
= "absolute";
600 this.selectedPiece
.style
.top
= 0;
601 this.selectedPiece
.style
.display
= "inline-block";
602 this.selectedPiece
.style
.zIndex
= 3000;
603 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
604 this.possibleMoves
= this.vr
.canIplay(this.mycolor
,startSquare
)
605 ? this.vr
.getPossibleMovesFrom(startSquare
)
607 e
.target
.parentNode
.appendChild(this.selectedPiece
);
610 mousemove: function(e
) {
611 if (!this.selectedPiece
)
613 e
= e
|| window
.event
;
614 // If there is an active element, move it around
615 if (!!this.selectedPiece
)
617 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
618 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
621 mouseup: function(e
) {
622 if (!this.selectedPiece
)
624 e
= e
|| window
.event
;
625 // Read drop target (or parentElement, parentNode... if type == "img")
626 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
627 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
628 this.selectedPiece
.style
.zIndex
= 3000;
629 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
630 landing
= landing
.parentNode
;
631 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
633 // OK: process move attempt
634 let endSquare
= this.getSquareFromId(landing
.id
);
635 let moves
= this.findMatchingMoves(endSquare
);
636 this.possibleMoves
= [];
637 if (moves
.length
> 1)
638 this.choices
= moves
;
639 else if (moves
.length
==1)
641 // Else: impossible move
642 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
643 delete this.selectedPiece
;
644 this.selectedPiece
= null;
646 findMatchingMoves: function(endSquare
) {
647 // Run through moves list and return the matching set (if promotions...)
649 this.possibleMoves
.forEach(function(m
) {
650 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
655 animateMove: function(move) {
656 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
657 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
658 let rectStart
= startSquare
.getBoundingClientRect();
659 let rectEnd
= endSquare
.getBoundingClientRect();
660 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
661 let movingPiece
= document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
662 // HACK for animation (otherwise with positive translate, image slides "under background"...)
663 // Possible improvement: just alter squares on the piece's way...
664 squares
= document
.getElementsByClassName("board");
665 for (let i
=0; i
<squares
.length
; i
++)
667 let square
= squares
.item(i
);
668 if (square
.id
!= this.getSquareId(move.start
))
669 square
.style
.zIndex
= "-1";
671 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
672 movingPiece
.style
.transitionDuration
= "0.2s";
673 movingPiece
.style
.zIndex
= "3000";
675 for (let i
=0; i
<squares
.length
; i
++)
676 squares
.item(i
).style
.zIndex
= "auto";
677 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
681 play: function(move, programmatic
) {
682 if (!!programmatic
) //computer or human opponent
684 this.animateMove(move);
687 const oppCol
= this.vr
.getOppCol(this.vr
.turn
);
688 this.incheck
= this.vr
.getCheckSquares(move, oppCol
); //is opponent in check?
689 // Not programmatic, or animation is over
690 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
691 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
692 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
693 this.vr
.play(move, "ingame");
694 if (this.mode
== "human")
695 this.updateStorage(); //after our moves and opponent moves
696 const eog
= this.vr
.checkGameOver(this.vr
.turn
);
699 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
700 setTimeout(this.playComputerMove
, 500);