1 // Game logic on a variant page
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... (as moves)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket connection
12 score: "*", //'*' means 'unfinished'
13 mode: "idle", //human, friend, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
20 hints: (getCookie("hints") === "1" ? true : false),
21 color: getCookie("color", "lichess"), //lichess, chesscom or chesstempo
22 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
23 sound: getCookie("sound", "2"),
27 const [sizeX
,sizeY
] = VariantRules
.size
;
28 const smallScreen
= (screen
.width
<= 420);
29 // Precompute hints squares to facilitate rendering
30 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
31 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
32 // Also precompute in-check squares
33 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
34 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
35 let elementArray
= [];
40 on: { click: this.clickGameSeek
},
41 attrs: { "aria-label": 'New online game' },
44 "bottom": true, //display below
46 "playing": this.mode
== "human",
50 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
52 if (["idle","computer"].includes(this.mode
))
57 on: { click: this.clickComputerGame
},
58 attrs: { "aria-label": 'New game VS computer' },
62 "playing": this.mode
== "computer",
66 [h('i', { 'class': { "material-icons": true } }, "computer")])
69 if (["idle","friend"].includes(this.mode
))
74 on: { click: this.clickFriendGame
},
75 attrs: { "aria-label": 'New IRL game' },
79 "playing": this.mode
== "friend",
83 [h('i', { 'class': { "material-icons": true } }, "people")])
88 const square00
= document
.getElementById("sq-0-0");
89 const squareWidth
= !!square00
90 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
92 const settingsBtnElt
= document
.getElementById("settingsBtn");
93 const indicWidth
= !!settingsBtnElt
//-2 for border:
94 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
95 : 37; //TODO: always 37?
96 if (this.mode
== "human")
98 let connectedIndic
= h(
102 "topindicator": true,
104 "connected": this.oppConnected
,
105 "disconnected": !this.oppConnected
,
108 "width": indicWidth
+ "px",
109 "height": indicWidth
+ "px",
113 elementArray
.push(connectedIndic
);
119 "topindicator": true,
121 "white-turn": this.vr
.turn
=="w",
122 "black-turn": this.vr
.turn
=="b",
125 "width": indicWidth
+ "px",
126 "height": indicWidth
+ "px",
130 elementArray
.push(turnIndic
);
134 on: { click: this.showSettings
},
136 "aria-label": 'Settings',
141 "topindicator": true,
143 "settings-btn": true,
146 [h('i', { 'class': { "material-icons": true } }, "settings")]
148 elementArray
.push(settingsBtn
);
149 let choices
= h('div',
151 attrs: { "id": "choices" },
152 'class': { 'row': true },
154 "display": this.choices
.length
>0?"block":"none",
155 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
156 "width": (this.choices
.length
* squareWidth
) + "px",
157 "height": squareWidth
+ "px",
160 this.choices
.map( m
=> { //a "choice" is a move
165 ['board'+sizeY
]: true,
168 'width': (100/this.choices
.length
) + "%",
169 'padding-bottom': (100/this.choices
.length
) + "%",
174 attrs: { "src": '/images/pieces/' +
175 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
176 'class': { 'choice-piece': true },
177 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
183 // Create board element (+ reserves if needed by variant or mode)
184 let gameDiv
= h('div',
186 'class': { 'game': true },
188 [_
.range(sizeX
).map(i
=> {
189 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
196 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
198 _
.range(sizeY
).map(j
=> {
199 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
201 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
209 'ghost': !!this.selectedPiece
210 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
213 src: "/images/pieces/" +
214 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
220 if (this.hints
&& hintSquares
[ci
][cj
])
230 src: "/images/mark.svg",
236 const lm
= this.vr
.lastMove
;
237 const showLight
= this.hints
&&
238 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
244 ['board'+sizeY
]: true,
245 'light-square': (i
+j
)%2==0,
246 'dark-square': (i
+j
)%2==1,
248 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
249 'incheck': showLight
&& incheckSq
[ci
][cj
],
252 id: this.getSquareId({x:ci
,y:cj
}),
261 if (this.mode
!= "idle")
266 on: { click: this.resign
},
267 attrs: { "aria-label": 'Resign' },
271 "small": smallScreen
,
274 [h('i', { 'class': { "material-icons": true } }, "flag")])
277 else if (this.vr
.moves
.length
> 0)
279 // A game finished, and another is not started yet: allow navigation
280 actionArray
= actionArray
.concat([
283 on: { click: e
=> this.undo() },
284 attrs: { "aria-label": 'Undo' },
286 "small": smallScreen
,
290 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
293 on: { click: e
=> this.play() },
294 attrs: { "aria-label": 'Play' },
295 "class": { "small": smallScreen
},
297 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
301 if (this.mode
== "friend")
303 actionArray
= actionArray
.concat(
307 on: { click: this.undoInGame
},
308 attrs: { "aria-label": 'Undo' },
310 "small": smallScreen
,
314 [h('i', { 'class': { "material-icons": true } }, "undo")]
318 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
319 attrs: { "aria-label": 'Flip' },
320 "class": { "small": smallScreen
},
322 [h('i', { 'class': { "material-icons": true } }, "cached")]
326 elementArray
.push(gameDiv
);
327 if (!!this.vr
.reserve
)
329 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
330 let myReservePiecesArray
= [];
331 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
333 myReservePiecesArray
.push(h('div',
335 'class': {'board':true, ['board'+sizeY
]:true},
336 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
341 'class': {"piece":true},
343 "src": "/images/pieces/" +
344 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
348 {"class": { "reserve-count": true } },
349 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
353 let oppReservePiecesArray
= [];
354 const oppCol
= this.vr
.getOppCol(this.mycolor
);
355 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
357 oppReservePiecesArray
.push(h('div',
359 'class': {'board':true, ['board'+sizeY
]:true},
360 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
365 'class': {"piece":true},
367 "src": "/images/pieces/" +
368 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
372 {"class": { "reserve-count": true } },
373 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
377 let reserves
= h('div',
389 "reserve-row-1": true,
395 { 'class': { 'row': true }},
396 oppReservePiecesArray
400 elementArray
.push(reserves
);
402 const eogMessage
= this.getEndgameMessage(this.score
);
406 attrs: { "id": "modal-eog", type: "checkbox" },
407 "class": { "modal": true },
411 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
416 "class": { "card": true, "smallpad": true },
421 attrs: { "for": "modal-eog" },
422 "class": { "modal-close": true },
427 "class": { "section": true },
428 domProps: { innerHTML: eogMessage
},
436 elementArray
= elementArray
.concat(modalEog
);
438 // TODO: next 3 modals in (pug) view directly?!
439 const modalNewgame
= [
442 attrs: { "id": "modal-newgame", type: "checkbox" },
443 "class": { "modal": true },
447 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
452 "class": { "card": true, "smallpad": true },
457 attrs: { "id": "close-newgame", "for": "modal-newgame" },
458 "class": { "modal-close": true },
463 "class": { "section": true },
464 domProps: { innerHTML: "New game" },
469 "class": { "section": true },
470 domProps: { innerHTML: "Waiting for opponent..." },
478 elementArray
= elementArray
.concat(modalNewgame
);
479 const modalFenEdit
= [
482 attrs: { "id": "modal-fenedit", type: "checkbox" },
483 "class": { "modal": true },
487 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
492 "class": { "card": true, "smallpad": true },
497 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
498 "class": { "modal-close": true },
503 "class": { "section": true },
504 domProps: { innerHTML: "Position + flags (FEN):" },
512 value: VariantRules
.GenRandInitFen(),
520 const fen
= document
.getElementById("input-fen").value
;
521 document
.getElementById("modal-fenedit").checked
= false;
522 this.newGame("friend", fen
);
525 domProps: { innerHTML: "Ok" },
532 document
.getElementById("input-fen").value
=
533 VariantRules
.GenRandInitFen();
536 domProps: { innerHTML: "Random" },
544 elementArray
= elementArray
.concat(modalFenEdit
);
545 const modalSettings
= [
548 attrs: { "id": "modal-settings", type: "checkbox" },
549 "class": { "modal": true },
553 attrs: { "role": "dialog", "aria-labelledby": "modal-settings" },
558 "class": { "card": true, "smallpad": true },
563 attrs: { "id": "close-settings", "for": "modal-settings" },
564 "class": { "modal-close": true },
569 "class": { "section": true },
570 domProps: { innerHTML: "Preferences" },
573 // https://minicss.org/docs#forms-and-input
588 domProps: { innerHTML: "Show hints?" },
591 h('p', { domProps: { innerHTML: "TODO: board(color)" } }),
592 h('p', { domProps: { innerHTML: "TODO: sound(level)" } }),
598 elementArray
= elementArray
.concat(modalSettings
);
599 const actions
= h('div',
601 attrs: { "id": "actions" },
602 'class': { 'text-center': true },
606 elementArray
.push(actions
);
607 if (this.score
!= "*")
611 { attrs: { id: "pgn-div" } },
623 attrs: { id: "pgn-game" },
624 on: { click: this.download
},
625 domProps: { innerHTML: this.pgnTxt
}
632 else if (this.mode
!= "idle")
637 { attrs: { id: "fen-div" } },
641 attrs: { id: "fen-string" },
642 domProps: { innerHTML: this.vr
.getFen() }
655 "col-md-offset-2":true,
657 "col-lg-offset-3":true,
659 // NOTE: click = mousedown + mouseup
661 mousedown: this.mousedown
,
662 mousemove: this.mousemove
,
663 mouseup: this.mouseup
,
664 touchstart: this.mousedown
,
665 touchmove: this.mousemove
,
666 touchend: this.mouseup
,
672 created: function() {
673 const url
= socketUrl
;
674 const continuation
= (localStorage
.getItem("variant") === variant
);
675 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
678 // HACK: play a small silent sound to allow "new game" sound later
679 // if tab not focused (TODO: does it really work ?!)
680 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
682 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
683 const socketOpenListener
= () => {
686 const fen
= localStorage
.getItem("fen");
687 const mycolor
= localStorage
.getItem("mycolor");
688 const oppid
= localStorage
.getItem("oppid");
689 const moves
= JSON
.parse(localStorage
.getItem("moves"));
690 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
691 // Send ping to server (answer pong if opponent is connected)
692 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
694 else if (localStorage
.getItem("newgame") === variant
)
696 // New game request has been cancelled on disconnect
697 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
700 const socketMessageListener
= msg
=> {
701 const data
= JSON
.parse(msg
.data
);
704 case "newgame": //opponent found
705 // oppid: opponent socket ID
706 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
708 case "newmove": //..he played!
709 this.play(data
.move, "animate");
711 case "pong": //received if we sent a ping (game still alive on our side)
712 this.oppConnected
= true;
713 const L
= this.vr
.moves
.length
;
714 // Send our "last state" informations to opponent
715 this.conn
.send(JSON
.stringify({
718 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
722 case "lastate": //got opponent infos about last move (we might have resigned)
723 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
726 this.conn
.send(JSON
.stringify({
733 else if (data
.movesCount
< 0)
736 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
738 else if (data
.movesCount
< this.vr
.moves
.length
)
740 // We must tell last move to opponent
741 const L
= this.vr
.moves
.length
;
742 this.conn
.send(JSON
.stringify({
745 lastMove:this.vr
.moves
[L
-1],
749 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
750 this.play(data
.lastMove
, "animate");
752 case "resign": //..you won!
753 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
755 // TODO: also use (dis)connect info to count online players?
758 if (this.mode
== "human" && this.oppid
== data
.id
)
759 this.oppConnected
= (data
.code
== "connect");
763 const socketCloseListener
= () => {
764 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
765 this.conn
.addEventListener('open', socketOpenListener
);
766 this.conn
.addEventListener('message', socketMessageListener
);
767 this.conn
.addEventListener('close', socketCloseListener
);
769 this.conn
.onopen
= socketOpenListener
;
770 this.conn
.onmessage
= socketMessageListener
;
771 this.conn
.onclose
= socketCloseListener
;
772 // Listen to keyboard left/right to navigate in game
773 document
.onkeydown
= event
=> {
774 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
775 && [37,39].includes(event
.keyCode
))
777 event
.preventDefault();
778 if (event
.keyCode
== 37) //Back
786 download: function() {
787 let content
= document
.getElementById("pgn-game").innerHTML
;
788 content
= content
.replace(/<br>/g, "\n");
789 // Prepare and trigger download link
790 let downloadAnchor
= document
.getElementById("download");
791 downloadAnchor
.setAttribute("download", "game.pgn");
792 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
793 encodeURIComponent(content
);
794 downloadAnchor
.click();
796 endGame: function(score
) {
798 let modalBox
= document
.getElementById("modal-eog");
799 modalBox
.checked
= true;
800 // Variants may have special PGN structure (so next function isn't defined here)
801 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
802 setTimeout(() => { modalBox
.checked
= false; }, 2000);
803 if (this.mode
== "human")
806 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
809 getEndgameMessage: function(score
) {
810 let eogMessage
= "Unfinished";
814 eogMessage
= "White win";
817 eogMessage
= "Black win";
825 setStorage: function() {
826 localStorage
.setItem("myid", this.myid
);
827 localStorage
.setItem("variant", variant
);
828 localStorage
.setItem("mycolor", this.mycolor
);
829 localStorage
.setItem("oppid", this.oppid
);
830 localStorage
.setItem("fenStart", this.fenStart
);
831 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
832 localStorage
.setItem("fen", this.vr
.getFen());
834 updateStorage: function() {
835 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
836 localStorage
.setItem("fen", this.vr
.getFen());
838 clearStorage: function() {
839 delete localStorage
["variant"];
840 delete localStorage
["myid"];
841 delete localStorage
["mycolor"];
842 delete localStorage
["oppid"];
843 delete localStorage
["fenStart"];
844 delete localStorage
["fen"];
845 delete localStorage
["moves"];
847 // HACK because mini-css tooltips are persistent after click...
848 getRidOfTooltip: function(elt
) {
849 elt
.style
.visibility
= "hidden";
850 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
852 showSettings: function(e
) {
853 this.getRidOfTooltip(e
.currentTarget
);
854 document
.getElementById("modal-settings").checked
= true;
856 toggleHints: function() {
857 this.hints
= !this.hints
;
858 setCookie("hints", this.hints
? "1" : "0");
860 clickGameSeek: function(e
) {
861 this.getRidOfTooltip(e
.currentTarget
);
862 if (this.mode
== "human")
863 return; //no newgame while playing
866 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
867 delete localStorage
["newgame"]; //cancel game seek
871 this.newGame("human");
873 clickComputerGame: function(e
) {
874 this.getRidOfTooltip(e
.currentTarget
);
875 if (this.mode
== "human")
876 return; //no newgame while playing
877 this.newGame("computer");
879 clickFriendGame: function(e
) {
880 this.getRidOfTooltip(e
.currentTarget
);
881 document
.getElementById("modal-fenedit").checked
= true;
883 resign: function(e
) {
884 this.getRidOfTooltip(e
.currentTarget
);
885 if (this.mode
== "human" && this.oppConnected
)
888 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
889 } catch (INVALID_STATE_ERR
) {
890 return; //socket is not ready (and not yet reconnected)
893 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
895 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
896 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
897 console
.log(fen
); //DEBUG
898 if (mode
=="human" && !oppId
)
900 const storageVariant
= localStorage
.getItem("variant");
901 if (!!storageVariant
&& storageVariant
!== variant
)
903 alert("Finish your " + storageVariant
+ " game first!");
906 // Send game request and wait..
907 localStorage
["newgame"] = variant
;
909 this.clearStorage(); //in case of
911 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
912 } catch (INVALID_STATE_ERR
) {
913 return; //nothing achieved
915 if (continuation
!== "reconnect") //TODO: bad HACK...
917 let modalBox
= document
.getElementById("modal-newgame");
918 modalBox
.checked
= true;
919 setTimeout(() => { modalBox
.checked
= false; }, 2000);
923 this.vr
= new VariantRules(fen
, moves
|| []);
925 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
927 this.incheck
= []; //in case of
928 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
934 // Not playing sound on game continuation:
935 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
936 document
.getElementById("modal-newgame").checked
= false;
939 this.oppConnected
= true;
940 this.mycolor
= color
;
942 if (!!moves
&& moves
.length
> 0) //imply continuation
944 const lastMove
= moves
[moves
.length
-1];
945 this.vr
.undo(lastMove
);
946 this.incheck
= this.vr
.getCheckSquares(lastMove
);
947 this.vr
.play(lastMove
, "ingame");
949 delete localStorage
["newgame"];
950 this.setStorage(); //in case of interruptions
952 else if (mode
== "computer")
954 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
955 if (this.mycolor
== 'b')
956 setTimeout(this.playComputerMove
, 500);
958 //else: against a (IRL) friend: nothing more to do
960 playComputerMove: function() {
961 const timeStart
= Date
.now();
962 const compMove
= this.vr
.getComputerMove();
963 // (first move) HACK: avoid selecting elements before they appear on page:
964 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
965 setTimeout(() => this.play(compMove
, "animate"), delay
);
967 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
968 getSquareId: function(o
) {
969 // NOTE: a separator is required to allow any size of board
970 return "sq-" + o
.x
+ "-" + o
.y
;
973 getSquareFromId: function(id
) {
974 let idParts
= id
.split('-');
975 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
977 mousedown: function(e
) {
978 e
= e
|| window
.event
;
981 while (!ingame
&& elem
!== null)
983 if (elem
.classList
.contains("game"))
988 elem
= elem
.parentElement
;
990 if (!ingame
) //let default behavior (click on button...)
992 e
.preventDefault(); //disable native drag & drop
993 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
995 // Next few lines to center the piece on mouse cursor
996 let rect
= e
.target
.parentNode
.getBoundingClientRect();
998 x: rect
.x
+ rect
.width
/2,
999 y: rect
.y
+ rect
.width
/2,
1000 id: e
.target
.parentNode
.id
1002 this.selectedPiece
= e
.target
.cloneNode();
1003 this.selectedPiece
.style
.position
= "absolute";
1004 this.selectedPiece
.style
.top
= 0;
1005 this.selectedPiece
.style
.display
= "inline-block";
1006 this.selectedPiece
.style
.zIndex
= 3000;
1007 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1008 const iCanPlay
= this.mode
!="idle"
1009 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
1010 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
1011 // Next line add moving piece just after current image
1012 // (required for Crazyhouse reserve)
1013 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1016 mousemove: function(e
) {
1017 if (!this.selectedPiece
)
1019 e
= e
|| window
.event
;
1020 // If there is an active element, move it around
1021 if (!!this.selectedPiece
)
1023 const [offsetX
,offsetY
] = !!e
.clientX
1024 ? [e
.clientX
,e
.clientY
] //desktop browser
1025 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1026 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1027 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1030 mouseup: function(e
) {
1031 if (!this.selectedPiece
)
1033 e
= e
|| window
.event
;
1034 // Read drop target (or parentElement, parentNode... if type == "img")
1035 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1036 const [offsetX
,offsetY
] = !!e
.clientX
1037 ? [e
.clientX
,e
.clientY
]
1038 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1039 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1040 this.selectedPiece
.style
.zIndex
= 3000;
1041 // Next condition: classList.contains(piece) fails because of marks
1042 while (landing
.tagName
== "IMG")
1043 landing
= landing
.parentNode
;
1044 if (this.start
.id
== landing
.id
)
1046 // A click: selectedPiece and possibleMoves are already filled
1049 // OK: process move attempt
1050 let endSquare
= this.getSquareFromId(landing
.id
);
1051 let moves
= this.findMatchingMoves(endSquare
);
1052 this.possibleMoves
= [];
1053 if (moves
.length
> 1)
1054 this.choices
= moves
;
1055 else if (moves
.length
==1)
1056 this.play(moves
[0]);
1057 // Else: impossible move
1058 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1059 delete this.selectedPiece
;
1060 this.selectedPiece
= null;
1062 findMatchingMoves: function(endSquare
) {
1063 // Run through moves list and return the matching set (if promotions...)
1065 this.possibleMoves
.forEach(function(m
) {
1066 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1071 animateMove: function(move) {
1072 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1073 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1074 let rectStart
= startSquare
.getBoundingClientRect();
1075 let rectEnd
= endSquare
.getBoundingClientRect();
1076 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1078 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1079 // HACK for animation (with positive translate, image slides "under background")
1080 // Possible improvement: just alter squares on the piece's way...
1081 squares
= document
.getElementsByClassName("board");
1082 for (let i
=0; i
<squares
.length
; i
++)
1084 let square
= squares
.item(i
);
1085 if (square
.id
!= this.getSquareId(move.start
))
1086 square
.style
.zIndex
= "-1";
1088 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1089 translation
.y
+ "px)";
1090 movingPiece
.style
.transitionDuration
= "0.2s";
1091 movingPiece
.style
.zIndex
= "3000";
1093 for (let i
=0; i
<squares
.length
; i
++)
1094 squares
.item(i
).style
.zIndex
= "auto";
1095 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1099 play: function(move, programmatic
) {
1102 // Navigate after game is over
1103 if (this.cursor
>= this.vr
.moves
.length
)
1104 return; //already at the end
1105 move = this.vr
.moves
[this.cursor
++];
1107 if (!!programmatic
) //computer or human opponent
1109 this.animateMove(move);
1112 // Not programmatic, or animation is over
1113 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1114 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1115 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1116 if (this.mode
!= "idle")
1118 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1119 this.vr
.play(move, "ingame");
1123 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1124 this.$forceUpdate(); //TODO: ?!
1126 if (this.mode
== "human")
1127 this.updateStorage(); //after our moves and opponent moves
1128 if (this.mode
!= "idle")
1130 const eog
= this.vr
.checkGameOver();
1134 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1135 setTimeout(this.playComputerMove
, 500);
1138 // Navigate after game is over
1139 if (this.cursor
== 0)
1140 return; //already at the beginning
1141 if (this.cursor
== this.vr
.moves
.length
)
1142 this.incheck
= []; //in case of...
1143 const move = this.vr
.moves
[--this.cursor
];
1144 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1145 this.$forceUpdate(); //TODO: ?!
1147 undoInGame: function() {
1148 const lm
= this.vr
.lastMove
;