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