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