Commit | Line | Data |
---|---|---|
a6088c90 | 1 | <template lang="pug"> |
7aa548e7 | 2 | main |
c292ebb2 BA |
3 | input#modalInfo.modal(type="checkbox") |
4 | div#infoDiv( | |
5 | role="dialog" | |
6 | data-checkbox="modalInfo" | |
7 | ) | |
8 | .card.text-center | |
9 | label.modal-close(for="modalInfo") | |
f14572c4 BA |
10 | a( |
11 | :href="'#/game/' + rematchId" | |
12 | onClick="document.getElementById('modalInfo').checked=false" | |
13 | ) | |
14 | | {{ st.tr["Rematch in progress"] }} | |
910d631b BA |
15 | input#modalChat.modal( |
16 | type="checkbox" | |
8be8238c | 17 | @click="toggleChat()" |
910d631b BA |
18 | ) |
19 | div#chatWrap( | |
20 | role="dialog" | |
21 | data-checkbox="modalChat" | |
22 | ) | |
5b4de147 | 23 | .card |
a1c48034 | 24 | label.modal-close(for="modalChat") |
ed06d9e9 | 25 | #participants |
afde7666 | 26 | span {{ st.tr["Participant(s):"] }} |
910d631b BA |
27 | span( |
28 | v-for="p in Object.values(people)" | |
a041d5d8 | 29 | v-if="p.focus && !!p.name" |
910d631b | 30 | ) |
ed06d9e9 | 31 | | {{ p.name }} |
a041d5d8 BA |
32 | span.anonymous( |
33 | v-if="Object.values(people).some(p => p.focus && !p.name)" | |
34 | ) | |
ed06d9e9 | 35 | | + @nonymous |
910d631b | 36 | Chat( |
aae89b49 | 37 | ref="chatcomp" |
910d631b BA |
38 | :players="game.players" |
39 | :pastChats="game.chats" | |
910d631b | 40 | @mychat="processChat" |
db1f1f9a | 41 | @chatcleared="clearChat" |
910d631b | 42 | ) |
5b4de147 BA |
43 | input#modalConfirm.modal(type="checkbox") |
44 | div#confirmDiv(role="dialog") | |
45 | .card | |
a17ae317 BA |
46 | .diagram( |
47 | v-if="!!vr && ['all','byrow'].includes(vr.showMoves)" | |
48 | v-html="curDiag" | |
49 | ) | |
50 | p.text-center(v-else) | |
51 | span {{ st.tr["Move played:"] + " " }} | |
52 | span.bold {{ moveNotation }} | |
53 | br | |
54 | span {{ st.tr["Are you sure?"] }} | |
5b4de147 BA |
55 | .button-group#buttonsConfirm |
56 | // onClick for acceptBtn: set dynamically | |
57 | button.acceptBtn | |
58 | span {{ st.tr["Validate"] }} | |
59 | button.refuseBtn(@click="cancelMove()") | |
60 | span {{ st.tr["Cancel"] }} | |
7aa548e7 | 61 | .row |
050ae3b5 | 62 | #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2 |
2f258c37 BA |
63 | span.variant-cadence {{ game.cadence }} |
64 | span.variant-name {{ game.vname }} | |
feaf1bf7 BA |
65 | span#nextGame( |
66 | v-if="nextIds.length > 0" | |
67 | @click="showNextGame()" | |
68 | ) | |
69 | | {{ st.tr["Next_g"] }} | |
70 | button#chatBtn.tooltip( | |
71 | onClick="window.doClick('modalChat')" | |
72 | aria-label="Chat" | |
73 | ) | |
74 | img(src="/images/icons/chat.svg") | |
4f518610 | 75 | #actions(v-if="game.score=='*'") |
feaf1bf7 | 76 | button.tooltip( |
910d631b BA |
77 | @click="clickDraw()" |
78 | :class="{['draw-' + drawOffer]: true}" | |
feaf1bf7 | 79 | :aria-label="st.tr['Draw']" |
910d631b | 80 | ) |
feaf1bf7 BA |
81 | img(src="/images/icons/draw.svg") |
82 | button.tooltip( | |
910d631b BA |
83 | v-if="!!game.mycolor" |
84 | @click="abortGame()" | |
feaf1bf7 | 85 | :aria-label="st.tr['Abort']" |
910d631b | 86 | ) |
feaf1bf7 BA |
87 | img(src="/images/icons/abort.svg") |
88 | button.tooltip( | |
910d631b BA |
89 | v-if="!!game.mycolor" |
90 | @click="resign()" | |
feaf1bf7 | 91 | :aria-label="st.tr['Resign']" |
910d631b | 92 | ) |
feaf1bf7 BA |
93 | img(src="/images/icons/resign.svg") |
94 | button.tooltip( | |
28b32b4f | 95 | v-else |
c292ebb2 BA |
96 | @click="clickRematch()" |
97 | :class="{['rematch-' + rematchOffer]: true}" | |
feaf1bf7 BA |
98 | :aria-label="st.tr['Rematch']" |
99 | ) | |
100 | img(src="/images/icons/rematch.svg") | |
050ae3b5 BA |
101 | #playersInfo |
102 | p | |
5bcc9b31 BA |
103 | span.name(:class="{connected: isConnected(0)}") |
104 | | {{ game.players[0].name || "@nonymous" }} | |
57eb158f BA |
105 | span.time( |
106 | v-if="game.score=='*'" | |
107 | :class="{yourturn: !!vr && vr.turn == 'w'}" | |
108 | ) | |
109 | span.time-left {{ virtualClocks[0][0] }} | |
110 | span.time-separator(v-if="!!virtualClocks[0][1]") : | |
aae89b49 BA |
111 | span.time-right(v-if="!!virtualClocks[0][1]") |
112 | | {{ virtualClocks[0][1] }} | |
050ae3b5 | 113 | span.split-names - |
5bcc9b31 BA |
114 | span.name(:class="{connected: isConnected(1)}") |
115 | | {{ game.players[1].name || "@nonymous" }} | |
57eb158f BA |
116 | span.time( |
117 | v-if="game.score=='*'" | |
118 | :class="{yourturn: !!vr && vr.turn == 'b'}" | |
119 | ) | |
120 | span.time-left {{ virtualClocks[1][0] }} | |
121 | span.time-separator(v-if="!!virtualClocks[1][1]") : | |
aae89b49 BA |
122 | span.time-right(v-if="!!virtualClocks[1][1]") |
123 | | {{ virtualClocks[1][1] }} | |
910d631b | 124 | BaseGame( |
8477e53d | 125 | ref="basegame" |
910d631b | 126 | :game="game" |
910d631b | 127 | @newmove="processMove" |
910d631b | 128 | ) |
a6088c90 BA |
129 | </template> |
130 | ||
131 | <script> | |
46284a2f | 132 | import BaseGame from "@/components/BaseGame.vue"; |
f21cd6d9 | 133 | import Chat from "@/components/Chat.vue"; |
a6088c90 | 134 | import { store } from "@/store"; |
967a2686 | 135 | import { GameStorage } from "@/utils/gameStorage"; |
5b87454c | 136 | import { ppt } from "@/utils/datetime"; |
23ecf008 | 137 | import { ajax } from "@/utils/ajax"; |
66d03f23 | 138 | import { extractTime } from "@/utils/timeControl"; |
51d87b52 | 139 | import { getRandString } from "@/utils/alea"; |
5aa14a21 BA |
140 | import { getScoreMessage } from "@/utils/scoring"; |
141 | import { getFullNotation } from "@/utils/notation"; | |
5b4de147 | 142 | import { getDiagram } from "@/utils/printDiagram"; |
dcd68c41 | 143 | import { processModalClick } from "@/utils/modalClick"; |
e71161fb | 144 | import { playMove, getFilteredMove } from "@/utils/playUndo"; |
1611a25f | 145 | import { ArrayFun } from "@/utils/array"; |
8418f0d7 | 146 | import params from "@/parameters"; |
a6088c90 | 147 | export default { |
6808d7a1 | 148 | name: "my-game", |
a6088c90 BA |
149 | components: { |
150 | BaseGame, | |
6808d7a1 | 151 | Chat |
a6088c90 | 152 | }, |
a6088c90 BA |
153 | data: function() { |
154 | return { | |
155 | st: store.state, | |
f54f4c26 BA |
156 | // gameRef can point to a corr game, local game or remote live game |
157 | gameRef: "", | |
feaf1bf7 | 158 | nextIds: [], |
aae89b49 BA |
159 | game: {}, //passed to BaseGame |
160 | // virtualClocks will be initialized from true game.clocks | |
161 | virtualClocks: [], | |
6dd02928 | 162 | vr: null, //"variant rules" object initialized from FEN |
dcd68c41 | 163 | drawOffer: "", |
585d0955 | 164 | rematchId: "", |
c292ebb2 | 165 | rematchOffer: "", |
584f81b9 | 166 | lastateAsked: false, |
dcd68c41 | 167 | people: {}, //players + observers |
760adbce | 168 | lastate: undefined, //used if opponent send lastate before game is ready |
72ccbd67 | 169 | repeat: {}, //detect position repetition |
5b4de147 | 170 | curDiag: "", //for corr moves confirmation |
8418f0d7 | 171 | conn: null, |
f9c36b2d BA |
172 | roomInitialized: false, |
173 | // If newmove has wrong index: ask fullgame again: | |
57eb158f | 174 | askGameTime: 0, |
dcff8e82 | 175 | gameIsLoading: false, |
f9c36b2d BA |
176 | // If asklastate got no reply, ask again: |
177 | gotLastate: false, | |
e5c1d0fb | 178 | gotMoveIdx: -1, //last move index received |
f9c36b2d BA |
179 | // If newmove got no pingback, send again: |
180 | opponentGotMove: false, | |
51d87b52 | 181 | connexionString: "", |
a17ae317 BA |
182 | // Incomplete info games: show move played |
183 | moveNotation: "", | |
aae89b49 | 184 | // Intervals from setInterval(): |
aae89b49 BA |
185 | askLastate: null, |
186 | retrySendmove: null, | |
187 | clockUpdate: null, | |
51d87b52 BA |
188 | // Related to (killing of) self multi-connects: |
189 | newConnect: {}, | |
6808d7a1 | 190 | killed: {} |
a6088c90 BA |
191 | }; |
192 | }, | |
193 | watch: { | |
aae89b49 BA |
194 | $route: function(to, from) { |
195 | if (from.params["id"] != to.params["id"]) { | |
196 | // Change everything: | |
197 | this.cleanBeforeDestroy(); | |
5aa14a21 BA |
198 | let boardDiv = document.querySelector(".game"); |
199 | if (!!boardDiv) | |
200 | // In case of incomplete information variant: | |
201 | boardDiv.style.visibility = "hidden"; | |
aae89b49 BA |
202 | this.atCreation(); |
203 | } else { | |
204 | // Same game ID | |
aae89b49 | 205 | this.nextIds = JSON.parse(this.$route.query["next"] || "[]"); |
f54f4c26 | 206 | this.loadGame(this.game); |
aae89b49 | 207 | } |
6808d7a1 | 208 | } |
92a523d1 | 209 | }, |
71468011 | 210 | // NOTE: some redundant code with Hall.vue (mostly related to people array) |
a6088c90 | 211 | created: function() { |
aae89b49 | 212 | this.atCreation(); |
cdb34c93 | 213 | }, |
dcd68c41 | 214 | mounted: function() { |
a041d5d8 | 215 | document.addEventListener('visibilitychange', this.visibilityChange); |
42a92848 BA |
216 | ["chatWrap", "infoDiv"].forEach(eltName => { |
217 | document.getElementById(eltName) | |
218 | .addEventListener("click", processModalClick); | |
219 | }); | |
5b4de147 BA |
220 | if ("ontouchstart" in window) { |
221 | // Disable tooltips on smartphones: | |
abb5917e | 222 | document.querySelectorAll("#aboveBoard .tooltip").forEach(elt => { |
407342b6 | 223 | elt.classList.remove("tooltip"); |
5b4de147 BA |
224 | }); |
225 | } | |
dcd68c41 | 226 | }, |
8418f0d7 | 227 | beforeDestroy: function() { |
a041d5d8 | 228 | document.removeEventListener('visibilitychange', this.visibilityChange); |
aae89b49 | 229 | this.cleanBeforeDestroy(); |
8418f0d7 | 230 | }, |
cdb34c93 | 231 | methods: { |
a041d5d8 BA |
232 | visibilityChange: function() { |
233 | // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27 | |
234 | this.send( | |
235 | document.visibilityState == "visible" | |
236 | ? "getfocus" | |
237 | : "losefocus" | |
238 | ); | |
239 | }, | |
aae89b49 BA |
240 | atCreation: function() { |
241 | // 0] (Re)Set variables | |
f54f4c26 BA |
242 | this.gameRef = this.$route.params["id"]; |
243 | // next = next corr games IDs to navigate faster (if applicable) | |
aae89b49 BA |
244 | this.nextIds = JSON.parse(this.$route.query["next"] || "[]"); |
245 | // Always add myself to players' list | |
246 | const my = this.st.user; | |
a041d5d8 BA |
247 | this.$set( |
248 | this.people, | |
249 | my.sid, | |
250 | { | |
251 | id: my.id, | |
252 | name: my.name, | |
253 | focus: true | |
254 | } | |
255 | ); | |
aae89b49 BA |
256 | this.game = { |
257 | players: [{ name: "" }, { name: "" }], | |
258 | chats: [], | |
259 | rendered: false | |
260 | }; | |
261 | let chatComp = this.$refs["chatcomp"]; | |
262 | if (!!chatComp) chatComp.chats = []; | |
263 | this.virtualClocks = [[0,0], [0,0]]; | |
264 | this.vr = null; | |
265 | this.drawOffer = ""; | |
584f81b9 | 266 | this.lastateAsked = false; |
c292ebb2 | 267 | this.rematchOffer = ""; |
aae89b49 | 268 | this.lastate = undefined; |
aae89b49 BA |
269 | this.roomInitialized = false; |
270 | this.askGameTime = 0; | |
271 | this.gameIsLoading = false; | |
272 | this.gotLastate = false; | |
273 | this.gotMoveIdx = -1; | |
274 | this.opponentGotMove = false; | |
aae89b49 BA |
275 | this.askLastate = null; |
276 | this.retrySendmove = null; | |
277 | this.clockUpdate = null; | |
278 | this.newConnect = {}; | |
279 | this.killed = {}; | |
280 | // 1] Initialize connection | |
281 | this.connexionString = | |
282 | params.socketUrl + | |
283 | "/?sid=" + | |
284 | this.st.user.sid + | |
cafe0166 BA |
285 | "&id=" + |
286 | this.st.user.id + | |
aae89b49 BA |
287 | "&tmpId=" + |
288 | getRandString() + | |
289 | "&page=" + | |
290 | // Discard potential "/?next=[...]" for page indication: | |
291 | encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]); | |
292 | this.conn = new WebSocket(this.connexionString); | |
293 | this.conn.onmessage = this.socketMessageListener; | |
294 | this.conn.onclose = this.socketCloseListener; | |
295 | // Socket init required before loading remote game: | |
296 | const socketInit = callback => { | |
297 | if (!!this.conn && this.conn.readyState == 1) | |
298 | // 1 == OPEN state | |
299 | callback(); | |
300 | else | |
301 | // Socket not ready yet (initial loading) | |
f54f4c26 | 302 | // NOTE: first arg is Websocket object, unused here: |
aae89b49 BA |
303 | this.conn.onopen = () => callback(); |
304 | }; | |
f54f4c26 BA |
305 | this.fetchGame((game) => { |
306 | if (!!game) | |
307 | this.loadVariantThenGame(game, () => socketInit(this.roomInit)); | |
308 | else | |
309 | // Live game stored remotely: need socket to retrieve it | |
310 | // NOTE: the callback "roomInit" will be lost, so we don't provide it. | |
311 | // --> It will be given when receiving "fullgame" socket event. | |
312 | socketInit(() => { this.send("askfullgame"); }); | |
313 | }); | |
aae89b49 BA |
314 | }, |
315 | cleanBeforeDestroy: function() { | |
aae89b49 BA |
316 | if (!!this.askLastate) |
317 | clearInterval(this.askLastate); | |
318 | if (!!this.retrySendmove) | |
319 | clearInterval(this.retrySendmove); | |
320 | if (!!this.clockUpdate) | |
321 | clearInterval(this.clockUpdate); | |
322 | this.send("disconnect"); | |
323 | }, | |
760adbce | 324 | roomInit: function() { |
f9c36b2d BA |
325 | if (!this.roomInitialized) { |
326 | // Notify the room only now that I connected, because | |
327 | // messages might be lost otherwise (if game loading is slow) | |
328 | this.send("connect"); | |
329 | this.send("pollclients"); | |
330 | // We may ask fullgame several times if some moves are lost, | |
331 | // but room should be init only once: | |
332 | this.roomInitialized = true; | |
333 | } | |
71468011 BA |
334 | }, |
335 | send: function(code, obj) { | |
f9c36b2d | 336 | if (!!this.conn) |
6808d7a1 | 337 | this.conn.send(JSON.stringify(Object.assign({ code: code }, obj))); |
5f131484 | 338 | }, |
050ae3b5 | 339 | isConnected: function(index) { |
29ced362 | 340 | const player = this.game.players[index]; |
a041d5d8 | 341 | // Is it me ? In this case no need to bother with focus |
0234201f | 342 | if (this.st.user.sid == player.sid || this.st.user.id == player.id) |
0a17525e BA |
343 | // Still have to check for name (because of potential multi-accounts |
344 | // on same browser, although this should be rare...) | |
345 | return (!this.st.user.name || this.st.user.name == player.name); | |
29ced362 | 346 | // Try to find a match in people: |
6808d7a1 | 347 | return ( |
1611a25f | 348 | ( |
a041d5d8 BA |
349 | !!player.sid && |
350 | Object.keys(this.people).some(sid => | |
351 | sid == player.sid && this.people[sid].focus) | |
1611a25f BA |
352 | ) |
353 | || | |
354 | ( | |
f14572c4 | 355 | !!player.id && |
a041d5d8 | 356 | Object.values(this.people).some(p => |
0234201f | 357 | p.id == player.id && p.focus) |
1611a25f | 358 | ) |
6808d7a1 | 359 | ); |
050ae3b5 | 360 | }, |
c292ebb2 BA |
361 | getOppsid: function() { |
362 | let oppsid = this.game.oppsid; | |
363 | if (!oppsid) { | |
364 | oppsid = Object.keys(this.people).find( | |
365 | sid => this.people[sid].id == this.game.oppid | |
366 | ); | |
367 | } | |
368 | // oppsid is useful only if opponent is online: | |
369 | if (!!oppsid && !!this.people[oppsid]) return oppsid; | |
370 | return null; | |
371 | }, | |
8be8238c BA |
372 | toggleChat: function() { |
373 | if (document.getElementById("modalChat").checked) | |
374 | // Entering chat | |
375 | document.getElementById("inputChat").focus(); | |
376 | // TODO: next line is only required when exiting chat, | |
377 | // but the event for now isn't well detected. | |
db1f1f9a BA |
378 | document.getElementById("chatBtn").classList.remove("somethingnew"); |
379 | }, | |
380 | processChat: function(chat) { | |
381 | this.send("newchat", { data: chat }); | |
382 | // NOTE: anonymous chats in corr games are not stored on server (TODO?) | |
383 | if (this.game.type == "corr" && this.st.user.id > 0) | |
aae89b49 | 384 | this.updateCorrGame({ chat: chat }); |
db1f1f9a BA |
385 | }, |
386 | clearChat: function() { | |
387 | // Nothing more to do if game is live (chats not recorded) | |
23ecf008 | 388 | if (this.game.type == "corr") { |
e57c4de4 BA |
389 | if (!!this.game.mycolor) { |
390 | ajax( | |
391 | "/chats", | |
392 | "DELETE", | |
393 | { data: { gid: this.game.id } } | |
394 | ); | |
395 | } | |
dcff8e82 | 396 | this.$set(this.game, "chats", []); |
db1f1f9a BA |
397 | } |
398 | }, | |
584f81b9 BA |
399 | getGameType: function(game) { |
400 | return game.cadence.indexOf("d") >= 0 ? "corr" : "live"; | |
401 | }, | |
cafe0166 BA |
402 | // Notify something after a new move (to opponent and me on MyGames page) |
403 | notifyMyGames: function(thing, data) { | |
404 | this.send( | |
405 | "notify" + thing, | |
406 | { | |
407 | data: data, | |
408 | targets: this.game.players.map(p => { | |
0234201f | 409 | return { sid: p.sid, id: p.id }; |
cafe0166 BA |
410 | }) |
411 | } | |
412 | ); | |
1611a25f | 413 | }, |
feaf1bf7 BA |
414 | showNextGame: function() { |
415 | // Did I play in current game? If not, add it to nextIds list | |
416 | if (this.game.score == "*" && this.vr.turn == this.game.mycolor) | |
417 | this.nextIds.unshift(this.game.id); | |
418 | const nextGid = this.nextIds.pop(); | |
419 | this.$router.push( | |
420 | "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds)); | |
421 | }, | |
d6f08e56 BA |
422 | askGameAgain: function() { |
423 | this.gameIsLoading = true; | |
aae89b49 | 424 | const currentUrl = document.location.href; |
57eb158f | 425 | const doAskGame = () => { |
e01e086d | 426 | if (document.location.href != currentUrl) return; //page change |
f54f4c26 BA |
427 | this.fetchGame((game) => { |
428 | if (!!game) | |
429 | // This is my game: just reload. | |
430 | this.loadGame(game); | |
431 | else | |
432 | // Just ask fullgame again (once!), this is much simpler. | |
433 | // If this fails, the user could just reload page :/ | |
434 | this.send("askfullgame"); | |
435 | }); | |
57eb158f BA |
436 | }; |
437 | // Delay of at least 2s between two game requests | |
438 | const now = Date.now(); | |
439 | const delay = Math.max(2000 - (now - this.askGameTime), 0); | |
440 | this.askGameTime = now; | |
441 | setTimeout(doAskGame, delay); | |
d6f08e56 | 442 | }, |
cdb34c93 | 443 | socketMessageListener: function(msg) { |
6808d7a1 | 444 | if (!this.conn) return; |
a6088c90 | 445 | const data = JSON.parse(msg.data); |
6808d7a1 | 446 | switch (data.code) { |
5f131484 | 447 | case "pollclients": |
934f7f70 BA |
448 | // TODO: shuffling and random filtering on server, if |
449 | // the room is really crowded. | |
5f131484 | 450 | data.sockIds.forEach(sid => { |
a041d5d8 BA |
451 | if (sid != this.st.user.sid) { |
452 | this.people[sid] = { focus: true }; | |
6808d7a1 | 453 | this.send("askidentity", { target: sid }); |
a041d5d8 | 454 | } |
5f131484 BA |
455 | }); |
456 | break; | |
71468011 | 457 | case "connect": |
efdfb4c7 | 458 | if (!this.people[data.from]) { |
a041d5d8 | 459 | this.people[data.from] = { focus: true }; |
51d87b52 | 460 | this.newConnect[data.from] = true; //for self multi-connects tests |
6808d7a1 | 461 | this.send("askidentity", { target: data.from }); |
51d87b52 | 462 | } |
71468011 BA |
463 | break; |
464 | case "disconnect": | |
465 | this.$delete(this.people, data.from); | |
466 | break; | |
a041d5d8 BA |
467 | case "getfocus": { |
468 | let player = this.people[data.from]; | |
469 | if (!!player) { | |
470 | player.focus = true; | |
471 | this.$forceUpdate(); //TODO: shouldn't be required | |
472 | } | |
473 | break; | |
474 | } | |
475 | case "losefocus": { | |
476 | let player = this.people[data.from]; | |
477 | if (!!player) { | |
478 | player.focus = false; | |
479 | this.$forceUpdate(); //TODO: shouldn't be required | |
480 | } | |
481 | break; | |
482 | } | |
51d87b52 BA |
483 | case "killed": |
484 | // I logged in elsewhere: | |
51d87b52 | 485 | this.conn = null; |
09d37571 | 486 | alert(this.st.tr["New connexion detected: tab now offline"]); |
51d87b52 | 487 | break; |
6808d7a1 | 488 | case "askidentity": { |
efdfb4c7 | 489 | // Request for identification |
51d87b52 BA |
490 | const me = { |
491 | // Decompose to avoid revealing email | |
492 | name: this.st.user.name, | |
493 | sid: this.st.user.sid, | |
6808d7a1 | 494 | id: this.st.user.id |
51d87b52 | 495 | }; |
6808d7a1 | 496 | this.send("identity", { data: me, target: data.from }); |
5f131484 | 497 | break; |
51d87b52 | 498 | } |
6808d7a1 | 499 | case "identity": { |
71468011 | 500 | const user = data.data; |
a041d5d8 BA |
501 | let player = this.people[user.sid]; |
502 | // player.focus is already set | |
503 | player.name = user.name; | |
504 | player.id = user.id; | |
505 | this.$forceUpdate(); //TODO: shouldn't be required | |
f9c36b2d BA |
506 | // If I multi-connect, kill current connexion if no mark (I'm older) |
507 | if (this.newConnect[user.sid]) { | |
6808d7a1 | 508 | if ( |
6808d7a1 BA |
509 | user.id > 0 && |
510 | user.id == this.st.user.id && | |
f9c36b2d BA |
511 | user.sid != this.st.user.sid && |
512 | !this.killed[this.st.user.sid] | |
6808d7a1 | 513 | ) { |
6808d7a1 | 514 | this.send("killme", { sid: this.st.user.sid }); |
51d87b52 | 515 | this.killed[this.st.user.sid] = true; |
51d87b52 | 516 | } |
f9c36b2d | 517 | delete this.newConnect[user.sid]; |
a0c41e7e | 518 | } |
dcff8e82 BA |
519 | if (!this.killed[this.st.user.sid]) { |
520 | // Ask potentially missed last state, if opponent and I play | |
521 | if ( | |
522 | !!this.game.mycolor && | |
523 | this.game.type == "live" && | |
524 | this.game.score == "*" && | |
525 | this.game.players.some(p => p.sid == user.sid) | |
526 | ) { | |
aae89b49 | 527 | this.send("asklastate", { target: user.sid }); |
e01e086d | 528 | let counter = 1; |
aae89b49 BA |
529 | this.askLastate = setInterval( |
530 | () => { | |
e01e086d BA |
531 | // Ask at most 3 times: |
532 | // if no reply after that there should be a network issue. | |
533 | if ( | |
534 | counter < 3 && | |
535 | !this.gotLastate && | |
536 | !!this.people[user.sid] | |
537 | ) { | |
aae89b49 | 538 | this.send("asklastate", { target: user.sid }); |
e01e086d BA |
539 | counter++; |
540 | } else { | |
aae89b49 | 541 | clearInterval(this.askLastate); |
e01e086d | 542 | } |
aae89b49 | 543 | }, |
e01e086d | 544 | 1500 |
aae89b49 | 545 | ); |
dcff8e82 BA |
546 | } |
547 | } | |
a0c41e7e | 548 | break; |
71468011 BA |
549 | } |
550 | case "askgame": | |
551 | // Send current (live) game if not asked by any of the players | |
6808d7a1 BA |
552 | if ( |
553 | this.game.type == "live" && | |
554 | this.game.players.every(p => p.sid != data.from[0]) | |
555 | ) { | |
71468011 BA |
556 | const myGame = { |
557 | id: this.game.id, | |
558 | fen: this.game.fen, | |
559 | players: this.game.players, | |
560 | vid: this.game.vid, | |
561 | cadence: this.game.cadence, | |
f54f4c26 | 562 | score: this.game.score |
71468011 | 563 | }; |
6808d7a1 | 564 | this.send("game", { data: myGame, target: data.from }); |
71468011 BA |
565 | } |
566 | break; | |
567 | case "askfullgame": | |
e8da204a BA |
568 | const gameToSend = Object.keys(this.game) |
569 | .filter(k => | |
570 | [ | |
571 | "id","fen","players","vid","cadence","fenStart","vname", | |
c292ebb2 | 572 | "moves","clocks","initime","score","drawOffer","rematchOffer" |
e8da204a BA |
573 | ].includes(k)) |
574 | .reduce( | |
575 | (obj, k) => { | |
576 | obj[k] = this.game[k]; | |
577 | return obj; | |
578 | }, | |
579 | {} | |
580 | ); | |
581 | this.send("fullgame", { data: gameToSend, target: data.from }); | |
71468011 BA |
582 | break; |
583 | case "fullgame": | |
584 | // Callback "roomInit" to poll clients only after game is loaded | |
f54f4c26 | 585 | this.loadVariantThenGame(data.data, this.roomInit); |
71468011 | 586 | break; |
a0c41e7e | 587 | case "asklastate": |
dcff8e82 | 588 | // Sending informative last state if I played a move or score != "*" |
584f81b9 BA |
589 | // If the game or moves aren't loaded yet, delay the sending: |
590 | if (!this.game || !this.game.moves) this.lastateAsked = true; | |
591 | else this.sendLastate(data.from); | |
c6788ecf | 592 | break; |
dcff8e82 BA |
593 | case "lastate": { |
594 | // Got opponent infos about last move | |
595 | this.gotLastate = true; | |
596 | if (!data.data.nothing) { | |
597 | this.lastate = data.data; | |
598 | if (this.game.rendered) | |
599 | // Game is rendered (Board component) | |
600 | this.processLastate(); | |
601 | // Else: will be processed when game is ready | |
602 | } | |
71468011 | 603 | break; |
dcff8e82 | 604 | } |
6808d7a1 | 605 | case "newmove": { |
dcff8e82 BA |
606 | const movePlus = data.data; |
607 | const movesCount = this.game.moves.length; | |
608 | if (movePlus.index > movesCount) { | |
609 | // This can only happen if I'm an observer and missed a move. | |
57eb158f BA |
610 | if (this.gotMoveIdx < movePlus.index) |
611 | this.gotMoveIdx = movePlus.index; | |
d6f08e56 BA |
612 | if (!this.gameIsLoading) this.askGameAgain(); |
613 | } | |
614 | else { | |
f9c36b2d | 615 | if ( |
dcff8e82 BA |
616 | movePlus.index < movesCount || |
617 | this.gotMoveIdx >= movePlus.index | |
f9c36b2d BA |
618 | ) { |
619 | // Opponent re-send but we already have the move: | |
620 | // (maybe he didn't receive our pingback...) | |
dcff8e82 | 621 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
f9c36b2d | 622 | } else { |
dcff8e82 BA |
623 | this.gotMoveIdx = movePlus.index; |
624 | const receiveMyMove = (movePlus.color == this.game.mycolor); | |
f9c36b2d BA |
625 | if (!receiveMyMove && !!this.game.mycolor) |
626 | // Notify opponent that I got the move: | |
dcff8e82 BA |
627 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
628 | if (movePlus.cancelDrawOffer) { | |
f9c36b2d BA |
629 | // Opponent refuses draw |
630 | this.drawOffer = ""; | |
631 | // NOTE for corr games: drawOffer reset by player in turn | |
632 | if ( | |
633 | this.game.type == "live" && | |
634 | !!this.game.mycolor && | |
635 | !receiveMyMove | |
636 | ) { | |
f54f4c26 | 637 | GameStorage.update(this.gameRef, { drawOffer: "" }); |
f9c36b2d BA |
638 | } |
639 | } | |
57eb158f BA |
640 | this.$refs["basegame"].play(movePlus.move, "received", null, true); |
641 | this.processMove( | |
dcff8e82 | 642 | movePlus.move, |
f9c36b2d | 643 | { |
e01e086d | 644 | clock: movePlus.clock, |
f9c36b2d BA |
645 | receiveMyMove: receiveMyMove |
646 | } | |
647 | ); | |
648 | } | |
633959bf | 649 | } |
a6088c90 | 650 | break; |
71468011 | 651 | } |
f9c36b2d BA |
652 | case "gotmove": { |
653 | this.opponentGotMove = true; | |
e01e086d BA |
654 | // Now his clock starts running: |
655 | const oppIdx = ['w','b'].indexOf(this.vr.turn); | |
656 | this.game.initime[oppIdx] = Date.now(); | |
657 | this.re_setClocks(); | |
f9c36b2d BA |
658 | break; |
659 | } | |
93d1d7a7 | 660 | case "resign": |
059228c9 BA |
661 | const score = (data.data == "b" ? "1-0" : "0-1"); |
662 | const side = (data.data == "w" ? "White" : "Black"); | |
8477e53d | 663 | this.gameOver(score, side + " surrender"); |
93d1d7a7 | 664 | break; |
93d1d7a7 | 665 | case "abort": |
8477e53d | 666 | this.gameOver("?", "Stop"); |
93d1d7a7 | 667 | break; |
2cc10cdb | 668 | case "draw": |
71468011 | 669 | this.gameOver("1/2", data.data); |
2cc10cdb BA |
670 | break; |
671 | case "drawoffer": | |
41c80bb6 BA |
672 | // NOTE: observers don't know who offered draw |
673 | this.drawOffer = "received"; | |
f54f4c26 BA |
674 | if (this.game.type == "live") { |
675 | GameStorage.update( | |
676 | this.gameRef, | |
677 | { drawOffer: V.GetOppCol(this.game.mycolor) } | |
678 | ); | |
679 | } | |
6d9f4315 | 680 | break; |
c292ebb2 BA |
681 | case "rematchoffer": |
682 | // NOTE: observers don't know who offered rematch | |
683 | this.rematchOffer = data.data ? "received" : ""; | |
f54f4c26 BA |
684 | if (this.game.type == "live") { |
685 | GameStorage.update( | |
686 | this.gameRef, | |
687 | { rematchOffer: V.GetOppCol(this.game.mycolor) } | |
688 | ); | |
689 | } | |
c292ebb2 BA |
690 | break; |
691 | case "newgame": { | |
692 | // A game started, redirect if I'm playing in | |
693 | const gameInfo = data.data; | |
584f81b9 | 694 | const gameType = this.getGameType(gameInfo); |
c292ebb2 | 695 | if ( |
584f81b9 BA |
696 | gameType == "live" && |
697 | gameInfo.players.some(p => p.sid == this.st.user.sid) | |
698 | ) { | |
699 | this.addAndGotoLiveGame(gameInfo); | |
700 | } else if ( | |
701 | gameType == "corr" && | |
0234201f | 702 | gameInfo.players.some(p => p.id == this.st.user.id) |
c292ebb2 BA |
703 | ) { |
704 | this.$router.push("/game/" + gameInfo.id); | |
705 | } else { | |
f54f4c26 | 706 | this.rematchId = gameInfo.id; |
c292ebb2 BA |
707 | document.getElementById("modalInfo").checked = true; |
708 | } | |
709 | break; | |
710 | } | |
71468011 | 711 | case "newchat": |
8be8238c | 712 | this.$refs["chatcomp"].newChat(data.data); |
71468011 | 713 | if (!document.getElementById("modalChat").checked) |
2f258c37 | 714 | document.getElementById("chatBtn").classList.add("somethingnew"); |
a6088c90 BA |
715 | break; |
716 | } | |
cdb34c93 | 717 | }, |
51d87b52 BA |
718 | socketCloseListener: function() { |
719 | this.conn = new WebSocket(this.connexionString); | |
6808d7a1 BA |
720 | this.conn.addEventListener("message", this.socketMessageListener); |
721 | this.conn.addEventListener("close", this.socketCloseListener); | |
51d87b52 | 722 | }, |
5aa14a21 | 723 | updateCorrGame: function(obj, callback) { |
aae89b49 BA |
724 | ajax( |
725 | "/games", | |
726 | "PUT", | |
727 | { | |
e57c4de4 | 728 | data: { |
f54f4c26 | 729 | gid: this.gameRef, |
e57c4de4 BA |
730 | newObj: obj |
731 | }, | |
732 | success: () => { | |
733 | if (!!callback) callback(); | |
734 | } | |
aae89b49 BA |
735 | } |
736 | ); | |
737 | }, | |
584f81b9 BA |
738 | sendLastate: function(target) { |
739 | if ( | |
740 | (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) || | |
741 | this.game.score != "*" || | |
742 | this.drawOffer == "sent" || | |
743 | this.rematchOffer == "sent" | |
744 | ) { | |
745 | // Send our "last state" informations to opponent | |
746 | const L = this.game.moves.length; | |
747 | const myIdx = ["w", "b"].indexOf(this.game.mycolor); | |
748 | const myLastate = { | |
749 | lastMove: L > 0 ? this.game.moves[L - 1] : undefined, | |
750 | clock: this.game.clocks[myIdx], | |
751 | // Since we played a move (or abort or resign), | |
752 | // only drawOffer=="sent" is possible | |
753 | drawSent: this.drawOffer == "sent", | |
754 | rematchSent: this.rematchOffer == "sent", | |
755 | score: this.game.score, | |
b83a675a | 756 | scoreMsg: this.game.scoreMsg, |
584f81b9 BA |
757 | movesCount: L, |
758 | initime: this.game.initime[1 - myIdx] //relevant only if I played | |
759 | }; | |
760 | this.send("lastate", { data: myLastate, target: target }); | |
761 | } else { | |
762 | this.send("lastate", { data: {nothing: true}, target: target }); | |
763 | } | |
764 | }, | |
760adbce BA |
765 | // lastate was received, but maybe game wasn't ready yet: |
766 | processLastate: function() { | |
767 | const data = this.lastate; | |
768 | this.lastate = undefined; //security... | |
769 | const L = this.game.moves.length; | |
6808d7a1 | 770 | if (data.movesCount > L) { |
760adbce | 771 | // Just got last move from him |
e01e086d BA |
772 | this.$refs["basegame"].play(data.lastMove, "received", null, true); |
773 | this.processMove(data.lastMove, { clock: data.clock }); | |
a0c41e7e | 774 | } |
6808d7a1 | 775 | if (data.drawSent) this.drawOffer = "received"; |
c292ebb2 | 776 | if (data.rematchSent) this.rematchOffer = "received"; |
6808d7a1 | 777 | if (data.score != "*") { |
a0c41e7e | 778 | this.drawOffer = ""; |
5aa14a21 | 779 | if (this.game.score == "*") |
a17ae317 | 780 | this.gameOver(data.score, data.scoreMsg); |
760adbce BA |
781 | } |
782 | }, | |
dcd68c41 | 783 | clickDraw: function() { |
6808d7a1 BA |
784 | if (!this.game.mycolor) return; //I'm just spectator |
785 | if (["received", "threerep"].includes(this.drawOffer)) { | |
786 | if (!confirm(this.st.tr["Accept draw?"])) return; | |
787 | const message = | |
788 | this.drawOffer == "received" | |
789 | ? "Mutual agreement" | |
790 | : "Three repetitions"; | |
791 | this.send("draw", { data: message }); | |
77c50966 | 792 | this.gameOver("1/2", message); |
6808d7a1 | 793 | } else if (this.drawOffer == "") { |
e71161fb | 794 | // No effect if drawOffer == "sent" |
9ee2826a | 795 | if (this.game.mycolor != this.vr.turn) { |
6808d7a1 | 796 | alert(this.st.tr["Draw offer only in your turn"]); |
6fba6e0c | 797 | return; |
6808d7a1 BA |
798 | } |
799 | if (!confirm(this.st.tr["Offer draw?"])) return; | |
760adbce | 800 | this.drawOffer = "sent"; |
71468011 | 801 | this.send("drawoffer"); |
aae89b49 BA |
802 | if (this.game.type == "live") { |
803 | GameStorage.update( | |
f54f4c26 | 804 | this.gameRef, |
aae89b49 BA |
805 | { drawOffer: this.game.mycolor } |
806 | ); | |
807 | } else this.updateCorrGame({ drawOffer: this.game.mycolor }); | |
a6088c90 BA |
808 | } |
809 | }, | |
584f81b9 BA |
810 | addAndGotoLiveGame: function(gameInfo, callback) { |
811 | const game = Object.assign( | |
812 | {}, | |
813 | gameInfo, | |
814 | { | |
815 | // (other) Game infos: constant | |
816 | fenStart: gameInfo.fen, | |
817 | vname: this.game.vname, | |
818 | created: Date.now(), | |
819 | // Game state (including FEN): will be updated | |
820 | moves: [], | |
821 | clocks: [-1, -1], //-1 = unstarted | |
822 | initime: [0, 0], //initialized later | |
823 | score: "*" | |
824 | } | |
825 | ); | |
826 | GameStorage.add(game, (err) => { | |
827 | // No error expected. | |
828 | if (!err) { | |
829 | if (this.st.settings.sound) | |
830 | new Audio("/sounds/newgame.flac").play().catch(() => {}); | |
585d0955 | 831 | if (!!callback) callback(); |
584f81b9 BA |
832 | this.$router.push("/game/" + gameInfo.id); |
833 | } | |
834 | }); | |
835 | }, | |
c292ebb2 BA |
836 | clickRematch: function() { |
837 | if (!this.game.mycolor) return; //I'm just spectator | |
838 | if (this.rematchOffer == "received") { | |
839 | // Start a new game! | |
840 | let gameInfo = { | |
841 | id: getRandString(), //ignored if corr | |
842 | fen: V.GenRandInitFen(this.game.randomness), | |
843 | players: this.game.players.reverse(), | |
844 | vid: this.game.vid, | |
845 | cadence: this.game.cadence | |
846 | }; | |
584f81b9 | 847 | const notifyNewGame = () => { |
f14572c4 | 848 | const oppsid = this.getOppsid(); //may be null |
584f81b9 | 849 | this.send("rnewgame", { data: gameInfo, oppsid: oppsid }); |
f14572c4 BA |
850 | // To main Hall if corr game: |
851 | if (this.game.type == "corr") | |
852 | this.send("newgame", { data: gameInfo }); | |
cafe0166 BA |
853 | // Also to MyGames page: |
854 | this.notifyMyGames("newgame", gameInfo); | |
584f81b9 BA |
855 | }; |
856 | if (this.game.type == "live") | |
857 | this.addAndGotoLiveGame(gameInfo, notifyNewGame); | |
c292ebb2 BA |
858 | else { |
859 | // corr game | |
860 | ajax( | |
861 | "/games", | |
862 | "POST", | |
863 | { | |
864 | // cid is useful to delete the challenge: | |
865 | data: { gameInfo: gameInfo }, | |
866 | success: (response) => { | |
867 | gameInfo.id = response.gameId; | |
584f81b9 | 868 | notifyNewGame(); |
c292ebb2 BA |
869 | this.$router.push("/game/" + response.gameId); |
870 | } | |
871 | } | |
872 | ); | |
873 | } | |
874 | } else if (this.rematchOffer == "") { | |
875 | this.rematchOffer = "sent"; | |
876 | this.send("rematchoffer", { data: true }); | |
877 | if (this.game.type == "live") { | |
878 | GameStorage.update( | |
f54f4c26 | 879 | this.gameRef, |
c292ebb2 BA |
880 | { rematchOffer: this.game.mycolor } |
881 | ); | |
882 | } else this.updateCorrGame({ rematchOffer: this.game.mycolor }); | |
883 | } else if (this.rematchOffer == "sent") { | |
884 | // Toggle rematch offer (on --> off) | |
885 | this.rematchOffer = ""; | |
886 | this.send("rematchoffer", { data: false }); | |
887 | if (this.game.type == "live") { | |
888 | GameStorage.update( | |
f54f4c26 | 889 | this.gameRef, |
c292ebb2 BA |
890 | { rematchOffer: '' } |
891 | ); | |
892 | } else this.updateCorrGame({ rematchOffer: 'n' }); | |
893 | } | |
894 | }, | |
7f3484bd | 895 | abortGame: function() { |
6808d7a1 | 896 | if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return; |
8477e53d | 897 | this.gameOver("?", "Stop"); |
71468011 | 898 | this.send("abort"); |
a6088c90 | 899 | }, |
6808d7a1 | 900 | resign: function() { |
77c50966 | 901 | if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"])) |
a6088c90 | 902 | return; |
6808d7a1 | 903 | this.send("resign", { data: this.game.mycolor }); |
059228c9 BA |
904 | const score = (this.game.mycolor == "w" ? "0-1" : "1-0"); |
905 | const side = (this.game.mycolor == "w" ? "White" : "Black"); | |
8477e53d | 906 | this.gameOver(score, side + " surrender"); |
a6088c90 | 907 | }, |
760adbce | 908 | loadGame: function(game, callback) { |
32f6285e BA |
909 | this.vr = new V(game.fen); |
910 | const gtype = this.getGameType(game); | |
911 | const tc = extractTime(game.cadence); | |
912 | const myIdx = game.players.findIndex(p => { | |
913 | return p.sid == this.st.user.sid || p.id == this.st.user.id; | |
914 | }); | |
915 | const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers | |
916 | if (!game.chats) game.chats = []; //live games don't have chat history | |
917 | if (gtype == "corr") { | |
918 | // NOTE: clocks in seconds, initime in milliseconds | |
919 | game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of | |
920 | game.clocks = [tc.mainTime, tc.mainTime]; | |
921 | const L = game.moves.length; | |
922 | if (game.score == "*") { | |
923 | // Set clocks + initime | |
f14572c4 | 924 | game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]; |
32f6285e BA |
925 | if (L >= 1) game.initime[L % 2] = game.moves[L-1].played; |
926 | // NOTE: game.clocks shouldn't be computed right now: | |
927 | // job will be done in re_setClocks() called soon below. | |
66d03f23 | 928 | } |
32f6285e BA |
929 | // Sort chat messages from newest to oldest |
930 | game.chats.sort((c1, c2) => { | |
931 | return c2.added - c1.added; | |
932 | }); | |
933 | if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) { | |
934 | // Did a chat message arrive after my last move? | |
935 | let dtLastMove = 0; | |
936 | if (L == 1 && myIdx == 0) | |
937 | dtLastMove = game.moves[0].played; | |
938 | else if (L >= 2) { | |
939 | if (L % 2 == 0) { | |
940 | // It's now white turn | |
941 | dtLastMove = game.moves[L-1-(1-myIdx)].played; | |
942 | } else { | |
943 | // Black turn: | |
944 | dtLastMove = game.moves[L-1-myIdx].played; | |
77c50966 BA |
945 | } |
946 | } | |
32f6285e BA |
947 | if (dtLastMove < game.chats[0].added) |
948 | document.getElementById("chatBtn").classList.add("somethingnew"); | |
949 | } | |
950 | // Now that we used idx and played, re-format moves as for live games | |
951 | game.moves = game.moves.map(m => m.squares); | |
952 | } | |
953 | if (gtype == "live" && game.clocks[0] < 0) { | |
954 | // Game is unstarted. clocks and initime are ignored until move 2 | |
955 | game.clocks = [tc.mainTime, tc.mainTime]; | |
956 | game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]; | |
957 | if (myIdx >= 0) { | |
958 | // I play in this live game | |
959 | GameStorage.update(game.id, { | |
960 | clocks: game.clocks, | |
961 | initime: game.initime | |
962 | }); | |
77c50966 | 963 | } |
32f6285e BA |
964 | } |
965 | // TODO: merge next 2 "if" conditions | |
966 | if (!!game.drawOffer) { | |
967 | if (game.drawOffer == "t") | |
968 | // Three repetitions | |
969 | this.drawOffer = "threerep"; | |
970 | else { | |
971 | // Draw offered by any of the players: | |
972 | if (myIdx < 0) this.drawOffer = "received"; | |
c292ebb2 BA |
973 | else { |
974 | // I play in this game: | |
975 | if ( | |
32f6285e BA |
976 | (game.drawOffer == "w" && myIdx == 0) || |
977 | (game.drawOffer == "b" && myIdx == 1) | |
c292ebb2 | 978 | ) |
32f6285e BA |
979 | this.drawOffer = "sent"; |
980 | else this.drawOffer = "received"; | |
c292ebb2 BA |
981 | } |
982 | } | |
32f6285e BA |
983 | } |
984 | if (!!game.rematchOffer) { | |
985 | if (myIdx < 0) this.rematchOffer = "received"; | |
986 | else { | |
987 | // I play in this game: | |
988 | if ( | |
989 | (game.rematchOffer == "w" && myIdx == 0) || | |
990 | (game.rematchOffer == "b" && myIdx == 1) | |
991 | ) | |
992 | this.rematchOffer = "sent"; | |
993 | else this.rematchOffer = "received"; | |
5aa14a21 | 994 | } |
32f6285e BA |
995 | } |
996 | this.repeat = {}; //reset: scan past moves' FEN: | |
997 | let repIdx = 0; | |
998 | let vr_tmp = new V(game.fenStart); | |
999 | let curTurn = "n"; | |
1000 | game.moves.forEach(m => { | |
1001 | playMove(m, vr_tmp); | |
1002 | const fenIdx = vr_tmp.getFen().replace(/ /g, "_"); | |
1003 | this.repeat[fenIdx] = this.repeat[fenIdx] | |
1004 | ? this.repeat[fenIdx] + 1 | |
1005 | : 1; | |
1006 | }); | |
1007 | if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep"; | |
1008 | this.game = Object.assign( | |
1009 | // NOTE: assign mycolor here, since BaseGame could also be VS computer | |
1010 | { | |
1011 | type: gtype, | |
1012 | increment: tc.increment, | |
1013 | mycolor: mycolor, | |
1014 | // opponent sid not strictly required (or available), but easier | |
1015 | // at least oppsid or oppid is available anyway: | |
1016 | oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid, | |
1017 | oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id | |
1018 | }, | |
1019 | game | |
1020 | ); | |
1021 | this.$refs["basegame"].re_setVariables(this.game); | |
1022 | if (!this.gameIsLoading) { | |
1023 | // Initial loading: | |
1024 | this.gotMoveIdx = game.moves.length - 1; | |
1025 | // If we arrive here after 'nextGame' action, the board might be hidden | |
1026 | let boardDiv = document.querySelector(".game"); | |
1027 | if (!!boardDiv && boardDiv.style.visibility == "hidden") | |
1028 | boardDiv.style.visibility = "visible"; | |
1029 | } | |
1030 | this.re_setClocks(); | |
1031 | this.$nextTick(() => { | |
1032 | this.game.rendered = true; | |
1033 | // Did lastate arrive before game was rendered? | |
1034 | if (this.lastate) this.processLastate(); | |
1035 | }); | |
1036 | if (this.lastateAsked) { | |
1037 | this.lastateAsked = false; | |
1038 | this.sendLastate(game.oppsid); | |
1039 | } | |
1040 | if (this.gameIsLoading) { | |
1041 | this.gameIsLoading = false; | |
1042 | if (this.gotMoveIdx >= game.moves.length) | |
1043 | // Some moves arrived meanwhile... | |
1044 | this.askGameAgain(); | |
1045 | } | |
1046 | if (!!callback) callback(); | |
1047 | }, | |
f54f4c26 BA |
1048 | loadVariantThenGame: async function(game, callback) { |
1049 | await import("@/variants/" + game.vname + ".js") | |
1050 | .then((vModule) => { | |
1051 | window.V = vModule[game.vname + "Rules"]; | |
1052 | this.loadGame(game, callback); | |
1053 | }); | |
1054 | }, | |
1055 | // 3 cases for loading a game: | |
1056 | // - from indexedDB (running or completed live game I play) | |
1057 | // - from server (one correspondance game I play[ed] or not) | |
1058 | // - from remote peer (one live game I don't play, finished or not) | |
1059 | fetchGame: function(callback) { | |
1060 | if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) { | |
1061 | // corr games identifiers are integers | |
1062 | ajax( | |
1063 | "/games", | |
1064 | "GET", | |
1065 | { | |
1066 | data: { gid: this.gameRef }, | |
1067 | success: (res) => { | |
1068 | res.game.moves.forEach(m => { | |
1069 | m.squares = JSON.parse(m.squares); | |
1070 | }); | |
1071 | callback(res.game); | |
e57c4de4 | 1072 | } |
f54f4c26 BA |
1073 | } |
1074 | ); | |
1075 | } else | |
1076 | // Local game (or live remote) | |
1077 | GameStorage.get(this.gameRef, callback); | |
a6088c90 | 1078 | }, |
9ef63965 | 1079 | re_setClocks: function() { |
dcff8e82 | 1080 | if (this.game.moves.length < 2 || this.game.score != "*") { |
9ef63965 | 1081 | // 1st move not completed yet, or game over: freeze time |
57eb158f | 1082 | this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':')); |
9ef63965 BA |
1083 | return; |
1084 | } | |
1085 | const currentTurn = this.vr.turn; | |
8477e53d | 1086 | const currentMovesCount = this.game.moves.length; |
6808d7a1 BA |
1087 | const colorIdx = ["w", "b"].indexOf(currentTurn); |
1088 | let countdown = | |
1089 | this.game.clocks[colorIdx] - | |
1090 | (Date.now() - this.game.initime[colorIdx]) / 1000; | |
1091 | this.virtualClocks = [0, 1].map(i => { | |
1092 | const removeTime = | |
1093 | i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0; | |
57eb158f | 1094 | return ppt(this.game.clocks[i] - removeTime).split(':'); |
9ef63965 | 1095 | }); |
e01e086d BA |
1096 | this.clockUpdate = setInterval( |
1097 | () => { | |
1098 | if ( | |
1099 | countdown < 0 || | |
1100 | this.game.moves.length > currentMovesCount || | |
1101 | this.game.score != "*" | |
1102 | ) { | |
1103 | clearInterval(this.clockUpdate); | |
1104 | if (countdown < 0) | |
1105 | this.gameOver( | |
1106 | currentTurn == "w" ? "0-1" : "1-0", | |
1107 | "Time" | |
1108 | ); | |
1109 | } else | |
1110 | this.$set( | |
1111 | this.virtualClocks, | |
1112 | colorIdx, | |
1113 | ppt(Math.max(0, --countdown)).split(':') | |
6808d7a1 | 1114 | ); |
e01e086d BA |
1115 | }, |
1116 | 1000 | |
1117 | ); | |
9ef63965 | 1118 | }, |
57eb158f | 1119 | // Update variables and storage after a move: |
e71161fb | 1120 | processMove: function(move, data) { |
e5c1d0fb | 1121 | if (!data) data = {}; |
e71161fb BA |
1122 | const moveCol = this.vr.turn; |
1123 | const doProcessMove = () => { | |
1124 | const colorIdx = ["w", "b"].indexOf(moveCol); | |
1125 | const nextIdx = 1 - colorIdx; | |
dcff8e82 | 1126 | const origMovescount = this.game.moves.length; |
e01e086d | 1127 | let addTime = 0; //for live games |
f9c36b2d | 1128 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
e71161fb BA |
1129 | if (this.drawOffer == "received") |
1130 | // I refuse draw | |
1131 | this.drawOffer = ""; | |
dcff8e82 | 1132 | if (this.game.type == "live" && origMovescount >= 2) { |
e71161fb BA |
1133 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
1134 | // elapsed time is measured in milliseconds | |
1135 | addTime = this.game.increment - elapsed / 1000; | |
1136 | } | |
dce792f6 | 1137 | } |
dcff8e82 | 1138 | // Update current game object: |
e71161fb | 1139 | playMove(move, this.vr); |
e01e086d BA |
1140 | // The move is played: stop clock |
1141 | clearInterval(this.clockUpdate); | |
f54f4c26 BA |
1142 | if (!data.score) |
1143 | // Received move, score is computed in BaseGame, but maybe not yet. | |
1144 | // ==> Compute it here, although this is redundant (TODO) | |
1145 | data.score = this.vr.getCurrentScore(); | |
1146 | if (data.score != "*") this.gameOver(data.score); | |
dcff8e82 | 1147 | this.game.moves.push(move); |
e71161fb | 1148 | this.game.fen = this.vr.getFen(); |
e01e086d BA |
1149 | if (this.game.type == "live") { |
1150 | if (!!data.clock) this.game.clocks[colorIdx] = data.clock; | |
1151 | else this.game.clocks[colorIdx] += addTime; | |
8be8238c BA |
1152 | } else { |
1153 | // In corr games, just reset clock to mainTime: | |
e01e086d BA |
1154 | this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime; |
1155 | } | |
1156 | // NOTE: opponent's initime is reset after "gotmove" is received | |
1157 | if ( | |
1158 | !this.game.mycolor || | |
1159 | moveCol != this.game.mycolor || | |
1160 | !!data.receiveMyMove | |
1161 | ) { | |
1162 | this.game.initime[nextIdx] = Date.now(); | |
1163 | } | |
e71161fb | 1164 | // If repetition detected, consider that a draw offer was received: |
f9c36b2d | 1165 | const fenObj = this.vr.getFenForRepeat(); |
e01e086d BA |
1166 | this.repeat[fenObj] = |
1167 | !!this.repeat[fenObj] | |
1168 | ? this.repeat[fenObj] + 1 | |
1169 | : 1; | |
f9c36b2d | 1170 | if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep"; |
e71161fb | 1171 | else if (this.drawOffer == "threerep") this.drawOffer = ""; |
dcff8e82 BA |
1172 | if (!!this.game.mycolor && !data.receiveMyMove) { |
1173 | // NOTE: 'var' to see that variable outside this block | |
1174 | var filtered_move = getFilteredMove(move); | |
1175 | } | |
cafe0166 BA |
1176 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
1177 | // Notify turn on MyGames page: | |
1178 | this.notifyMyGames( | |
1179 | "turn", | |
1180 | { | |
f54f4c26 | 1181 | gid: this.gameRef, |
cafe0166 BA |
1182 | turn: this.vr.turn |
1183 | } | |
1184 | ); | |
1185 | } | |
aae89b49 BA |
1186 | // Since corr games are stored at only one location, update should be |
1187 | // done only by one player for each move: | |
e71161fb | 1188 | if ( |
f9c36b2d BA |
1189 | !!this.game.mycolor && |
1190 | !data.receiveMyMove && | |
e71161fb BA |
1191 | (this.game.type == "live" || moveCol == this.game.mycolor) |
1192 | ) { | |
1193 | let drawCode = ""; | |
1194 | switch (this.drawOffer) { | |
1195 | case "threerep": | |
1196 | drawCode = "t"; | |
1197 | break; | |
1198 | case "sent": | |
1199 | drawCode = this.game.mycolor; | |
1200 | break; | |
1201 | case "received": | |
1202 | drawCode = V.GetOppCol(this.game.mycolor); | |
1203 | break; | |
1204 | } | |
1205 | if (this.game.type == "corr") { | |
aae89b49 BA |
1206 | // corr: only move, fen and score |
1207 | this.updateCorrGame({ | |
e71161fb BA |
1208 | fen: this.game.fen, |
1209 | move: { | |
1210 | squares: filtered_move, | |
dcff8e82 | 1211 | idx: origMovescount |
e71161fb BA |
1212 | }, |
1213 | // Code "n" for "None" to force reset (otherwise it's ignored) | |
1214 | drawOffer: drawCode || "n" | |
1215 | }); | |
1216 | } | |
57eb158f BA |
1217 | else { |
1218 | const updateStorage = () => { | |
f54f4c26 | 1219 | GameStorage.update(this.gameRef, { |
57eb158f BA |
1220 | fen: this.game.fen, |
1221 | move: filtered_move, | |
1222 | moveIdx: origMovescount, | |
1223 | clocks: this.game.clocks, | |
1224 | initime: this.game.initime, | |
1225 | drawOffer: drawCode | |
1226 | }); | |
1227 | }; | |
1228 | // The active tab can update storage immediately | |
1229 | if (!document.hidden) updateStorage(); | |
1230 | // Small random delay otherwise | |
1231 | else setTimeout(updateStorage, 500 + 1000 * Math.random()); | |
e71161fb | 1232 | } |
e69f159d | 1233 | } |
dcff8e82 BA |
1234 | // Send move ("newmove" event) to people in the room (if our turn) |
1235 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { | |
e01e086d | 1236 | let sendMove = { |
dcff8e82 BA |
1237 | move: filtered_move, |
1238 | index: origMovescount, | |
1239 | // color is required to check if this is my move (if several tabs opened) | |
1240 | color: moveCol, | |
dcff8e82 BA |
1241 | cancelDrawOffer: this.drawOffer == "" |
1242 | }; | |
e01e086d BA |
1243 | if (this.game.type == "live") |
1244 | sendMove["clock"] = this.game.clocks[colorIdx]; | |
dcff8e82 BA |
1245 | this.opponentGotMove = false; |
1246 | this.send("newmove", {data: sendMove}); | |
1247 | // If the opponent doesn't reply gotmove soon enough, re-send move: | |
e01e086d BA |
1248 | // Do this at most 2 times, because mpore would mean network issues, |
1249 | // opponent would then be expected to disconnect/reconnect. | |
1250 | let counter = 1; | |
1251 | const currentUrl = document.location.href; | |
aae89b49 | 1252 | this.retrySendmove = setInterval( |
57eb158f | 1253 | () => { |
e01e086d BA |
1254 | if ( |
1255 | counter >= 3 || | |
1256 | this.opponentGotMove || | |
1257 | document.location.href != currentUrl //page change | |
1258 | ) { | |
aae89b49 | 1259 | clearInterval(this.retrySendmove); |
57eb158f BA |
1260 | return; |
1261 | } | |
c292ebb2 BA |
1262 | const oppsid = this.getOppsid(); |
1263 | if (!oppsid) | |
57eb158f | 1264 | // Opponent is disconnected: he'll ask last state |
aae89b49 | 1265 | clearInterval(this.retrySendmove); |
e01e086d BA |
1266 | else { |
1267 | this.send("newmove", { data: sendMove, target: oppsid }); | |
1268 | counter++; | |
1269 | } | |
57eb158f | 1270 | }, |
e01e086d | 1271 | 1500 |
57eb158f | 1272 | ); |
dcff8e82 | 1273 | } |
e01e086d BA |
1274 | else |
1275 | // Not my move or I'm an observer: just start other player's clock | |
1276 | this.re_setClocks(); | |
e71161fb | 1277 | }; |
f9c36b2d BA |
1278 | if ( |
1279 | this.game.type == "corr" && | |
1280 | moveCol == this.game.mycolor && | |
1281 | !data.receiveMyMove | |
1282 | ) { | |
a17ae317 | 1283 | let boardDiv = document.querySelector(".game"); |
5aa14a21 BA |
1284 | const afterSetScore = () => { |
1285 | doProcessMove(); | |
1286 | if (this.st.settings.gotonext && this.nextIds.length > 0) | |
1287 | this.showNextGame(); | |
1288 | else { | |
5aa14a21 | 1289 | // The board might have been hidden: |
5aa14a21 BA |
1290 | if (boardDiv.style.visibility == "hidden") |
1291 | boardDiv.style.visibility = "visible"; | |
e71161fb | 1292 | } |
5aa14a21 | 1293 | }; |
a17ae317 BA |
1294 | let el = document.querySelector("#buttonsConfirm > .acceptBtn"); |
1295 | // We may play several moves in a row: in case of, remove listener: | |
1296 | let elClone = el.cloneNode(true); | |
1297 | el.parentNode.replaceChild(elClone, el); | |
1298 | elClone.addEventListener( | |
1299 | "click", | |
1300 | () => { | |
1301 | document.getElementById("modalConfirm").checked = false; | |
1302 | if (!!data.score && data.score != "*") | |
1303 | // Set score first | |
1304 | this.gameOver(data.score, null, afterSetScore); | |
1305 | else afterSetScore(); | |
1306 | } | |
1307 | ); | |
1308 | // PlayOnBoard is enough, and more appropriate for Synchrone Chess | |
1309 | V.PlayOnBoard(this.vr.board, move); | |
1310 | const position = this.vr.getBaseFen(); | |
1311 | V.UndoOnBoard(this.vr.board, move); | |
5aa14a21 | 1312 | if (["all","byrow"].includes(V.ShowMoves)) { |
5aa14a21 BA |
1313 | this.curDiag = getDiagram({ |
1314 | position: position, | |
1315 | orientation: V.CanFlip ? this.game.mycolor : "w" | |
1316 | }); | |
f3fe29d8 BA |
1317 | document.querySelector("#confirmDiv > .card").style.width = |
1318 | boardDiv.offsetWidth + "px"; | |
5aa14a21 BA |
1319 | } else { |
1320 | // Incomplete information: just ask confirmation | |
a17ae317 | 1321 | // Hide the board, because otherwise it could reveal infos |
5aa14a21 | 1322 | boardDiv.style.visibility = "hidden"; |
a17ae317 | 1323 | this.moveNotation = getFullNotation(move); |
5aa14a21 | 1324 | } |
a17ae317 | 1325 | document.getElementById("modalConfirm").checked = true; |
6d68309a | 1326 | } |
aae89b49 | 1327 | else { |
5aa14a21 | 1328 | // Normal situation |
5aa14a21 | 1329 | if (!!data.score && data.score != "*") |
e01e086d BA |
1330 | this.gameOver(data.score, null, doProcessMove); |
1331 | else doProcessMove(); | |
aae89b49 | 1332 | } |
b4fb1612 | 1333 | }, |
5b4de147 | 1334 | cancelMove: function() { |
a17ae317 BA |
1335 | let boardDiv = document.querySelector(".game"); |
1336 | if (boardDiv.style.visibility == "hidden") | |
1337 | boardDiv.style.visibility = "visible"; | |
5b4de147 BA |
1338 | document.getElementById("modalConfirm").checked = false; |
1339 | this.$refs["basegame"].cancelLastMove(); | |
1340 | }, | |
5aa14a21 BA |
1341 | // In corr games, callback to change page only after score is set: |
1342 | gameOver: function(score, scoreMsg, callback) { | |
430a2038 | 1343 | this.game.score = score; |
5aa14a21 | 1344 | if (!scoreMsg) scoreMsg = getScoreMessage(score); |
a17ae317 | 1345 | this.game.scoreMsg = scoreMsg; |
5aa14a21 | 1346 | this.$set(this.game, "scoreMsg", scoreMsg); |
ab6f48ea | 1347 | const myIdx = this.game.players.findIndex(p => { |
0234201f | 1348 | return p.sid == this.st.user.sid || p.id == this.st.user.id; |
ab6f48ea | 1349 | }); |
6808d7a1 | 1350 | if (myIdx >= 0) { |
8477e53d | 1351 | // OK, I play in this game |
aae89b49 | 1352 | const scoreObj = { |
6808d7a1 BA |
1353 | score: score, |
1354 | scoreMsg: scoreMsg | |
aae89b49 | 1355 | }; |
5aa14a21 | 1356 | if (this.game.type == "live") { |
f54f4c26 | 1357 | GameStorage.update(this.gameRef, scoreObj); |
5aa14a21 BA |
1358 | if (!!callback) callback(); |
1359 | } | |
1360 | else this.updateCorrGame(scoreObj, callback); | |
48ab808f | 1361 | // Notify the score to main Hall. TODO: only one player (currently double send) |
6808d7a1 | 1362 | this.send("result", { gid: this.game.id, score: score }); |
cafe0166 BA |
1363 | // Also to MyGames page (TODO: doubled as well...) |
1364 | this.notifyMyGames( | |
1365 | "score", | |
1366 | { | |
f54f4c26 | 1367 | gid: this.gameRef, |
cafe0166 BA |
1368 | score: score |
1369 | } | |
1370 | ); | |
dcd68c41 | 1371 | } |
5aa14a21 | 1372 | else if (!!callback) callback(); |
6808d7a1 BA |
1373 | } |
1374 | } | |
a6088c90 BA |
1375 | }; |
1376 | </script> | |
7e1a1fe9 | 1377 | |
41c80bb6 | 1378 | <style lang="sass" scoped> |
c292ebb2 BA |
1379 | #infoDiv > .card |
1380 | padding: 15px 0 | |
1381 | max-width: 430px | |
1382 | ||
72ccbd67 | 1383 | .connected |
050ae3b5 | 1384 | background-color: lightgreen |
72ccbd67 | 1385 | |
ed06d9e9 BA |
1386 | #participants |
1387 | margin-left: 5px | |
1388 | ||
1389 | .anonymous | |
1390 | color: grey | |
1391 | font-style: italic | |
1392 | ||
ec905cbc BA |
1393 | #playersInfo > p |
1394 | margin: 0 | |
1395 | ||
430a2038 BA |
1396 | @media screen and (min-width: 768px) |
1397 | #actions | |
1398 | width: 300px | |
1399 | @media screen and (max-width: 767px) | |
1400 | .game | |
1401 | width: 100% | |
72ccbd67 | 1402 | |
430a2038 | 1403 | #actions |
cf94b843 | 1404 | display: inline-block |
1d6d7b1d | 1405 | margin: 0 |
feaf1bf7 BA |
1406 | |
1407 | button | |
1408 | display: inline-block | |
1409 | margin: 0 | |
1410 | display: inline-flex | |
1411 | img | |
1412 | height: 24px | |
1413 | display: flex | |
1414 | @media screen and (max-width: 767px) | |
1415 | height: 18px | |
a1c48034 | 1416 | |
050ae3b5 BA |
1417 | @media screen and (max-width: 767px) |
1418 | #aboveBoard | |
1419 | text-align: center | |
885d93a7 BA |
1420 | @media screen and (min-width: 768px) |
1421 | #aboveBoard | |
1422 | margin-left: 30% | |
050ae3b5 | 1423 | |
2f258c37 BA |
1424 | .variant-cadence |
1425 | padding-right: 10px | |
1426 | ||
1427 | .variant-name | |
8c5f5390 | 1428 | font-weight: bold |
77c50966 | 1429 | padding-right: 10px |
77c50966 | 1430 | |
feaf1bf7 BA |
1431 | span#nextGame |
1432 | background-color: #edda99 | |
1433 | cursor: pointer | |
1434 | display: inline-block | |
1435 | margin-right: 10px | |
1436 | ||
57eb158f | 1437 | span.name |
050ae3b5 | 1438 | font-size: 1.5rem |
57eb158f | 1439 | padding: 0 3px |
050ae3b5 | 1440 | |
57eb158f | 1441 | span.time |
050ae3b5 BA |
1442 | font-size: 2rem |
1443 | display: inline-block | |
57eb158f BA |
1444 | .time-left |
1445 | margin-left: 10px | |
1446 | .time-right | |
1447 | margin-left: 5px | |
1448 | .time-separator | |
1449 | margin-left: 5px | |
1450 | position: relative | |
1451 | top: -1px | |
1452 | ||
1453 | span.yourturn | |
1454 | color: #831B1B | |
1455 | .time-separator | |
1456 | animation: blink-animation 2s steps(3, start) infinite | |
1457 | @keyframes blink-animation | |
1458 | to | |
1459 | visibility: hidden | |
050ae3b5 BA |
1460 | |
1461 | .split-names | |
1462 | display: inline-block | |
1463 | margin: 0 15px | |
1464 | ||
5b4de147 | 1465 | #chatWrap > .card |
a1c48034 | 1466 | padding-top: 20px |
a154d45e | 1467 | max-width: 767px |
5b4de147 BA |
1468 | border: none |
1469 | ||
1470 | #confirmDiv > .card | |
1471 | max-width: 767px | |
1472 | max-height: 100% | |
cf94b843 | 1473 | |
dcd68c41 BA |
1474 | .draw-sent, .draw-sent:hover |
1475 | background-color: lightyellow | |
1476 | ||
1477 | .draw-received, .draw-received:hover | |
1478 | background-color: lightgreen | |
1479 | ||
1480 | .draw-threerep, .draw-threerep:hover | |
1481 | background-color: #e4d1fc | |
2f258c37 | 1482 | |
c292ebb2 BA |
1483 | .rematch-sent, .rematch-sent:hover |
1484 | background-color: lightyellow | |
1485 | ||
1486 | .rematch-received, .rematch-received:hover | |
1487 | background-color: lightgreen | |
1488 | ||
2f258c37 BA |
1489 | .somethingnew |
1490 | background-color: #c5fefe | |
5b4de147 BA |
1491 | |
1492 | .diagram | |
1493 | margin: 0 auto | |
5b4de147 BA |
1494 | width: 100% |
1495 | ||
1496 | #buttonsConfirm | |
1497 | margin: 0 | |
1498 | & > button > span | |
1499 | width: 100% | |
1500 | text-align: center | |
1501 | ||
1502 | button.acceptBtn | |
1503 | background-color: lightgreen | |
1504 | button.refuseBtn | |
1505 | background-color: red | |
7e1a1fe9 | 1506 | </style> |