Draft moveList component
[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
BA
3
4// Game logic on a variant page: 3 modes, analyze, computer or human
1d184b4c 5Vue.component('my-game', {
fd373b27 6 // gameId: to find the game in storage (assumption: it exists)
81bc1102 7 // fen: to start from a FEN without identifiers (analyze mode)
d44df0b0 8 props: ["conn","gameId","fen","mode","allowChat","allowMovelist"],
1d184b4c
BA
9 data: function() {
10 return {
81da2786 11 // if oppid == "computer" then mode = "computer" (otherwise human)
3a609580 12 myid: "", //our ID, always set
fd373b27 13 //this.myid = localStorage.getItem("myid")
1d184b4c 14 oppid: "", //opponent ID in case of HH game
81da2786
BA
15 score: "*", //'*' means 'unfinished'
16 mycolor: "w",
fd373b27 17 oppConnected: false, //TODO?
3840e240 18 pgnTxt: "",
a897b421 19 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
e6dcb115 20 sound: parseInt(localStorage["sound"] || "2"),
643479f8
BA
21 // Web worker to play computer moves without freezing interface:
22 compWorker: new Worker('/javascripts/playCompMove.js'),
23 timeStart: undefined, //time when computer starts thinking
fd373b27 24 vr: null, //VariantRules object, describing the game state + rules
d44df0b0
BA
25 endgameMessage: "",
26 orientation: "w",
27
28 moves: [], //TODO: initialize if gameId is defined...
81bc1102
BA
29 // orientation :: button flip
30 // userColor: given by gameId, or fen (if no game Id)
31 // gameOver: known if gameId; otherwise assue false
32 // lastMove: update after every play, initialize with last move from list (if continuation)
33 //orientation ? userColor ? gameOver ? lastMove ?
34
1d184b4c
BA
35 };
36 },
fd08ab2c
BA
37 watch: {
38 fen: function(newFen) {
39 this.vr = new VariantRules(newFen);
40 },
d44df0b0
BA
41 gameId: function() {
42 this.loadGame();
43 },
fd08ab2c 44 },
81da2786 45 computed: {
81da2786 46 showChat: function() {
fd373b27 47 return this.allowChat && this.mode=='human' && this.score != '*';
81da2786
BA
48 },
49 showMoves: function() {
fd373b27
BA
50 return this.allowMovelist && window.innerWidth >= 768;
51 },
52 showFen: function() {
53 return variant.name != "Dark" || this.score != "*";
c794dbb8
BA
54 },
55 },
81da2786 56 // Modal end of game, and then sub-components
fd373b27 57 // TODO: provide chat parameters (connection, players ID...)
4608eed9 58 // and also moveList parameters (just moves ?)
fd373b27
BA
59 // TODO: connection + turn indicators en haut à droite (superposé au menu)
60 // TODO: controls: abort, clear, resign, draw (avec confirm box)
61 // et si partie terminée : (mode analyse) just clear, back / play
62 // + flip button toujours disponible
63 // gotoMove : vr = new VariantRules(fen stocké dans le coup [TODO])
4608eed9
BA
64
65 // NOTE: move.color must be fulfilled after each move played, because of Marseille (or Avalanche) chess
66 // --> useful in moveList component (universal comma separator ?)
67
81da2786
BA
68 template: `
69 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
70 <input id="modal-eog" type="checkbox" class="modal"/>
71 <div role="dialog" aria-labelledby="eogMessage">
72 <div class="card smallpad small-modal text-center">
fd373b27
BA
73 <label for="modal-eog" class="modal-close">
74 </label>
75 <h3 id="eogMessage" class="section">
76 {{ endgameMessage }}
77 </h3>
936dc463
BA
78 </div>
79 </div>
fd373b27
BA
80 <my-chat v-if="showChat">
81 </my-chat>
d44df0b0 82 <my-board v-bind:vr="vr" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play">
fd373b27 83 </my-board>
d44df0b0 84 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
fd373b27
BA
85 <p id="fen-string" class="text-center">
86 {{ vr.getFen() }}
87 </p>
88 </div>
81da2786 89 <div id="pgn-div" class="section-content">
4608eed9 90 <a id="download" href="#">
fd373b27 91 </a>
81da2786 92 <button id="downloadBtn" @click="download">
d44df0b0 93 {{ translate("Download PGN") }}
81da2786 94 </button>
fd373b27 95 </div>
7ee085c2 96 <my-move-list v-if="showMoves" :moves="moves">
fd373b27 97 </my-move-list>
81da2786
BA
98 </div>
99 `,
1d184b4c 100 created: function() {
81bc1102 101
d44df0b0
BA
102// console.log(this.fen);
103// console.log(this.gameId);
104 if (!!this.gameId)
105 this.loadGame();
106 else if (!!this.fen)
107 this.vr = new VariantRules(this.fen);
fd373b27 108 // TODO: after game, archive in indexedDB
067c675b 109 // TODO: this events listener is central. Refactor ? How ?
d35f20e4 110 const socketMessageListener = msg => {
1d184b4c 111 const data = JSON.parse(msg.data);
edcd679a 112 let L = undefined;
1d184b4c
BA
113 switch (data.code)
114 {
1d184b4c 115 case "newmove": //..he played!
8d7e2786 116 this.play(data.move, (variant.name!="Dark" ? "animate" : null));
1d184b4c 117 break;
f3802fcd 118 case "pong": //received if we sent a ping (game still alive on our side)
56a683cd
BA
119 if (this.gameId != data.gameId)
120 break; //games IDs don't match: definitely over...
1d184b4c 121 this.oppConnected = true;
f3802fcd 122 // Send our "last state" informations to opponent
edcd679a 123 L = this.vr.moves.length;
a29d9d6b 124 this.conn.send(JSON.stringify({
56a683cd
BA
125 code: "lastate",
126 oppid: this.oppid,
127 gameId: this.gameId,
128 lastMove: (L>0?this.vr.moves[L-1]:undefined),
129 movesCount: L,
a29d9d6b 130 }));
1d184b4c 131 break;
56a683cd 132 case "lastate": //got opponent infos about last move
edcd679a 133 L = this.vr.moves.length;
56a683cd
BA
134 if (this.gameId != data.gameId)
135 break; //games IDs don't match: nothing we can do...
136 // OK, opponent still in game (which might be over)
edcd679a 137 if (this.score != "*")
a29d9d6b 138 {
56a683cd 139 // We finished the game (any result possible)
a29d9d6b 140 this.conn.send(JSON.stringify({
56a683cd
BA
141 code: "lastate",
142 oppid: data.oppid,
143 gameId: this.gameId,
144 score: this.score,
a29d9d6b
BA
145 }));
146 }
56a683cd
BA
147 else if (!!data.score) //opponent finished the game
148 this.endGame(data.score);
149 else if (data.movesCount < L)
a29d9d6b
BA
150 {
151 // We must tell last move to opponent
a29d9d6b 152 this.conn.send(JSON.stringify({
56a683cd
BA
153 code: "lastate",
154 oppid: this.oppid,
edcd679a 155 gameId: this.gameId,
56a683cd
BA
156 lastMove: this.vr.moves[L-1],
157 movesCount: L,
a29d9d6b
BA
158 }));
159 }
56a683cd 160 else if (data.movesCount > L) //just got last move from him
a29d9d6b 161 this.play(data.lastMove, "animate");
ecf44502 162 break;
1d184b4c 163 case "resign": //..you won!
dfb4afc1 164 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 165 break;
f3802fcd 166 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
167 case "connect":
168 case "disconnect":
4f7723a1 169 if (this.mode=="human" && this.oppid == data.id)
1d184b4c 170 this.oppConnected = (data.code == "connect");
4f7723a1 171 if (this.oppConnected && this.score != "*")
3a609580
BA
172 {
173 // Send our name to the opponent, in case of he hasn't it
174 this.conn.send(JSON.stringify({
175 code:"myname", name:this.myname, oppid: this.oppid}));
176 }
1d184b4c
BA
177 break;
178 }
179 };
067c675b 180
d35f20e4 181 const socketCloseListener = () => {
d35f20e4
BA
182 this.conn.addEventListener('message', socketMessageListener);
183 this.conn.addEventListener('close', socketCloseListener);
184 };
d35f20e4
BA
185 this.conn.onmessage = socketMessageListener;
186 this.conn.onclose = socketCloseListener;
81da2786 187
067c675b 188 // Computer moves web worker logic: (TODO: also for observers in HH games)
8d7e2786 189 this.compWorker.postMessage(["scripts",variant.name]);
643479f8
BA
190 const self = this;
191 this.compWorker.onmessage = function(e) {
aa78cc74 192 let compMove = e.data;
78bab51e
BA
193 if (!compMove)
194 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
6e62b1c7
BA
195 if (!Array.isArray(compMove))
196 compMove = [compMove]; //to deal with MarseilleRules
197 // TODO: imperfect attempt to avoid ghost move:
198 compMove.forEach(m => { m.computer = true; });
643479f8
BA
199 // (first move) HACK: small delay to avoid selecting elements
200 // before they appear on page:
201 const delay = Math.max(500-(Date.now()-self.timeStart), 0);
202 setTimeout(() => {
8d7e2786 203 const animate = (variant.name!="Dark" ? "animate" : null);
aa78cc74 204 if (self.mode == "computer") //warning: mode could have changed!
5915f720 205 self.play(compMove[0], animate);
6e62b1c7
BA
206 if (compMove.length == 2)
207 setTimeout( () => {
208 if (self.mode == "computer")
5915f720 209 self.play(compMove[1], animate);
78bab51e 210 }, 750);
643479f8
BA
211 }, delay);
212 }
1d184b4c 213 },
d44df0b0 214 // this.conn est une prop, donnée depuis variant.js
fd373b27
BA
215 //dans variant.js (plutôt room.js) conn gère aussi les challenges
216 // Puis en webRTC, repenser tout ça.
81da2786 217 methods: {
d44df0b0
BA
218 translate: translate,
219 loadGame: function() {
220 // TODO: load this.gameId ...
221 },
fd373b27
BA
222 setEndgameMessage: function(score) {
223 let eogMessage = "Undefined";
224 switch (score)
225 {
226 case "1-0":
227 eogMessage = translations["White win"];
228 break;
229 case "0-1":
230 eogMessage = translations["Black win"];
231 break;
232 case "1/2":
233 eogMessage = translations["Draw"];
234 break;
235 case "?":
236 eogMessage = "Unfinished";
237 break;
238 }
239 this.endgameMessage = eogMessage;
240 },
01ca2adc 241 download: function() {
edcd679a 242 // Variants may have special PGN structure (so next function isn't defined here)
fd373b27
BA
243 // TODO: get fenStart from local game (using gameid)
244 const content = V.GetPGN(this.moves, this.mycolor, this.score, fenStart, this.mode);
01ca2adc
BA
245 // Prepare and trigger download link
246 let downloadAnchor = document.getElementById("download");
247 downloadAnchor.setAttribute("download", "game.pgn");
edcd679a 248 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
01ca2adc
BA
249 downloadAnchor.click();
250 },
fd373b27
BA
251 showScoreMsg: function(score) {
252 this.setEndgameMessage(score);
ecf44502 253 let modalBox = document.getElementById("modal-eog");
186516b8 254 modalBox.checked = true;
1a788978
BA
255 setTimeout(() => { modalBox.checked = false; }, 2000);
256 },
257 endGame: function(score) {
258 this.score = score;
56a683cd
BA
259 if (["human","computer"].includes(this.mode))
260 {
261 const prefix = (this.mode=="computer" ? "comp-" : "");
262 localStorage.setItem(prefix+"score", score);
263 }
fd373b27 264 this.showScoreMsg(score);
3a609580
BA
265 if (this.mode == "human" && this.oppConnected)
266 {
267 // Send our nickname to opponent
268 this.conn.send(JSON.stringify({
269 code:"myname", name:this.myname, oppid:this.oppid}));
270 }
fd373b27
BA
271 // TODO: what about cursor ?
272 //this.cursor = this.vr.moves.length; //to navigate in finished game
1d184b4c 273 },
067c675b
BA
274 resign: function(e) {
275 this.getRidOfTooltip(e.currentTarget);
276 if (this.mode == "human" && this.oppConnected)
277 {
278 try {
279 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
280 } catch (INVALID_STATE_ERR) {
281 return; //socket is not ready (and not yet reconnected)
282 }
283 }
284 this.endGame(this.mycolor=="w"?"0-1":"1-0");
285 },
1d184b4c 286 playComputerMove: function() {
643479f8
BA
287 this.timeStart = Date.now();
288 this.compWorker.postMessage(["askmove"]);
1d184b4c 289 },
fd373b27
BA
290 animateMove: function(move) {
291 let startSquare = document.getElementById(this.getSquareId(move.start));
292 let endSquare = document.getElementById(this.getSquareId(move.end));
293 let rectStart = startSquare.getBoundingClientRect();
294 let rectEnd = endSquare.getBoundingClientRect();
295 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
296 let movingPiece =
297 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
298 // HACK for animation (with positive translate, image slides "under background")
299 // Possible improvement: just alter squares on the piece's way...
300 squares = document.getElementsByClassName("board");
301 for (let i=0; i<squares.length; i++)
302 {
303 let square = squares.item(i);
304 if (square.id != this.getSquareId(move.start))
305 square.style.zIndex = "-1";
306 }
307 movingPiece.style.transform = "translate(" + translation.x + "px," +
308 translation.y + "px)";
309 movingPiece.style.transitionDuration = "0.2s";
310 movingPiece.style.zIndex = "3000";
311 setTimeout( () => {
312 for (let i=0; i<squares.length; i++)
313 squares.item(i).style.zIndex = "auto";
314 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
315 this.play(move); //TODO: plutôt envoyer message "please play"
316 }, 250);
317 },
318 play: function(move, programmatic) {
319 if (!!programmatic) //computer or human opponent
320 return this.animateMove(move);
321 // Not programmatic, or animation is over
322 if (!move.notation)
323 move.notation = this.vr.getNotation(move);
324 this.vr.play(move);
325 if (!move.fen)
326 move.fen = this.vr.getFen();
327 if (this.sound == 2)
328 new Audio("/sounds/move.mp3").play().catch(err => {});
329 if (this.mode == "human")
330 {
331 updateStorage(move); //after our moves and opponent moves
332 if (this.vr.turn == this.userColor)
333 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
334 }
335 else if (this.mode == "computer")
336 {
337 // Send the move to web worker (including his own moves)
338 this.compWorker.postMessage(["newmove",move]);
339 }
340 if (this.score == "*" || this.mode == "analyze")
341 {
342 // Stack move on movesList
343 this.moves.push(move);
344 }
345 // Is opponent in check?
346 this.incheck = this.vr.getCheckSquares(this.vr.turn);
347 const score = this.vr.getCurrentScore();
348 if (score != "*")
349 {
350 if (["human","computer"].includes(this.mode))
351 this.endGame(score);
352 else //just show score on screen (allow undo)
353 this.showScoreMsg(score);
354 // TODO: notify end of game (give score)
355 }
356 else if (this.mode == "computer" && this.vr.turn != this.userColor)
357 this.playComputerMove();
358 },
359 undo: function(move) {
360 this.vr.undo(move);
361 if (this.sound == 2)
362 new Audio("/sounds/undo.mp3").play().catch(err => {});
363 this.incheck = this.vr.getCheckSquares(this.vr.turn);
364 if (this.mode == "analyze")
365 this.moves.pop();
366 },
1d184b4c
BA
367 },
368})
fd373b27 369// cursor + ........
067c675b
BA
370//TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
371//+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
372//comme sur lichess
fd373b27
BA
373//
374//TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB