Improved logic for playing against bots
[vchess.git] / client / src / components / BaseGame.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 input#modalEog.modal(type="checkbox")
5 div(role="dialog" aria-labelledby="eogMessage")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalEog")
8 h3#eogMessage.section {{ endgameMessage }}
834c202a
BA
9 Board(:vr="vr" :last-move="lastMove" :analyze="game.mode=='analyze'"
10 :user-color="game.mycolor" :orientation="orientation"
11 :vname="game.vname" @play-move="play")
a6088c90 12 .button-group
37cdcbf3
BA
13 button(@click="() => play()") Play
14 button(@click="() => undo()") Undo
a6088c90
BA
15 button(@click="flip") Flip
16 button(@click="gotoBegin") GotoBegin
17 button(@click="gotoEnd") GotoEnd
18 #fenDiv.section-content(v-if="showFen && !!vr")
19 p#fenString.text-center {{ vr.getFen() }}
20 #pgnDiv.section-content
21 a#download(href="#")
22 .button-group
23 button#downloadBtn(@click="download") {{ st.tr["Download PGN"] }}
24 button Import game
25 //MoveList(v-if="showMoves"
26 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
27</template>
28
29<script>
30import Board from "@/components/Board.vue";
31//import MoveList from "@/components/MoveList.vue";
32import { store } from "@/store";
33import { getSquareId } from "@/utils/squareId";
34
35export default {
36 name: 'my-base-game',
37 components: {
38 Board,
39 //MoveList,
40 },
bc8734ba 41 // "vr": VariantRules object, describing the game state + rules
834c202a 42 props: ["vr","game"],
a6088c90
BA
43 data: function() {
44 return {
45 st: store.state,
b7c32f1a 46 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
47 endgameMessage: "",
48 orientation: "w",
49 score: "*", //'*' means 'unfinished'
b7c32f1a 50 moves: [],
a6088c90
BA
51 cursor: -1, //index of the move just played
52 lastMove: null,
53 };
54 },
37cdcbf3 55 watch: {
834c202a
BA
56 // game initial FEN changes when a new game starts
57 "game.fenStart": function() {
37cdcbf3
BA
58 // Reset all variables
59 this.endgameMessage = "";
834c202a
BA
60 this.orientation = this.game.mycolor || "w"; //default orientation for observed games
61 this.score = this.game.score || "*"; //mutable (if initially "*")
62 this.moves = JSON.parse(JSON.stringify(this.game.moves || []));
4fe5664d
BA
63 const L = this.moves.length;
64 this.cursor = L-1;
65 this.lastMove = (L > 0 ? this.moves[L-1] : null);
37cdcbf3
BA
66 },
67 },
a6088c90
BA
68 computed: {
69 showMoves: function() {
70 return true;
71 //return window.innerWidth >= 768;
72 },
73 showFen: function() {
834c202a
BA
74 return this.game.vname != "Dark" || this.score != "*";
75 },
76 analyze: function() {
77 return this.game.mode == "analyze";
a6088c90
BA
78 },
79 },
80 methods: {
81 setEndgameMessage: function(score) {
82 let eogMessage = "Undefined";
83 switch (score)
84 {
85 case "1-0":
86 eogMessage = translations["White win"];
87 break;
88 case "0-1":
89 eogMessage = translations["Black win"];
90 break;
91 case "1/2":
92 eogMessage = translations["Draw"];
93 break;
94 case "?":
95 eogMessage = "Unfinished";
96 break;
97 }
98 this.endgameMessage = eogMessage;
99 },
100 download: function() {
101 const content = this.getPgn();
102 // Prepare and trigger download link
103 let downloadAnchor = document.getElementById("download");
104 downloadAnchor.setAttribute("download", "game.pgn");
105 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
106 downloadAnchor.click();
107 },
108 getPgn: function() {
109 let pgn = "";
110 pgn += '[Site "vchess.club"]\n';
834c202a 111 pgn += '[Variant "' + this.game.vname + '"]\n';
a6088c90 112 pgn += '[Date "' + getDate(new Date()) + '"]\n';
834c202a
BA
113 pgn += '[White "' + this.game.players[0] + '"]\n';
114 pgn += '[Black "' + this.game.players[1] + '"]\n';
115 pgn += '[Fen "' + this.game.fenStart + '"]\n';
a6088c90
BA
116 pgn += '[Result "' + this.score + '"]\n\n';
117 let counter = 1;
118 let i = 0;
119 while (i < this.moves.length)
120 {
121 pgn += (counter++) + ".";
122 for (let color of ["w","b"])
123 {
124 let move = "";
125 while (i < this.moves.length && this.moves[i].color == color)
126 move += this.moves[i++].notation[0] + ",";
127 move = move.slice(0,-1); //remove last comma
128 pgn += move + (i < this.moves.length-1 ? " " : "");
129 }
130 }
131 return pgn + "\n";
132 },
133 showScoreMsg: function(score) {
134 this.setEndgameMessage(score);
4494c17c 135 let modalBox = document.getElementById("modalEog");
a6088c90
BA
136 modalBox.checked = true;
137 setTimeout(() => { modalBox.checked = false; }, 2000);
138 },
139 endGame: function(score) {
140 this.score = score;
141 this.showScoreMsg(score);
834c202a 142 this.$emit("gameover"); //score not required (TODO?)
a6088c90
BA
143 },
144 animateMove: function(move) {
145 let startSquare = document.getElementById(getSquareId(move.start));
146 let endSquare = document.getElementById(getSquareId(move.end));
147 let rectStart = startSquare.getBoundingClientRect();
148 let rectEnd = endSquare.getBoundingClientRect();
149 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
150 let movingPiece =
151 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
152 // HACK for animation (with positive translate, image slides "under background")
153 // Possible improvement: just alter squares on the piece's way...
154 const squares = document.getElementsByClassName("board");
155 for (let i=0; i<squares.length; i++)
156 {
157 let square = squares.item(i);
158 if (square.id != getSquareId(move.start))
159 square.style.zIndex = "-1";
160 }
161 movingPiece.style.transform = "translate(" + translation.x + "px," +
162 translation.y + "px)";
163 movingPiece.style.transitionDuration = "0.2s";
164 movingPiece.style.zIndex = "3000";
165 setTimeout( () => {
166 for (let i=0; i<squares.length; i++)
167 squares.item(i).style.zIndex = "auto";
168 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
169 this.play(move);
170 }, 250);
171 },
172 play: function(move, programmatic) {
173 let navigate = !move;
174 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
175 // (except if we receive opponent's move, human or computer)
176 if (!navigate && !this.analyze && !programmatic
177 && this.cursor < this.moves.length-1)
178 {
179 return;
180 }
181 if (navigate)
182 {
183 if (this.cursor == this.moves.length-1)
184 return; //no more moves
185 move = this.moves[this.cursor+1];
186 }
187 if (!!programmatic) //computer or (remote) human opponent
188 {
189 if (this.cursor < this.moves.length-1)
190 this.gotoEnd(); //required to play the move
191 return this.animateMove(move);
192 }
193 // Not programmatic, or animation is over
194 if (!move.notation)
195 move.notation = this.vr.getNotation(move);
196 if (!move.color)
197 move.color = this.vr.turn;
198 this.vr.play(move);
199 this.cursor++;
200 this.lastMove = move;
201 if (!move.fen)
202 move.fen = this.vr.getFen();
203 if (this.st.settings.sound == 2)
204 new Audio("/sounds/move.mp3").play().catch(err => {});
a6088c90
BA
205 if (!navigate && (this.score == "*" || this.analyze))
206 {
207 // Stack move on movesList at current cursor
208 if (this.cursor == this.moves.length)
209 this.moves.push(move);
210 else
211 this.moves = this.moves.slice(0,this.cursor).concat([move]);
212 }
213 // Is opponent in check?
214 this.incheck = this.vr.getCheckSquares(this.vr.turn);
215 const score = this.vr.getCurrentScore();
216 if (score != "*")
217 {
218 if (!this.analyze)
219 this.endGame(score);
220 else //just show score on screen (allow undo)
221 this.showScoreMsg(score);
222 }
4494c17c
BA
223 if (!this.analyze)
224 this.$emit("newmove", move); //post-processing (e.g. computer play)
a6088c90
BA
225 },
226 undo: function(move) {
227 let navigate = !move;
228 if (navigate)
229 {
230 if (this.cursor < 0)
231 return; //no more moves
232 move = this.moves[this.cursor];
233 }
234 this.vr.undo(move);
235 this.cursor--;
236 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
237 if (this.st.settings.sound == 2)
238 new Audio("/sounds/undo.mp3").play().catch(err => {});
239 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4494c17c 240 if (!navigate)
a6088c90
BA
241 this.moves.pop();
242 },
243 gotoMove: function(index) {
37cdcbf3 244 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
245 this.cursor = index;
246 this.lastMove = this.moves[index];
247 },
248 gotoBegin: function() {
834c202a 249 this.vr.re_init(this.game.fenStart);
a6088c90
BA
250 this.cursor = -1;
251 this.lastMove = null;
252 },
253 gotoEnd: function() {
254 this.gotoMove(this.moves.length-1);
255 },
256 flip: function() {
257 this.orientation = V.GetNextCol(this.orientation);
258 },
259 },
260};
261</script>