Fix play comp move in ComputerGame component
[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 }}
9 Board(:vr="vr" :last-move="lastMove" :analyze="analyze" :user-color="mycolor"
b7c32f1a 10 :orientation="orientation" :vname="vname" @play-move="play")
a6088c90
BA
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>
29import Board from "@/components/Board.vue";
30//import MoveList from "@/components/MoveList.vue";
31import { store } from "@/store";
32import { getSquareId } from "@/utils/squareId";
33
34export default {
35 name: 'my-base-game',
36 components: {
37 Board,
38 //MoveList,
39 },
bc8734ba 40 // "vr": VariantRules object, describing the game state + rules
b7c32f1a 41 props: ["vname","analyze","vr","fenStart","players","mycolor"],
a6088c90
BA
42 data: function() {
43 return {
44 st: store.state,
b7c32f1a 45 // NOTE: all following variables must be reset at the beginning of a game
a6088c90
BA
46 endgameMessage: "",
47 orientation: "w",
48 score: "*", //'*' means 'unfinished'
b7c32f1a 49 moves: [],
a6088c90
BA
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() {
b7c32f1a 60 return this.vname != "Dark" || this.score != "*";
a6088c90
BA
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';
b7c32f1a 94 pgn += '[Variant "' + this.vname + '"]\n';
a6088c90
BA
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 => {});
a6088c90
BA
188 if (!navigate && (this.score == "*" || this.analyze))
189 {
190 // Stack move on movesList at current cursor
191 if (this.cursor == this.moves.length)
192 this.moves.push(move);
193 else
194 this.moves = this.moves.slice(0,this.cursor).concat([move]);
195 }
196 // Is opponent in check?
197 this.incheck = this.vr.getCheckSquares(this.vr.turn);
198 const score = this.vr.getCurrentScore();
199 if (score != "*")
200 {
201 if (!this.analyze)
202 this.endGame(score);
203 else //just show score on screen (allow undo)
204 this.showScoreMsg(score);
205 }
1acda11c 206 this.$emit("newmove", move); //post-processing (e.g. computer play)
a6088c90
BA
207 },
208 undo: function(move) {
209 let navigate = !move;
210 if (navigate)
211 {
212 if (this.cursor < 0)
213 return; //no more moves
214 move = this.moves[this.cursor];
215 }
216 this.vr.undo(move);
217 this.cursor--;
218 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
219 if (this.st.settings.sound == 2)
220 new Audio("/sounds/undo.mp3").play().catch(err => {});
221 this.incheck = this.vr.getCheckSquares(this.vr.turn);
1acda11c 222 if (this.analyze) //TODO: can this happen?
a6088c90
BA
223 this.moves.pop();
224 },
225 gotoMove: function(index) {
226 this.vr = new V(this.moves[index].fen);
227 this.cursor = index;
228 this.lastMove = this.moves[index];
229 },
230 gotoBegin: function() {
231 this.vr = new V(this.fenStart);
232 this.cursor = -1;
233 this.lastMove = null;
234 },
235 gotoEnd: function() {
236 this.gotoMove(this.moves.length-1);
237 },
238 flip: function() {
239 this.orientation = V.GetNextCol(this.orientation);
240 },
241 },
242};
243</script>