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