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