On the way to multi-tabs support
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90 1<template lang="pug">
7aa548e7 2main
bfe9a135 3 input#modalChat.modal(type="checkbox" @click="resetChatColor")
602d6bef 4 div#chatWrap(role="dialog" data-checkbox="modalChat" aria-labelledby="inputChat")
a1c48034
BA
5 #chat.card
6 label.modal-close(for="modalChat")
ed06d9e9 7 #participants
ac8f441c 8 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
ed06d9e9
BA
9 span(v-for="p in Object.values(people)" v-if="!!p.name")
10 | {{ p.name }}
11 span.anonymous(v-if="Object.values(people).some(p => !p.name)")
12 | + @nonymous
3837d4f7 13 Chat(:players="game.players" :pastChats="game.chats"
ac8f441c 14 :newChat="newChat" @mychat="processChat")
7aa548e7 15 .row
050ae3b5 16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
8c5f5390 17 span.variant-info {{ game.vname }}
cf94b843 18 button#chatBtn(onClick="doClick('modalChat')") Chat
4f518610 19 #actions(v-if="game.score=='*'")
602d6bef
BA
20 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}")
21 | {{ st.tr["Draw"] }}
77c50966
BA
22 button(v-if="!!game.mycolor" @click="abortGame") {{ st.tr["Abort"] }}
23 button(v-if="!!game.mycolor" @click="resign") {{ st.tr["Resign"] }}
050ae3b5
BA
24 #playersInfo
25 p
5bcc9b31
BA
26 span.name(:class="{connected: isConnected(0)}")
27 | {{ game.players[0].name || "@nonymous" }}
050ae3b5
BA
28 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
29 span.split-names -
5bcc9b31
BA
30 span.name(:class="{connected: isConnected(1)}")
31 | {{ game.players[1].name || "@nonymous" }}
050ae3b5 32 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
430a2038
BA
33 BaseGame(:game="game" :vr="vr" ref="basegame"
34 @newmove="processMove" @gameover="gameOver")
a6088c90
BA
35</template>
36
37<script>
46284a2f 38import BaseGame from "@/components/BaseGame.vue";
f21cd6d9 39import Chat from "@/components/Chat.vue";
a6088c90 40import { store } from "@/store";
967a2686 41import { GameStorage } from "@/utils/gameStorage";
5b87454c 42import { ppt } from "@/utils/datetime";
66d03f23 43import { extractTime } from "@/utils/timeControl";
f41ce580 44import { ArrayFun } from "@/utils/array";
dcd68c41 45import { processModalClick } from "@/utils/modalClick";
77c50966 46import { getScoreMessage } from "@/utils/scoring";
8418f0d7 47import params from "@/parameters";
a6088c90
BA
48
49export default {
50 name: 'my-game',
51 components: {
52 BaseGame,
5c8e044f 53 Chat,
a6088c90 54 },
f7121527 55 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
56 data: function() {
57 return {
58 st: store.state,
4b0384fa
BA
59 gameRef: { //given in URL (rid = remote ID)
60 id: "",
61 rid: ""
62 },
a0c41e7e
BA
63 game: { //passed to BaseGame
64 players:[{name:""},{name:""}],
65 rendered: false,
66 },
809ba2aa 67 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 68 vr: null, //"variant rules" object initialized from FEN
dcd68c41
BA
69 drawOffer: "",
70 people: {}, //players + observers
760adbce 71 lastate: undefined, //used if opponent send lastate before game is ready
72ccbd67 72 repeat: {}, //detect position repetition
ac8f441c 73 newChat: "",
8418f0d7
BA
74 conn: null,
75 page: "",
76 tempId: "", //to distinguish several tabs
a6088c90
BA
77 };
78 },
79 watch: {
5f131484
BA
80 "$route": function(to, from) {
81 this.gameRef.id = to.params["id"];
82 this.gameRef.rid = to.query["rid"];
83 this.loadGame();
a6088c90 84 },
5b87454c 85 "game.clocks": function(newState) {
b7cbbda1 86 if (this.game.moves.length < 2 || this.game.score != "*")
dce792f6 87 {
b7cbbda1 88 // 1st move not completed yet, or game over: freeze time
dce792f6
BA
89 this.virtualClocks = newState.map(s => ppt(s));
90 return;
91 }
809ba2aa 92 const currentTurn = this.vr.turn;
6fba6e0c 93 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
94 let countdown = newState[colorIdx] -
95 (Date.now() - this.game.initime[colorIdx])/1000;
c0b27606
BA
96 this.virtualClocks = [0,1].map(i => {
97 const removeTime = i == colorIdx
98 ? (Date.now() - this.game.initime[colorIdx])/1000
99 : 0;
100 return ppt(newState[i] - removeTime);
101 });
809ba2aa 102 let clockUpdate = setInterval(() => {
e69f159d 103 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
809ba2aa
BA
104 {
105 clearInterval(clockUpdate);
e69f159d 106 if (countdown < 0)
602d6bef 107 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
809ba2aa 108 }
9aa229f3 109 else
9aa229f3 110 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
809ba2aa 111 }, 1000);
5b87454c 112 },
92a523d1 113 },
dcd68c41 114 // NOTE: some redundant code with Hall.vue (related to people array)
a6088c90 115 created: function() {
5f131484
BA
116 // Always add myself to players' list
117 const my = this.st.user;
dcd68c41 118 this.$set(this.people, my.sid, {id:my.id, name:my.name});
dc284d90
BA
119 this.gameRef.id = this.$route.params["id"];
120 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
8418f0d7
BA
121 // Initialize connection
122 this.page = this.$route.path;
123 const connexionString = params.socketUrl +
124 "/?sid=" + this.st.user.sid +
125 "&tmpId=" + this.tempId +
126 "&page=" + encodeURIComponent(this.page);
127 this.conn = new WebSocket(connexionString);
128 this.conn.onmessage = this.socketMessageListener;
cdb34c93 129 const socketCloseListener = () => {
8418f0d7
BA
130 this.conn = new WebSocket(connexionString);
131 this.conn.addEventListener('message', this.socketMessageListener);
132 this.conn.addEventListener('close', socketCloseListener);
cdb34c93 133 };
8418f0d7 134 this.conn.onclose = socketCloseListener;
760adbce
BA
135 // Socket init required before loading remote game:
136 const socketInit = (callback) => {
8418f0d7 137 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
760adbce
BA
138 callback();
139 else //socket not ready yet (initial loading)
8418f0d7 140 this.conn.onopen = callback;
760adbce
BA
141 };
142 if (!this.gameRef.rid) //game stored locally or on server
143 this.loadGame(null, () => socketInit(this.roomInit));
144 else //game stored remotely: need socket to retrieve it
145 {
146 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
147 // --> It will be given when receiving "fullgame" socket event.
148 // A more general approach would be to store it somewhere.
149 socketInit(this.loadGame);
150 }
cdb34c93 151 },
dcd68c41
BA
152 mounted: function() {
153 document.getElementById("chatWrap").addEventListener(
154 "click", processModalClick);
155 },
8418f0d7
BA
156 beforeDestroy: function() {
157 this.conn.send(JSON.stringify({code:"disconnect",page:this.page}));
158 },
cdb34c93 159 methods: {
760adbce
BA
160 // O.1] Ask server for room composition:
161 roomInit: function() {
41c80bb6
BA
162 // Notify the room only now that I connected, because
163 // messages might be lost otherwise (if game loading is slow)
8418f0d7
BA
164 this.conn.send(JSON.stringify({code:"connect"}));
165 this.conn.send(JSON.stringify({code:"pollclients"}));
5f131484 166 },
050ae3b5 167 isConnected: function(index) {
29ced362
BA
168 const player = this.game.players[index];
169 // Is it me ?
170 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
050ae3b5 171 return true;
29ced362
BA
172 // Try to find a match in people:
173 return Object.keys(this.people).some(sid => sid == player.sid) ||
174 Object.values(this.people).some(p => p.id == player.uid);
050ae3b5 175 },
cdb34c93 176 socketMessageListener: function(msg) {
a6088c90 177 const data = JSON.parse(msg.data);
a6088c90
BA
178 switch (data.code)
179 {
6d9f4315 180 case "duplicate":
8418f0d7 181 this.conn.send(JSON.stringify({code:"duplicate",
d641bec1 182 page:"/game/" + this.game.id}));
bc093771 183 alert(this.st.tr["This tab is now offline"]);
6d9f4315 184 break;
5f131484
BA
185 // 0.2] Receive clients list (just socket IDs)
186 case "pollclients":
5f131484 187 data.sockIds.forEach(sid => {
dcd68c41
BA
188 if (!!this.people[sid])
189 return;
190 this.$set(this.people, sid, {id:0, name:""});
5f131484 191 // Ask only identity
8418f0d7 192 this.conn.send(JSON.stringify({code:"askidentity", target:sid}));
5f131484
BA
193 });
194 break;
5f131484 195 case "askidentity":
5f131484
BA
196 // Request for identification: reply if I'm not anonymous
197 if (this.st.user.id > 0)
198 {
8418f0d7 199 this.conn.send(JSON.stringify({code:"identity",
dcd68c41
BA
200 user: {
201 // NOTE: decompose to avoid revealing email
202 name: this.st.user.name,
203 sid: this.st.user.sid,
204 id: this.st.user.id,
205 },
206 target:data.from}));
5f131484
BA
207 }
208 break;
5f131484 209 case "identity":
41c80bb6
BA
210 this.$set(this.people, data.user.sid,
211 {id: data.user.id, name: data.user.name});
a0c41e7e
BA
212 // Ask potentially missed last state, if opponent and I play
213 if (!!this.game.mycolor
214 && this.game.type == "live" && this.game.score == "*"
215 && this.game.players.some(p => p.sid == data.user.sid))
216 {
8418f0d7 217 this.conn.send(JSON.stringify({code:"asklastate", target:data.user.sid}));
a0c41e7e
BA
218 }
219 break;
a0c41e7e 220 case "asklastate":
a0c41e7e
BA
221 // Sending last state if I played a move or score != "*"
222 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
633959bf 223 || this.game.score != "*" || this.drawOffer == "sent")
411d23cd 224 {
f41ce580 225 // Send our "last state" informations to opponent
411d23cd 226 const L = this.game.moves.length;
a0c41e7e 227 const myIdx = ["w","b"].indexOf(this.game.mycolor);
8418f0d7 228 this.conn.send(JSON.stringify({
411d23cd 229 code: "lastate",
a0c41e7e 230 target: data.from,
f41ce580
BA
231 state:
232 {
a0c41e7e
BA
233 // NOTE: lastMove (when defined) includes addTime
234 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
235 // Since we played a move (or abort or resign),
236 // only drawOffer=="sent" is possible
77c50966 237 drawSent: this.drawOffer == "sent",
f41ce580
BA
238 score: this.game.score,
239 movesCount: L,
a0c41e7e 240 initime: this.game.initime[1-myIdx], //relevant only if I played
f41ce580 241 }
411d23cd
BA
242 }));
243 }
a6088c90 244 break;
c6788ecf 245 case "askgame":
5fd5fb22
BA
246 // Send current (live) game if I play in (not an observer),
247 // and not asked by opponent (!)
248 if (this.game.type == "live"
249 && this.game.players.some(p => p.sid == this.st.user.sid)
250 && this.game.players.every(p => p.sid != data.from))
c6788ecf 251 {
5fd5fb22
BA
252 const myGame =
253 {
254 // Minimal game informations:
255 id: this.game.id,
256 players: this.game.players,
257 vid: this.game.vid,
258 timeControl: this.game.timeControl,
26f3a887 259 score: this.game.score,
5fd5fb22 260 };
8418f0d7 261 this.conn.send(JSON.stringify({code:"game",
5fd5fb22
BA
262 game:myGame, target:data.from}));
263 }
c6788ecf 264 break;
f41ce580 265 case "newmove":
77c50966 266 if (!!data.move.cancelDrawOffer) //opponent refuses draw
633959bf 267 {
77c50966 268 this.drawOffer = "";
c4f6d5a1
BA
269 // NOTE for corr games: drawOffer reset by player in turn
270 if (this.game.type == "live" && !!this.game.mycolor)
633959bf
BA
271 GameStorage.update(this.gameRef.id, {drawOffer: ""});
272 }
41c80bb6 273 this.$set(this.game, "moveToPlay", data.move);
f41ce580 274 break;
ac8f441c
BA
275 case "newchat":
276 this.newChat = data.chat;
277 if (!document.getElementById("modalChat").checked)
278 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
279 break;
a6088c90 280 case "lastate": //got opponent infos about last move
a0c41e7e
BA
281 this.lastate = data.state;
282 if (this.game.rendered) //game is rendered (Board component)
760adbce
BA
283 this.processLastate();
284 //else: will be processed when game is ready
a6088c90 285 break;
93d1d7a7 286 case "resign":
77c50966 287 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
93d1d7a7 288 break;
93d1d7a7 289 case "abort":
77c50966 290 this.gameOver("?", "Abort");
93d1d7a7 291 break;
2cc10cdb 292 case "draw":
77c50966 293 this.gameOver("1/2", data.message);
2cc10cdb
BA
294 break;
295 case "drawoffer":
41c80bb6
BA
296 // NOTE: observers don't know who offered draw
297 this.drawOffer = "received";
6d9f4315 298 break;
7e1a1fe9 299 case "askfullgame":
8418f0d7 300 this.conn.send(JSON.stringify({code:"fullgame",
41c80bb6 301 game:this.game, target:data.from}));
7e1a1fe9 302 break;
5f131484 303 case "fullgame":
760adbce
BA
304 // Callback "roomInit" to poll clients only after game is loaded
305 this.loadGame(data.game, this.roomInit);
5f131484 306 break;
5f131484 307 case "connect":
a0c41e7e 308 this.$set(this.people, data.from, {name:"", id:0});
8418f0d7 309 this.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
5f131484 310 break;
5f131484 311 case "disconnect":
dcd68c41 312 this.$delete(this.people, data.from);
a6088c90
BA
313 break;
314 }
cdb34c93 315 },
760adbce
BA
316 // lastate was received, but maybe game wasn't ready yet:
317 processLastate: function() {
318 const data = this.lastate;
319 this.lastate = undefined; //security...
320 const L = this.game.moves.length;
321 if (data.movesCount > L)
322 {
323 // Just got last move from him
a0c41e7e
BA
324 this.$set(this.game, "moveToPlay", Object.assign({}, data.lastMove, {initime: data.initime}));
325 }
633959bf
BA
326 if (data.drawSent)
327 this.drawOffer = "received";
a0c41e7e
BA
328 if (data.score != "*")
329 {
330 this.drawOffer = "";
331 if (this.game.score == "*")
332 this.gameOver(data.score);
760adbce
BA
333 }
334 },
dcd68c41 335 clickDraw: function() {
77c50966
BA
336 if (!this.game.mycolor)
337 return; //I'm just spectator
a1c48034 338 if (["received","threerep"].includes(this.drawOffer))
6fba6e0c 339 {
602d6bef 340 if (!confirm(this.st.tr["Accept draw?"]))
6fba6e0c 341 return;
a1c48034
BA
342 const message = (this.drawOffer == "received"
343 ? "Mutual agreement"
344 : "Three repetitions");
dcd68c41
BA
345 Object.keys(this.people).forEach(sid => {
346 if (sid != this.st.user.sid)
347 {
8418f0d7 348 this.conn.send(JSON.stringify({code:"draw",
dcd68c41
BA
349 message:message, target:sid}));
350 }
351 });
77c50966 352 this.gameOver("1/2", message);
2cc10cdb 353 }
41c80bb6 354 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
6fba6e0c 355 {
dfeb96ea
BA
356 if (this.game.mycolor != this.vr.turn)
357 return alert(this.st.tr["Draw offer only in your turn"]);
602d6bef 358 if (!confirm(this.st.tr["Offer draw?"]))
6fba6e0c 359 return;
760adbce 360 this.drawOffer = "sent";
dcd68c41
BA
361 Object.keys(this.people).forEach(sid => {
362 if (sid != this.st.user.sid)
8418f0d7 363 this.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
760adbce 364 });
dfeb96ea 365 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
a6088c90
BA
366 }
367 },
7f3484bd 368 abortGame: function() {
77c50966 369 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
7f3484bd 370 return;
77c50966 371 this.gameOver("?", "Abort");
dcd68c41
BA
372 Object.keys(this.people).forEach(sid => {
373 if (sid != this.st.user.sid)
5f131484 374 {
8418f0d7 375 this.conn.send(JSON.stringify({
5f131484 376 code: "abort",
dcd68c41 377 target: sid,
5f131484
BA
378 }));
379 }
7f3484bd 380 });
a6088c90
BA
381 },
382 resign: function(e) {
77c50966 383 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
a6088c90 384 return;
dcd68c41
BA
385 Object.keys(this.people).forEach(sid => {
386 if (sid != this.st.user.sid)
760adbce 387 {
8418f0d7 388 this.conn.send(JSON.stringify({code:"resign",
dcd68c41 389 side:this.game.mycolor, target:sid}));
760adbce
BA
390 }
391 });
77c50966 392 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 393 },
967a2686
BA
394 // 3 cases for loading a game:
395 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
396 // - from server (one correspondance game I play[ed] or not)
397 // - from remote peer (one live game I don't play, finished or not)
760adbce 398 loadGame: function(game, callback) {
967a2686 399 const afterRetrieval = async (game) => {
f41ce580
BA
400 const vModule = await import("@/variants/" + game.vname + ".js");
401 window.V = vModule.VariantRules;
402 this.vr = new V(game.fen);
c0b27606 403 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
92a523d1 404 const tc = extractTime(game.timeControl);
c0b27606
BA
405 if (gtype == "corr")
406 {
f41ce580
BA
407 if (game.players[0].color == "b")
408 {
409 // Adopt the same convention for live and corr games: [0] = white
410 [ game.players[0], game.players[1] ] =
411 [ game.players[1], game.players[0] ];
412 }
c0b27606 413 // corr game: needs to compute the clocks + initime
7f3484bd 414 // NOTE: clocks in seconds, initime in milliseconds
92a523d1 415 game.clocks = [tc.mainTime, tc.mainTime];
92b82def 416 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
b7cbbda1 417 if (game.score == "*") //otherwise no need to bother with time
92a523d1 418 {
b7cbbda1
BA
419 game.initime = [0, 0];
420 const L = game.moves.length;
421 if (L >= 3)
5f131484 422 {
b7cbbda1
BA
423 let addTime = [0, 0];
424 for (let i=2; i<L; i++)
425 {
426 addTime[i%2] += tc.increment -
427 (game.moves[i].played - game.moves[i-1].played) / 1000;
428 }
429 for (let i=0; i<=1; i++)
430 game.clocks[i] += addTime[i];
5f131484 431 }
b7cbbda1
BA
432 if (L >= 1)
433 game.initime[L%2] = game.moves[L-1].played;
92a523d1 434 }
92b82def 435 // Now that we used idx and played, re-format moves as for live games
6d68309a 436 game.moves = game.moves.map( (m) => {
92b82def 437 const s = m.squares;
6d68309a 438 return {
92b82def
BA
439 appear: s.appear,
440 vanish: s.vanish,
441 start: s.start,
442 end: s.end,
92b82def
BA
443 };
444 });
3837d4f7
BA
445 // Also sort chat messages (if any)
446 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
c0b27606 447 }
f41ce580
BA
448 const myIdx = game.players.findIndex(p => {
449 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
450 });
92a523d1 451 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
66d03f23
BA
452 {
453 game.clocks = [tc.mainTime, tc.mainTime];
b7cbbda1 454 if (game.score == "*")
22efa391 455 {
b7cbbda1
BA
456 game.initime[0] = Date.now();
457 if (myIdx >= 0)
22efa391 458 {
b7cbbda1
BA
459 // I play in this live game; corr games don't have clocks+initime
460 GameStorage.update(game.id,
461 {
462 clocks: game.clocks,
463 initime: game.initime,
464 });
465 }
22efa391 466 }
66d03f23 467 }
77c50966
BA
468 if (!!game.drawOffer)
469 {
470 if (game.drawOffer == "t") //three repetitions
471 this.drawOffer = "threerep";
472 else
473 {
474 if (myIdx < 0)
475 this.drawOffer = "received"; //by any of the players
476 else
477 {
478 // I play in this game:
479 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
480 this.drawOffer = "sent";
481 else //all other cases
482 this.drawOffer = "received";
483 }
484 }
485 }
486 if (!!game.scoreMsg)
487 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
4b0384fa
BA
488 this.game = Object.assign({},
489 game,
cf742aaf 490 // NOTE: assign mycolor here, since BaseGame could also be VS computer
6fba6e0c 491 {
c0b27606 492 type: gtype,
66d03f23 493 increment: tc.increment,
6fba6e0c 494 mycolor: [undefined,"w","b"][myIdx+1],
5f131484
BA
495 // opponent sid not strictly required (or available), but easier
496 // at least oppsid or oppid is available anyway:
497 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
498 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
6fba6e0c 499 }
4b0384fa 500 );
a0c41e7e
BA
501 this.$nextTick(() => {
502 this.game.rendered = true;
503 // Did lastate arrive before game was rendered?
504 if (!!this.lastate)
505 this.processLastate();
506 });
77c50966
BA
507 this.repeat = {}; //reset: scan past moves' FEN:
508 let repIdx = 0;
509 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
510 let vr_tmp = new V(game.fenStart);
511 game.moves.forEach(m => {
512 vr_tmp.play(m);
513 const fenObj = V.ParseFen( vr_tmp.getFen() );
514 repIdx = fenObj.position + "_" + fenObj.turn;
515 if (!!fenObj.flags)
516 repIdx += "_" + fenObj.flags;
517 this.repeat[repIdx] = (!!this.repeat[repIdx]
518 ? this.repeat[repIdx]+1
519 : 1);
520 });
521 if (this.repeat[repIdx] >= 3)
522 this.drawOffer = "threerep";
760adbce 523 callback();
967a2686
BA
524 };
525 if (!!game)
dc284d90 526 return afterRetrieval(game);
967a2686
BA
527 if (!!this.gameRef.rid)
528 {
760adbce 529 // Remote live game: forgetting about callback func... (TODO: design)
8418f0d7 530 this.conn.send(JSON.stringify(
5f131484 531 {code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
532 }
533 else
534 {
f41ce580 535 // Local or corr game
11667c79 536 GameStorage.get(this.gameRef.id, afterRetrieval);
967a2686 537 }
a6088c90 538 },
9d54ab89 539 // Post-process a move (which was just played)
ce87ac6a 540 processMove: function(move) {
a1c48034 541 // Update storage (corr or live) if I play in the game
6fba6e0c 542 const colorIdx = ["w","b"].indexOf(move.color);
a0c41e7e 543 const nextIdx = ["w","b"].indexOf(this.vr.turn);
9d54ab89 544 // https://stackoverflow.com/a/38750895
a1c48034
BA
545 if (!!this.game.mycolor)
546 {
547 const allowed_fields = ["appear", "vanish", "start", "end"];
548 // NOTE: 'var' to see this variable outside this block
549 var filtered_move = Object.keys(move)
550 .filter(key => allowed_fields.includes(key))
551 .reduce((obj, key) => {
552 obj[key] = move[key];
553 return obj;
554 }, {});
555 }
dc284d90 556 // Send move ("newmove" event) to people in the room (if our turn)
dce792f6 557 let addTime = 0;
9d54ab89 558 if (move.color == this.game.mycolor)
b4fb1612 559 {
77c50966
BA
560 if (this.drawOffer == "received") //I refuse draw
561 this.drawOffer = "";
dce792f6
BA
562 if (this.game.moves.length >= 2) //after first move
563 {
564 const elapsed = Date.now() - this.game.initime[colorIdx];
565 // elapsed time is measured in milliseconds
566 addTime = this.game.increment - elapsed/1000;
567 }
633959bf
BA
568 const sendMove = Object.assign({},
569 filtered_move,
570 {
571 addTime: addTime,
572 cancelDrawOffer: this.drawOffer=="",
573 });
dcd68c41
BA
574 Object.keys(this.people).forEach(sid => {
575 if (sid != this.st.user.sid)
dc284d90 576 {
8418f0d7 577 this.conn.send(JSON.stringify({
dc284d90 578 code: "newmove",
dcd68c41 579 target: sid,
dc284d90
BA
580 move: sendMove,
581 }));
582 }
583 });
a0c41e7e
BA
584 // (Add)Time indication: useful in case of lastate infos requested
585 move.addTime = addTime;
b4fb1612 586 }
5b87454c
BA
587 else
588 addTime = move.addTime; //supposed transmitted
77c50966
BA
589 // Update current game object:
590 this.game.moves.push(move);
591 this.game.fen = move.fen;
592 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
a0c41e7e
BA
593 // move.initime is set only when I receive a "lastate" move from opponent
594 this.game.initime[nextIdx] = move.initime || Date.now();
77c50966
BA
595 // If repetition detected, consider that a draw offer was received:
596 const fenObj = V.ParseFen(move.fen);
597 let repIdx = fenObj.position + "_" + fenObj.turn;
598 if (!!fenObj.flags)
599 repIdx += "_" + fenObj.flags;
600 this.repeat[repIdx] = (!!this.repeat[repIdx]
601 ? this.repeat[repIdx]+1
602 : 1);
603 if (this.repeat[repIdx] >= 3)
604 this.drawOffer = "threerep";
605 else if (this.drawOffer == "threerep")
606 this.drawOffer = "";
6d68309a
BA
607 // Since corr games are stored at only one location, update should be
608 // done only by one player for each move:
a1c48034
BA
609 if (!!this.game.mycolor &&
610 (this.game.type == "live" || move.color == this.game.mycolor))
967a2686 611 {
77c50966
BA
612 let drawCode = "";
613 switch (this.drawOffer)
614 {
615 case "threerep":
616 drawCode = "t";
617 break;
618 case "sent":
619 drawCode = this.game.mycolor;
620 break;
621 case "received":
622 drawCode = this.vr.turn;
623 break;
624 }
e69f159d 625 if (this.game.type == "corr")
f41ce580 626 {
e69f159d 627 GameStorage.update(this.gameRef.id,
6d68309a 628 {
e69f159d
BA
629 fen: move.fen,
630 move:
631 {
632 squares: filtered_move,
a0c41e7e 633 played: Date.now(),
77c50966 634 idx: this.game.moves.length - 1,
e69f159d 635 },
633959bf 636 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
e69f159d
BA
637 });
638 }
639 else //live
640 {
641 GameStorage.update(this.gameRef.id,
642 {
643 fen: move.fen,
644 move: filtered_move,
77c50966
BA
645 clocks: this.game.clocks,
646 initime: this.game.initime,
647 drawOffer: drawCode,
e69f159d
BA
648 });
649 }
6d68309a 650 }
b4fb1612 651 },
bfe9a135
BA
652 resetChatColor: function() {
653 // TODO: this is called twice, once on opening an once on closing
654 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
a1c48034 655 },
ac8f441c 656 processChat: function(chat) {
8418f0d7 657 this.conn.send(JSON.stringify({code:"newchat", chat:chat}));
0e16cb26
BA
658 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
659 if (this.game.type == "corr" && this.st.user.id > 0)
63ca2b89
BA
660 GameStorage.update(this.gameRef.id, {chat: chat});
661 },
430a2038 662 gameOver: function(score, scoreMsg) {
430a2038 663 this.game.score = score;
77c50966
BA
664 this.game.scoreMsg = this.st.tr[(!!scoreMsg
665 ? scoreMsg
666 : getScoreMessage(score))];
ab6f48ea
BA
667 const myIdx = this.game.players.findIndex(p => {
668 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
669 });
670 if (myIdx >= 0) //OK, I play in this game
dcd68c41
BA
671 {
672 GameStorage.update(this.gameRef.id,
673 {score: score, scoreMsg: scoreMsg});
674 }
ce87ac6a 675 },
a6088c90
BA
676 },
677};
678</script>
7e1a1fe9 679
41c80bb6 680<style lang="sass" scoped>
72ccbd67 681.connected
050ae3b5 682 background-color: lightgreen
72ccbd67 683
ed06d9e9
BA
684#participants
685 margin-left: 5px
686
687.anonymous
688 color: grey
689 font-style: italic
690
430a2038
BA
691@media screen and (min-width: 768px)
692 #actions
693 width: 300px
694@media screen and (max-width: 767px)
695 .game
696 width: 100%
72ccbd67 697
430a2038 698#actions
cf94b843 699 display: inline-block
430a2038 700 margin-top: 10px
430a2038
BA
701 button
702 display: inline-block
430a2038 703 margin: 0
a1c48034 704
050ae3b5
BA
705@media screen and (max-width: 767px)
706 #aboveBoard
707 text-align: center
885d93a7
BA
708@media screen and (min-width: 768px)
709 #aboveBoard
710 margin-left: 30%
050ae3b5 711
77c50966 712.variant-info
8c5f5390 713 font-weight: bold
77c50966 714 padding-right: 10px
77c50966 715
050ae3b5
BA
716.name
717 font-size: 1.5rem
718 padding: 1px
719
720.time
721 font-size: 2rem
722 display: inline-block
723 margin-left: 10px
724
725.split-names
726 display: inline-block
727 margin: 0 15px
728
430a2038 729#chat
a1c48034
BA
730 padding-top: 20px
731 max-width: 600px
430a2038 732 border: none;
cf94b843
BA
733
734#chatBtn
735 margin: 0 10px 0 0
dcd68c41
BA
736
737.draw-sent, .draw-sent:hover
738 background-color: lightyellow
739
740.draw-received, .draw-received:hover
741 background-color: lightgreen
742
743.draw-threerep, .draw-threerep:hover
744 background-color: #e4d1fc
7e1a1fe9 745</style>