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