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