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