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