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