Toward game info simplification
[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 }}
3d52a549
BA
9 Board(:vr="vr" :last-move="lastMove" :analyze="analyze"
10 :user-color="gameInfo.mycolor" :orientation="orientation"
11 :vname="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
13aa5a44
BA
42 // fenStart, players, mycolor
43 props: ["vname","analyze","vr","gameInfo"],
a6088c90
BA
44 data: function() {
45 return {
46 st: store.state,
b7c32f1a 47 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
48 endgameMessage: "",
49 orientation: "w",
50 score: "*", //'*' means 'unfinished'
b7c32f1a 51 moves: [],
a6088c90
BA
52 cursor: -1, //index of the move just played
53 lastMove: null,
54 };
55 },
37cdcbf3 56 watch: {
4fe5664d
BA
57 // gameInfo (immutable once set) changes when a new game starts
58 "gameInfo": function() {
37cdcbf3
BA
59 // Reset all variables
60 this.endgameMessage = "";
4fe5664d
BA
61 this.orientation = this.gameInfo.mycolor || "w"; //default orientation for observed games
62 this.score = this.gameInfo.score; //mutable (if initially "*")
63 this.moves = this.gameInfo.moves; //TODO: this is mutable; make a copy instead
64 const L = this.moves.length;
65 this.cursor = L-1;
66 this.lastMove = (L > 0 ? this.moves[L-1] : null);
37cdcbf3 67 },
4494c17c
BA
68 analyze: function() {
69 if (this.analyze)
70 {
71 // Switched to analyze mode: game is over
72 this.endGame("*");
73 }
74 },
37cdcbf3 75 },
a6088c90
BA
76 computed: {
77 showMoves: function() {
78 return true;
79 //return window.innerWidth >= 768;
80 },
81 showFen: function() {
b7c32f1a 82 return this.vname != "Dark" || this.score != "*";
a6088c90
BA
83 },
84 },
85 methods: {
86 setEndgameMessage: function(score) {
87 let eogMessage = "Undefined";
88 switch (score)
89 {
90 case "1-0":
91 eogMessage = translations["White win"];
92 break;
93 case "0-1":
94 eogMessage = translations["Black win"];
95 break;
96 case "1/2":
97 eogMessage = translations["Draw"];
98 break;
99 case "?":
100 eogMessage = "Unfinished";
101 break;
102 }
103 this.endgameMessage = eogMessage;
104 },
105 download: function() {
106 const content = this.getPgn();
107 // Prepare and trigger download link
108 let downloadAnchor = document.getElementById("download");
109 downloadAnchor.setAttribute("download", "game.pgn");
110 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
111 downloadAnchor.click();
112 },
113 getPgn: function() {
114 let pgn = "";
115 pgn += '[Site "vchess.club"]\n';
b7c32f1a 116 pgn += '[Variant "' + this.vname + '"]\n';
a6088c90 117 pgn += '[Date "' + getDate(new Date()) + '"]\n';
4fe5664d
BA
118 pgn += '[White "' + this.gameInfo.players[0] + '"]\n';
119 pgn += '[Black "' + this.gameInfo.players[1] + '"]\n';
120 pgn += '[Fen "' + this.gameInfo.fenStart + '"]\n';
a6088c90
BA
121 pgn += '[Result "' + this.score + '"]\n\n';
122 let counter = 1;
123 let i = 0;
124 while (i < this.moves.length)
125 {
126 pgn += (counter++) + ".";
127 for (let color of ["w","b"])
128 {
129 let move = "";
130 while (i < this.moves.length && this.moves[i].color == color)
131 move += this.moves[i++].notation[0] + ",";
132 move = move.slice(0,-1); //remove last comma
133 pgn += move + (i < this.moves.length-1 ? " " : "");
134 }
135 }
136 return pgn + "\n";
137 },
138 showScoreMsg: function(score) {
139 this.setEndgameMessage(score);
4494c17c 140 let modalBox = document.getElementById("modalEog");
a6088c90
BA
141 modalBox.checked = true;
142 setTimeout(() => { modalBox.checked = false; }, 2000);
143 },
144 endGame: function(score) {
145 this.score = score;
146 this.showScoreMsg(score);
147 this.$emit("game-over");
148 },
149 animateMove: function(move) {
150 let startSquare = document.getElementById(getSquareId(move.start));
151 let endSquare = document.getElementById(getSquareId(move.end));
152 let rectStart = startSquare.getBoundingClientRect();
153 let rectEnd = endSquare.getBoundingClientRect();
154 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
155 let movingPiece =
156 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
157 // HACK for animation (with positive translate, image slides "under background")
158 // Possible improvement: just alter squares on the piece's way...
159 const squares = document.getElementsByClassName("board");
160 for (let i=0; i<squares.length; i++)
161 {
162 let square = squares.item(i);
163 if (square.id != getSquareId(move.start))
164 square.style.zIndex = "-1";
165 }
166 movingPiece.style.transform = "translate(" + translation.x + "px," +
167 translation.y + "px)";
168 movingPiece.style.transitionDuration = "0.2s";
169 movingPiece.style.zIndex = "3000";
170 setTimeout( () => {
171 for (let i=0; i<squares.length; i++)
172 squares.item(i).style.zIndex = "auto";
173 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
174 this.play(move);
175 }, 250);
176 },
177 play: function(move, programmatic) {
178 let navigate = !move;
179 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
180 // (except if we receive opponent's move, human or computer)
181 if (!navigate && !this.analyze && !programmatic
182 && this.cursor < this.moves.length-1)
183 {
184 return;
185 }
186 if (navigate)
187 {
188 if (this.cursor == this.moves.length-1)
189 return; //no more moves
190 move = this.moves[this.cursor+1];
191 }
192 if (!!programmatic) //computer or (remote) human opponent
193 {
194 if (this.cursor < this.moves.length-1)
195 this.gotoEnd(); //required to play the move
196 return this.animateMove(move);
197 }
198 // Not programmatic, or animation is over
199 if (!move.notation)
200 move.notation = this.vr.getNotation(move);
201 if (!move.color)
202 move.color = this.vr.turn;
203 this.vr.play(move);
204 this.cursor++;
205 this.lastMove = move;
206 if (!move.fen)
207 move.fen = this.vr.getFen();
208 if (this.st.settings.sound == 2)
209 new Audio("/sounds/move.mp3").play().catch(err => {});
a6088c90
BA
210 if (!navigate && (this.score == "*" || this.analyze))
211 {
212 // Stack move on movesList at current cursor
213 if (this.cursor == this.moves.length)
214 this.moves.push(move);
215 else
216 this.moves = this.moves.slice(0,this.cursor).concat([move]);
217 }
218 // Is opponent in check?
219 this.incheck = this.vr.getCheckSquares(this.vr.turn);
220 const score = this.vr.getCurrentScore();
221 if (score != "*")
222 {
223 if (!this.analyze)
224 this.endGame(score);
225 else //just show score on screen (allow undo)
226 this.showScoreMsg(score);
227 }
4494c17c
BA
228 if (!this.analyze)
229 this.$emit("newmove", move); //post-processing (e.g. computer play)
a6088c90
BA
230 },
231 undo: function(move) {
232 let navigate = !move;
233 if (navigate)
234 {
235 if (this.cursor < 0)
236 return; //no more moves
237 move = this.moves[this.cursor];
238 }
239 this.vr.undo(move);
240 this.cursor--;
241 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
242 if (this.st.settings.sound == 2)
243 new Audio("/sounds/undo.mp3").play().catch(err => {});
244 this.incheck = this.vr.getCheckSquares(this.vr.turn);
4494c17c 245 if (!navigate)
a6088c90
BA
246 this.moves.pop();
247 },
248 gotoMove: function(index) {
37cdcbf3 249 this.vr.re_init(this.moves[index].fen);
a6088c90
BA
250 this.cursor = index;
251 this.lastMove = this.moves[index];
252 },
253 gotoBegin: function() {
37cdcbf3 254 this.vr.re_init(this.fenStart);
a6088c90
BA
255 this.cursor = -1;
256 this.lastMove = null;
257 },
258 gotoEnd: function() {
259 this.gotoMove(this.moves.length-1);
260 },
261 flip: function() {
262 this.orientation = V.GetNextCol(this.orientation);
263 },
264 },
265};
266</script>