4048a3d404190ecdf93d6b9743dba9d8cac243b6
[vchess.git] / public / javascripts / components / game.js
1 // TODO: envoyer juste "light move", sans FEN ni notation ...etc
2 // TODO: also "observers" prop, we should send moves to them too (in a web worker ? webRTC ?)
3
4 // Game logic on a variant page: 3 modes, analyze, computer or human
5 Vue.component('my-game', {
6 // gameId: to find the game in storage (assumption: it exists)
7 // fen: to start from a FEN without identifiers (analyze mode)
8 props: ["conn","gameId","fen","mode","allowChat","allowMovelist"],
9 data: function() {
10 return {
11 // if oppid == "computer" then mode = "computer" (otherwise human)
12 myid: "", //our ID, always set
13 //this.myid = localStorage.getItem("myid")
14 oppid: "", //opponent ID in case of HH game
15 score: "*", //'*' means 'unfinished'
16 mycolor: "w",
17 oppConnected: false, //TODO?
18 pgnTxt: "",
19 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
20 sound: parseInt(localStorage["sound"] || "2"),
21 // Web worker to play computer moves without freezing interface:
22 compWorker: new Worker('/javascripts/playCompMove.js'),
23 timeStart: undefined, //time when computer starts thinking
24 vr: null, //VariantRules object, describing the game state + rules
25 endgameMessage: "",
26 orientation: "w",
27 fenStart: "",
28
29 moves: [], //TODO: initialize if gameId is defined...
30 cursor: 0,
31 // orientation :: button flip
32 // userColor: given by gameId, or fen (if no game Id)
33 // gameOver: known if gameId; otherwise assue false
34 // lastMove: update after every play, initialize with last move from list (if continuation)
35 //orientation ? userColor ? gameOver ? lastMove ?
36
37 };
38 },
39 watch: {
40 fen: function(newFen) {
41 this.vr = new VariantRules(newFen);
42 },
43 gameId: function() {
44 this.loadGame();
45 },
46 },
47 computed: {
48 showChat: function() {
49 return this.allowChat && this.mode=='human' && this.score != '*';
50 },
51 showMoves: function() {
52 return true;
53 return this.allowMovelist && window.innerWidth >= 768;
54 },
55 showFen: function() {
56 return variant.name != "Dark" || this.score != "*";
57 },
58 },
59 // Modal end of game, and then sub-components
60 // TODO: provide chat parameters (connection, players ID...)
61 // and also moveList parameters (just moves ?)
62 // TODO: connection + turn indicators en haut à droite (superposé au menu)
63 // TODO: controls: abort, clear, resign, draw (avec confirm box)
64 // et si partie terminée : (mode analyse) just clear, back / play
65 // + flip button toujours disponible
66 // gotoMove : vr = new VariantRules(fen stocké dans le coup [TODO])
67
68 // NOTE: move.color must be fulfilled after each move played, because of Marseille (or Avalanche) chess
69 // --> useful in moveList component (universal comma separator ?)
70
71 template: `
72 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
73 <input id="modal-eog" type="checkbox" class="modal"/>
74 <div role="dialog" aria-labelledby="eogMessage">
75 <div class="card smallpad small-modal text-center">
76 <label for="modal-eog" class="modal-close">
77 </label>
78 <h3 id="eogMessage" class="section">
79 {{ endgameMessage }}
80 </h3>
81 </div>
82 </div>
83 <my-chat v-if="showChat">
84 </my-chat>
85 <my-board v-bind:vr="vr" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play">
86 </my-board>
87 <div class="button-group">
88 <button @click="() => play()">Play</button>
89 <button @click="() => undo()">Undo</button>
90 <button @click="flip">Flip</button>
91 <button @click="gotoBegin">GotoBegin</button>
92 <button @click="gotoEnd">GotoEnd</button>
93 </div>
94 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
95 <p id="fen-string" class="text-center">
96 {{ vr.getFen() }}
97 </p>
98 </div>
99 <div id="pgn-div" class="section-content">
100 <a id="download" href="#">
101 </a>
102 <button id="downloadBtn" @click="download">
103 {{ translate("Download PGN") }}
104 </button>
105 </div>
106 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
107 </my-move-list>
108 </div>
109 `,
110 created: function() {
111 if (!!this.gameId)
112 this.loadGame();
113 else if (!!this.fen)
114 {
115 this.vr = new VariantRules(this.fen);
116 this.fenStart = this.fen;
117 }
118 // TODO: after game, archive in indexedDB
119 // TODO: this events listener is central. Refactor ? How ?
120 const socketMessageListener = msg => {
121 const data = JSON.parse(msg.data);
122 let L = undefined;
123 switch (data.code)
124 {
125 case "newmove": //..he played!
126 this.play(data.move, (variant.name!="Dark" ? "animate" : null));
127 break;
128 case "pong": //received if we sent a ping (game still alive on our side)
129 if (this.gameId != data.gameId)
130 break; //games IDs don't match: definitely over...
131 this.oppConnected = true;
132 // Send our "last state" informations to opponent
133 L = this.vr.moves.length;
134 this.conn.send(JSON.stringify({
135 code: "lastate",
136 oppid: this.oppid,
137 gameId: this.gameId,
138 lastMove: (L>0?this.vr.moves[L-1]:undefined),
139 movesCount: L,
140 }));
141 break;
142 case "lastate": //got opponent infos about last move
143 L = this.vr.moves.length;
144 if (this.gameId != data.gameId)
145 break; //games IDs don't match: nothing we can do...
146 // OK, opponent still in game (which might be over)
147 if (this.score != "*")
148 {
149 // We finished the game (any result possible)
150 this.conn.send(JSON.stringify({
151 code: "lastate",
152 oppid: data.oppid,
153 gameId: this.gameId,
154 score: this.score,
155 }));
156 }
157 else if (!!data.score) //opponent finished the game
158 this.endGame(data.score);
159 else if (data.movesCount < L)
160 {
161 // We must tell last move to opponent
162 this.conn.send(JSON.stringify({
163 code: "lastate",
164 oppid: this.oppid,
165 gameId: this.gameId,
166 lastMove: this.vr.moves[L-1],
167 movesCount: L,
168 }));
169 }
170 else if (data.movesCount > L) //just got last move from him
171 this.play(data.lastMove, "animate");
172 break;
173 case "resign": //..you won!
174 this.endGame(this.mycolor=="w"?"1-0":"0-1");
175 break;
176 // TODO: also use (dis)connect info to count online players?
177 case "connect":
178 case "disconnect":
179 if (this.mode=="human" && this.oppid == data.id)
180 this.oppConnected = (data.code == "connect");
181 if (this.oppConnected && this.score != "*")
182 {
183 // Send our name to the opponent, in case of he hasn't it
184 this.conn.send(JSON.stringify({
185 code:"myname", name:this.myname, oppid: this.oppid}));
186 }
187 break;
188 }
189 };
190
191 const socketCloseListener = () => {
192 this.conn.addEventListener('message', socketMessageListener);
193 this.conn.addEventListener('close', socketCloseListener);
194 };
195 this.conn.onmessage = socketMessageListener;
196 this.conn.onclose = socketCloseListener;
197
198 // Computer moves web worker logic: (TODO: also for observers in HH games)
199 this.compWorker.postMessage(["scripts",variant.name]);
200 const self = this;
201 this.compWorker.onmessage = function(e) {
202 let compMove = e.data;
203 if (!compMove)
204 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
205 if (!Array.isArray(compMove))
206 compMove = [compMove]; //to deal with MarseilleRules
207 // TODO: imperfect attempt to avoid ghost move:
208 compMove.forEach(m => { m.computer = true; });
209 // (first move) HACK: small delay to avoid selecting elements
210 // before they appear on page:
211 const delay = Math.max(500-(Date.now()-self.timeStart), 0);
212 setTimeout(() => {
213 const animate = (variant.name!="Dark" ? "animate" : null);
214 if (self.mode == "computer") //warning: mode could have changed!
215 self.play(compMove[0], animate);
216 if (compMove.length == 2)
217 setTimeout( () => {
218 if (self.mode == "computer")
219 self.play(compMove[1], animate);
220 }, 750);
221 }, delay);
222 }
223 },
224 // this.conn est une prop, donnée depuis variant.js
225 //dans variant.js (plutôt room.js) conn gère aussi les challenges
226 // Puis en webRTC, repenser tout ça.
227 methods: {
228 translate: translate,
229 loadGame: function() {
230 // TODO: load this.gameId ...
231 },
232 setEndgameMessage: function(score) {
233 let eogMessage = "Undefined";
234 switch (score)
235 {
236 case "1-0":
237 eogMessage = translations["White win"];
238 break;
239 case "0-1":
240 eogMessage = translations["Black win"];
241 break;
242 case "1/2":
243 eogMessage = translations["Draw"];
244 break;
245 case "?":
246 eogMessage = "Unfinished";
247 break;
248 }
249 this.endgameMessage = eogMessage;
250 },
251 download: function() {
252 // Variants may have special PGN structure (so next function isn't defined here)
253 // TODO: get fenStart from local game (using gameid)
254 const content = V.GetPGN(this.moves, this.mycolor, this.score, fenStart, this.mode);
255 // Prepare and trigger download link
256 let downloadAnchor = document.getElementById("download");
257 downloadAnchor.setAttribute("download", "game.pgn");
258 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
259 downloadAnchor.click();
260 },
261 showScoreMsg: function(score) {
262 this.setEndgameMessage(score);
263 let modalBox = document.getElementById("modal-eog");
264 modalBox.checked = true;
265 setTimeout(() => { modalBox.checked = false; }, 2000);
266 },
267 endGame: function(score) {
268 this.score = score;
269 if (["human","computer"].includes(this.mode))
270 {
271 const prefix = (this.mode=="computer" ? "comp-" : "");
272 localStorage.setItem(prefix+"score", score);
273 }
274 this.showScoreMsg(score);
275 if (this.mode == "human" && this.oppConnected)
276 {
277 // Send our nickname to opponent
278 this.conn.send(JSON.stringify({
279 code:"myname", name:this.myname, oppid:this.oppid}));
280 }
281 // TODO: what about cursor ?
282 //this.cursor = this.vr.moves.length; //to navigate in finished game
283 },
284 resign: function(e) {
285 this.getRidOfTooltip(e.currentTarget);
286 if (this.mode == "human" && this.oppConnected)
287 {
288 try {
289 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
290 } catch (INVALID_STATE_ERR) {
291 return; //socket is not ready (and not yet reconnected)
292 }
293 }
294 this.endGame(this.mycolor=="w"?"0-1":"1-0");
295 },
296 playComputerMove: function() {
297 this.timeStart = Date.now();
298 this.compWorker.postMessage(["askmove"]);
299 },
300 animateMove: function(move) {
301 let startSquare = document.getElementById(this.getSquareId(move.start));
302 let endSquare = document.getElementById(this.getSquareId(move.end));
303 let rectStart = startSquare.getBoundingClientRect();
304 let rectEnd = endSquare.getBoundingClientRect();
305 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
306 let movingPiece =
307 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
308 // HACK for animation (with positive translate, image slides "under background")
309 // Possible improvement: just alter squares on the piece's way...
310 squares = document.getElementsByClassName("board");
311 for (let i=0; i<squares.length; i++)
312 {
313 let square = squares.item(i);
314 if (square.id != this.getSquareId(move.start))
315 square.style.zIndex = "-1";
316 }
317 movingPiece.style.transform = "translate(" + translation.x + "px," +
318 translation.y + "px)";
319 movingPiece.style.transitionDuration = "0.2s";
320 movingPiece.style.zIndex = "3000";
321 setTimeout( () => {
322 for (let i=0; i<squares.length; i++)
323 squares.item(i).style.zIndex = "auto";
324 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
325 this.play(move); //TODO: plutôt envoyer message "please play"
326 }, 250);
327 },
328 play: function(move, programmatic) {
329 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
330 if (this.mode != "analyze" && this.cursor < this.moves.length-1)
331 return;
332 let navigate = !move;
333 if (navigate)
334 {
335 if (this.cursor == this.moves.length)
336 return; //no more moves
337 move = this.moves[this.cursor];
338 }
339 if (!!programmatic) //computer or human opponent
340 return this.animateMove(move);
341 // Not programmatic, or animation is over
342 if (!move.notation)
343 move.notation = this.vr.getNotation(move);
344 if (!move.color)
345 move.color = this.vr.turn;
346 this.vr.play(move);
347 this.cursor++;
348 if (!move.fen)
349 move.fen = this.vr.getFen();
350 if (this.sound == 2)
351 new Audio("/sounds/move.mp3").play().catch(err => {});
352 if (this.mode == "human")
353 {
354 updateStorage(move); //after our moves and opponent moves
355 if (this.vr.turn == this.userColor)
356 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
357 }
358 else if (this.mode == "computer")
359 {
360 // Send the move to web worker (including his own moves)
361 this.compWorker.postMessage(["newmove",move]);
362 }
363 if (!navigate && (this.score == "*" || this.mode == "analyze"))
364 {
365 // Stack move on movesList at current cursor
366 if (this.cursor == this.moves.length)
367 this.moves.push(move);
368 else
369 this.moves = this.moves.slice(0,this.cursor-1).concat([move]);
370 }
371 // Is opponent in check?
372 this.incheck = this.vr.getCheckSquares(this.vr.turn);
373 const score = this.vr.getCurrentScore();
374 if (score != "*")
375 {
376 if (["human","computer"].includes(this.mode))
377 this.endGame(score);
378 else //just show score on screen (allow undo)
379 this.showScoreMsg(score);
380 // TODO: notify end of game (give score)
381 }
382 else if (this.mode == "computer" && this.vr.turn != this.userColor)
383 this.playComputerMove();
384 if (navigate)
385 this.$children[0].$forceUpdate(); //TODO!?
386 },
387 undo: function(move) {
388 let navigate = !move;
389 if (navigate)
390 {
391 if (this.cursor == 0)
392 return; //no more moves
393 move = this.moves[this.cursor-1];
394 }
395 this.vr.undo(move);
396 this.cursor--;
397 if (navigate)
398 this.$children[0].$forceUpdate(); //TODO!?
399 if (this.sound == 2)
400 new Audio("/sounds/undo.mp3").play().catch(err => {});
401 this.incheck = this.vr.getCheckSquares(this.vr.turn);
402 if (!navigate && this.mode == "analyze")
403 this.moves.pop();
404 if (navigate)
405 this.$forceUpdate(); //TODO!?
406 },
407 gotoMove: function(index) {
408 this.vr = new VariantRules(this.moves[index].fen);
409 this.cursor = index+1;
410 },
411 gotoBegin: function() {
412 this.vr = new VariantRules(this.fenStart);
413 this.cursor = 0;
414 },
415 gotoEnd: function() {
416 this.gotoMove(this.moves.length-1);
417 },
418 flip: function() {
419 this.orientation = V.GetNextCol(this.orientation);
420 },
421 },
422 })
423 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
424 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
425 //comme sur lichess
426 //
427 //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB