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