Finished problems page (untested)
[vchess.git] / public / javascripts / components / game.js
1 // Game logic on a variant page
2 Vue.component('my-game', {
3 props: ["gameId"], //to find the game in storage (assumption: it exists)
4 data: function() {
5 return {
6
7 // TODO: merge next variables into "game"
8 // if oppid == "computer" then mode = "computer" (otherwise human)
9 myid: "", //our ID, always set
10 //this.myid = localStorage.getItem("myid")
11 oppid: "", //opponent ID in case of HH game
12 score: "*", //'*' means 'unfinished'
13 mycolor: "w",
14 fromChallenge: false, //if true, show chat during game
15
16 conn: null, //socket connection
17 oppConnected: false,
18 seek: false,
19 fenStart: "",
20 pgnTxt: "",
21 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
22 sound: parseInt(localStorage["sound"] || "2"),
23 // Web worker to play computer moves without freezing interface:
24 compWorker: new Worker('/javascripts/playCompMove.js'),
25 timeStart: undefined, //time when computer starts thinking
26 };
27 },
28 computed: {
29 mode: function() {
30 return (this.game.oppid == "computer" ? "computer" ? "human");
31 },
32 showChat: function() {
33 return this.mode=='human' &&
34 (this.game.score != '*' || this.game.fromChallenge);
35 },
36 showMoves: function() {
37 return window.innerWidth >= 768;
38 },
39 },
40 // Modal end of game, and then sub-components
41 template: `
42 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
43 <input id="modal-eog" type="checkbox" class="modal"/>
44 <div role="dialog" aria-labelledby="eogMessage">
45 <div class="card smallpad small-modal text-center">
46 <label for="modal-eog" class="modal-close"></label>
47 <h3 id="eogMessage" class="section">{{ endgameMessage }}</h3>
48 </div>
49 </div>
50
51 <my-chat v-if="showChat"></my-chat>
52 //TODO: connection + turn indicators en haut à droite (superposé au menu)
53 <my-board></my-board>
54 // TODO: controls: abort, clear, resign, draw (avec confirm box)
55 // et si partie terminée : (mode analyse) just clear, back / play
56 // + flip button toujours disponible
57
58 <div id="pgn-div" class="section-content">
59 <a id="download" href: "#"></a>
60 <button id="downloadBtn" @click="download">
61 {{ translations["Download PGN"] }}
62 </button>
63
64 <my-move-list v-if="showMoves"></my-move-list>
65 </div>
66 `,
67 computed: {
68 endgameMessage: function() {
69 let eogMessage = "Unfinished";
70 switch (this.game.score)
71 {
72 case "1-0":
73 eogMessage = translations["White win"];
74 break;
75 case "0-1":
76 eogMessage = translations["Black win"];
77 break;
78 case "1/2":
79 eogMessage = translations["Draw"];
80 break;
81 }
82 return eogMessage;
83 },
84 },
85 created: function() {
86 const url = socketUrl;
87 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant._id);
88 // const socketOpenListener = () => {
89 // };
90
91 // TODO: after game, archive in indexedDB
92
93 // TODO: this events listener is central. Refactor ? How ?
94 const socketMessageListener = msg => {
95 const data = JSON.parse(msg.data);
96 let L = undefined;
97 switch (data.code)
98 {
99 case "newmove": //..he played!
100 this.play(data.move, (variant.name!="Dark" ? "animate" : null));
101 break;
102 case "pong": //received if we sent a ping (game still alive on our side)
103 if (this.gameId != data.gameId)
104 break; //games IDs don't match: definitely over...
105 this.oppConnected = true;
106 // Send our "last state" informations to opponent
107 L = this.vr.moves.length;
108 this.conn.send(JSON.stringify({
109 code: "lastate",
110 oppid: this.oppid,
111 gameId: this.gameId,
112 lastMove: (L>0?this.vr.moves[L-1]:undefined),
113 movesCount: L,
114 }));
115 break;
116 case "lastate": //got opponent infos about last move
117 L = this.vr.moves.length;
118 if (this.gameId != data.gameId)
119 break; //games IDs don't match: nothing we can do...
120 // OK, opponent still in game (which might be over)
121 if (this.score != "*")
122 {
123 // We finished the game (any result possible)
124 this.conn.send(JSON.stringify({
125 code: "lastate",
126 oppid: data.oppid,
127 gameId: this.gameId,
128 score: this.score,
129 }));
130 }
131 else if (!!data.score) //opponent finished the game
132 this.endGame(data.score);
133 else if (data.movesCount < L)
134 {
135 // We must tell last move to opponent
136 this.conn.send(JSON.stringify({
137 code: "lastate",
138 oppid: this.oppid,
139 gameId: this.gameId,
140 lastMove: this.vr.moves[L-1],
141 movesCount: L,
142 }));
143 }
144 else if (data.movesCount > L) //just got last move from him
145 this.play(data.lastMove, "animate");
146 break;
147 case "resign": //..you won!
148 this.endGame(this.mycolor=="w"?"1-0":"0-1");
149 break;
150 // TODO: also use (dis)connect info to count online players?
151 case "connect":
152 case "disconnect":
153 if (this.mode=="human" && this.oppid == data.id)
154 this.oppConnected = (data.code == "connect");
155 if (this.oppConnected && this.score != "*")
156 {
157 // Send our name to the opponent, in case of he hasn't it
158 this.conn.send(JSON.stringify({
159 code:"myname", name:this.myname, oppid: this.oppid}));
160 }
161 break;
162 }
163 };
164
165 const socketCloseListener = () => {
166 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant._id);
167 //this.conn.addEventListener('open', socketOpenListener);
168 this.conn.addEventListener('message', socketMessageListener);
169 this.conn.addEventListener('close', socketCloseListener);
170 };
171 //this.conn.onopen = socketOpenListener;
172 this.conn.onmessage = socketMessageListener;
173 this.conn.onclose = socketCloseListener;
174
175
176 // Listen to keyboard left/right to navigate in game
177 // TODO: also mouse wheel !
178 document.onkeydown = event => {
179 if (["human","computer"].includes(this.mode) &&
180 !!this.vr && this.vr.moves.length > 0 && [37,39].includes(event.keyCode))
181 {
182 event.preventDefault();
183 if (event.keyCode == 37) //Back
184 this.undo();
185 else //Forward (39)
186 this.play();
187 }
188 };
189
190
191 // Computer moves web worker logic: (TODO: also for observers in HH games)
192 this.compWorker.postMessage(["scripts",variant.name]);
193 const self = this;
194 this.compWorker.onmessage = function(e) {
195 let compMove = e.data;
196 if (!compMove)
197 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
198 if (!Array.isArray(compMove))
199 compMove = [compMove]; //to deal with MarseilleRules
200 // TODO: imperfect attempt to avoid ghost move:
201 compMove.forEach(m => { m.computer = true; });
202 // (first move) HACK: small delay to avoid selecting elements
203 // before they appear on page:
204 const delay = Math.max(500-(Date.now()-self.timeStart), 0);
205 setTimeout(() => {
206 const animate = (variant.name!="Dark" ? "animate" : null);
207 if (self.mode == "computer") //warning: mode could have changed!
208 self.play(compMove[0], animate);
209 if (compMove.length == 2)
210 setTimeout( () => {
211 if (self.mode == "computer")
212 self.play(compMove[1], animate);
213 }, 750);
214 }, delay);
215 }
216 },
217
218
219 methods: {
220 download: function() {
221 // Variants may have special PGN structure (so next function isn't defined here)
222 const content = V.GetPGN(this.moves, this.mycolor, this.score, this.fenStart, this.mode);
223 // Prepare and trigger download link
224 let downloadAnchor = document.getElementById("download");
225 downloadAnchor.setAttribute("download", "game.pgn");
226 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
227 downloadAnchor.click();
228 },
229 showScoreMsg: function() {
230 let modalBox = document.getElementById("modal-eog");
231 modalBox.checked = true;
232 setTimeout(() => { modalBox.checked = false; }, 2000);
233 },
234 endGame: function(score) {
235 this.score = score;
236 if (["human","computer"].includes(this.mode))
237 {
238 const prefix = (this.mode=="computer" ? "comp-" : "");
239 localStorage.setItem(prefix+"score", score);
240 }
241 this.showScoreMsg();
242 if (this.mode == "human" && this.oppConnected)
243 {
244 // Send our nickname to opponent
245 this.conn.send(JSON.stringify({
246 code:"myname", name:this.myname, oppid:this.oppid}));
247 }
248 this.cursor = this.vr.moves.length; //to navigate in finished game
249 },
250 resign: function(e) {
251 this.getRidOfTooltip(e.currentTarget);
252 if (this.mode == "human" && this.oppConnected)
253 {
254 try {
255 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
256 } catch (INVALID_STATE_ERR) {
257 return; //socket is not ready (and not yet reconnected)
258 }
259 }
260 this.endGame(this.mycolor=="w"?"0-1":"1-0");
261 },
262 playComputerMove: function() {
263 this.timeStart = Date.now();
264 this.compWorker.postMessage(["askmove"]);
265 },
266 // OK, these last functions can stay here (?!)
267 play: function(move, programmatic) {
268 if (!move)
269 {
270 // Navigate after game is over
271 if (this.cursor >= this.moves.length)
272 return; //already at the end
273 move = this.moves[this.cursor++];
274 }
275 if (!!programmatic) //computer or human opponent
276 return this.animateMove(move);
277 // Not programmatic, or animation is over
278 if (this.mode == "human" && this.vr.turn == this.mycolor)
279 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
280
281
282 // TODO: play move, and stack it on this.moves (if a move was provided; otherwise just navigate)
283
284 if (this.score == "*") //TODO: I don't like this if()
285 {
286 // Emergency check, if human game started "at the same time"
287 // TODO: robustify this...
288 if (this.mode == "human" && !!move.computer)
289 return;
290 this.vr.play(move, "ingame");
291 // Is opponent in check?
292 this.incheck = this.vr.getCheckSquares(this.vr.turn);
293 if (this.sound == 2)
294 new Audio("/sounds/move.mp3").play().catch(err => {});
295 if (this.mode == "computer")
296 {
297 // Send the move to web worker (TODO: including his own moves?!)
298 this.compWorker.postMessage(["newmove",move]);
299 }
300 const eog = this.vr.getCurrentScore();
301 if (eog != "*")
302 {
303 if (["human","computer"].includes(this.mode))
304 this.endGame(eog);
305 else
306 {
307 // Just show score on screen (allow undo)
308 this.score = eog;
309 this.showScoreMsg();
310 }
311 }
312 }
313 // else
314 // {
315 // VariantRules.PlayOnBoard(this.vr.board, move);
316 // this.$forceUpdate(); //TODO: ?!
317 // }
318 if (["human","computer","friend"].includes(this.mode))
319 this.updateStorage(); //after our moves and opponent moves
320 if (this.mode == "computer" && this.vr.turn != this.mycolor && this.score == "*")
321 this.playComputerMove();
322 },
323 // TODO: merge two next functions
324 undo: function() {
325 // Navigate after game is over
326 if (this.cursor == 0)
327 return; //already at the beginning
328 if (this.cursor == this.vr.moves.length)
329 this.incheck = []; //in case of...
330 const move = this.vr.moves[--this.cursor];
331 VariantRules.UndoOnBoard(this.vr.board, move);
332 this.$forceUpdate(); //TODO: ?!
333 },
334 undoInGame: function() {
335 const lm = this.vr.lastMove;
336 if (!!lm)
337 {
338 this.vr.undo(lm);
339 if (this.sound == 2)
340 new Audio("/sounds/undo.mp3").play().catch(err => {});
341 this.incheck = this.vr.getCheckSquares(this.vr.turn);
342 }
343 },
344 },
345 })
346
347 //// TODO: keep moves list here
348 //get lastMove()
349 // {
350 // const L = this.moves.length;
351 // return (L>0 ? this.moves[L-1] : null);
352 // }
353 //
354 //// here too:
355 // move.notation = this.getNotation(move);
356 //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
357 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
358 //comme sur lichess