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