1b216efae937c63afda5cc41cdd17dbd0110b2c0
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();
398 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
399 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
401 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
402 const socketOpenListener
= () => {
405 const fen
= localStorage
.getItem("fen");
406 const mycolor
= localStorage
.getItem("mycolor");
407 const oppid
= localStorage
.getItem("oppid");
408 const moves
= JSON
.parse(localStorage
.getItem("moves"));
409 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
410 // Send ping to server (answer pong if opponent is connected)
411 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
413 else if (localStorage
.getItem("newgame") === variant
)
415 // New game request has been cancelled on disconnect
417 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
420 const socketMessageListener
= msg
=> {
421 const data
= JSON
.parse(msg
.data
);
424 case "newgame": //opponent found
425 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
427 case "newmove": //..he played!
428 this.play(data
.move, "animate");
430 case "pong": //received if we sent a ping (game still alive on our side)
431 this.oppConnected
= true;
432 const L
= this.vr
.moves
.length
;
433 // Send our "last state" informations to opponent
434 this.conn
.send(JSON
.stringify({
437 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
441 case "lastate": //got opponent infos about last move (we might have resigned)
442 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
445 this.conn
.send(JSON
.stringify({
452 else if (data
.movesCount
< 0)
455 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
457 else if (data
.movesCount
< this.vr
.moves
.length
)
459 // We must tell last move to opponent
460 const L
= this.vr
.moves
.length
;
461 this.conn
.send(JSON
.stringify({
464 lastMove:this.vr
.moves
[L
-1],
468 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
469 this.play(data
.lastMove
, "animate");
471 case "resign": //..you won!
472 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
474 // TODO: also use (dis)connect info to count online players?
477 if (this.mode
== "human" && this.oppid
== data
.id
)
478 this.oppConnected
= (data
.code
== "connect");
482 const socketCloseListener
= () => {
483 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
484 this.conn
.addEventListener('open', socketOpenListener
);
485 this.conn
.addEventListener('message', socketMessageListener
);
486 this.conn
.addEventListener('close', socketCloseListener
);
488 this.conn
.onopen
= socketOpenListener
;
489 this.conn
.onmessage
= socketMessageListener
;
490 this.conn
.onclose
= socketCloseListener
;
493 download: function() {
494 let content
= document
.getElementById("pgn-game").innerHTML
;
495 content
= content
.replace(/<br>/g, "\n");
496 // Prepare and trigger download link
497 let downloadAnchor
= document
.getElementById("download");
498 downloadAnchor
.setAttribute("download", "game.pgn");
499 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
500 downloadAnchor
.click();
502 endGame: function(score
) {
504 let modalBox
= document
.getElementById("modal-eog");
505 modalBox
.checked
= true;
506 // Variants may have special PGN structure (so next function isn't defined here)
507 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
508 setTimeout(() => { modalBox
.checked
= false; }, 2000);
509 if (this.mode
== "human")
514 getEndgameMessage: function(score
) {
515 let eogMessage
= "Unfinished";
519 eogMessage
= "White win";
522 eogMessage
= "Black win";
530 toggleExpertMode: function() {
531 this.expert
= !this.expert
;
532 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
535 if (this.mode
== "human" && this.oppConnected
)
538 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
539 } catch (INVALID_STATE_ERR
) {
540 return; //socket is not ready (and not yet reconnected)
543 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
545 setStorage: function() {
546 localStorage
.setItem("myid", this.myid
);
547 localStorage
.setItem("variant", variant
);
548 localStorage
.setItem("mycolor", this.mycolor
);
549 localStorage
.setItem("oppid", this.oppid
);
550 localStorage
.setItem("fenStart", this.fenStart
);
551 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
552 localStorage
.setItem("fen", this.vr
.getFen());
554 updateStorage: function() {
555 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
556 localStorage
.setItem("fen", this.vr
.getFen());
558 clearStorage: function() {
559 delete localStorage
["variant"];
560 delete localStorage
["myid"];
561 delete localStorage
["mycolor"];
562 delete localStorage
["oppid"];
563 delete localStorage
["fenStart"];
564 delete localStorage
["fen"];
565 delete localStorage
["moves"];
567 clickGameSeek: function() {
568 if (this.mode
== "human")
569 return; //no newgame while playing
572 delete localStorage
["newgame"]; //cancel game seek
576 this.newGame("human");
578 clickComputerGame: function() {
579 if (this.mode
== "human")
580 return; //no newgame while playing
581 this.newGame("computer");
583 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
584 //const fen = "1n2T1n0/p2pO2p/1s1k1s2/8/3S2p1/2U2cO1/P3PuPP/3K1BR1 0100";
585 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
586 console
.log(fen
); //DEBUG
588 if (mode
=="human" && !oppId
)
590 const storageVariant
= localStorage
.getItem("variant");
591 if (!!storageVariant
&& storageVariant
!== variant
)
593 alert("Finish your " + storageVariant
+ " game first!");
596 // Send game request and wait..
597 localStorage
["newgame"] = variant
;
599 this.clearStorage(); //in case of
601 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
602 } catch (INVALID_STATE_ERR
) {
603 return; //nothing achieved
605 if (continuation
!== "reconnect") //TODO: bad HACK...
607 let modalBox
= document
.getElementById("modal-newgame");
608 modalBox
.checked
= true;
609 setTimeout(() => { modalBox
.checked
= false; }, 2000);
613 this.vr
= new VariantRules(fen
, moves
|| []);
614 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
616 this.incheck
= []; //in case of
617 this.fenStart
= continuation
618 ? localStorage
.getItem("fenStart")
619 : fen
.split(" ")[0]; //Only the position matters
625 // Not playing sound on game continuation:
626 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
627 document
.getElementById("modal-newgame").checked
= false;
630 this.oppConnected
= true;
631 this.mycolor
= color
;
633 if (!!moves
&& moves
.length
> 0) //imply continuation
635 const lastMove
= moves
[moves
.length
-1];
636 this.vr
.undo(lastMove
);
637 this.incheck
= this.vr
.getCheckSquares(lastMove
);
638 this.vr
.play(lastMove
, "ingame");
640 delete localStorage
["newgame"];
641 this.setStorage(); //in case of interruptions
643 else //against computer
645 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
646 if (this.mycolor
== 'b')
647 setTimeout(this.playComputerMove
, 500);
650 playComputerMove: function() {
651 const timeStart
= Date
.now();
652 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
655 const L
= this.vr
.moves
.length
;
656 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
657 this.vr
.shouldReturn
= true;
659 const compMove
= this.vr
.getComputerMove();
660 // (first move) HACK: avoid selecting elements before they appear on page:
661 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
662 setTimeout(() => this.play(compMove
, "animate"), delay
);
664 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
665 getSquareId: function(o
) {
666 // NOTE: a separator is required to allow any size of board
667 return "sq-" + o
.x
+ "-" + o
.y
;
670 getSquareFromId: function(id
) {
671 let idParts
= id
.split('-');
672 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
674 mousedown: function(e
) {
675 e
= e
|| window
.event
;
676 e
.preventDefault(); //disable native drag & drop
677 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
679 // Next few lines to center the piece on mouse cursor
680 let rect
= e
.target
.parentNode
.getBoundingClientRect();
682 x: rect
.x
+ rect
.width
/2,
683 y: rect
.y
+ rect
.width
/2,
684 id: e
.target
.parentNode
.id
686 this.selectedPiece
= e
.target
.cloneNode();
687 this.selectedPiece
.style
.position
= "absolute";
688 this.selectedPiece
.style
.top
= 0;
689 this.selectedPiece
.style
.display
= "inline-block";
690 this.selectedPiece
.style
.zIndex
= 3000;
691 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
692 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
693 ? this.vr
.getPossibleMovesFrom(startSquare
)
695 e
.target
.parentNode
.appendChild(this.selectedPiece
);
698 mousemove: function(e
) {
699 if (!this.selectedPiece
)
701 e
= e
|| window
.event
;
702 // If there is an active element, move it around
703 if (!!this.selectedPiece
)
705 this.selectedPiece
.style
.left
= (e
.clientX
-this.start
.x
) + "px";
706 this.selectedPiece
.style
.top
= (e
.clientY
-this.start
.y
) + "px";
709 mouseup: function(e
) {
710 if (!this.selectedPiece
)
712 e
= e
|| window
.event
;
713 // Read drop target (or parentElement, parentNode... if type == "img")
714 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
715 let landing
= document
.elementFromPoint(e
.clientX
, e
.clientY
);
716 this.selectedPiece
.style
.zIndex
= 3000;
717 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
718 landing
= landing
.parentNode
;
719 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
721 // OK: process move attempt
722 let endSquare
= this.getSquareFromId(landing
.id
);
723 let moves
= this.findMatchingMoves(endSquare
);
724 this.possibleMoves
= [];
725 if (moves
.length
> 1)
726 this.choices
= moves
;
727 else if (moves
.length
==1)
729 // Else: impossible move
730 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
731 delete this.selectedPiece
;
732 this.selectedPiece
= null;
734 findMatchingMoves: function(endSquare
) {
735 // Run through moves list and return the matching set (if promotions...)
737 this.possibleMoves
.forEach(function(m
) {
738 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
743 animateMove: function(move) {
744 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
745 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
746 let rectStart
= startSquare
.getBoundingClientRect();
747 let rectEnd
= endSquare
.getBoundingClientRect();
748 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
750 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
751 // HACK for animation (with positive translate, image slides "under background"...)
752 // Possible improvement: just alter squares on the piece's way...
753 squares
= document
.getElementsByClassName("board");
754 for (let i
=0; i
<squares
.length
; i
++)
756 let square
= squares
.item(i
);
757 if (square
.id
!= this.getSquareId(move.start
))
758 square
.style
.zIndex
= "-1";
760 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
761 movingPiece
.style
.transitionDuration
= "0.2s";
762 movingPiece
.style
.zIndex
= "3000";
764 for (let i
=0; i
<squares
.length
; i
++)
765 squares
.item(i
).style
.zIndex
= "auto";
766 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
770 play: function(move, programmatic
) {
771 if (!!programmatic
) //computer or human opponent
773 this.animateMove(move);
776 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
777 // Not programmatic, or animation is over
778 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
779 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
780 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
781 this.vr
.play(move, "ingame");
782 if (this.mode
== "human")
783 this.updateStorage(); //after our moves and opponent moves
784 const eog
= this.vr
.checkGameOver();
787 else if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
788 setTimeout(this.playComputerMove
, 500);