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": |
5f131484 | 448 | data.sockIds.forEach(sid => { |
a041d5d8 BA |
449 | if (sid != this.st.user.sid) { |
450 | this.people[sid] = { focus: true }; | |
6808d7a1 | 451 | this.send("askidentity", { target: sid }); |
a041d5d8 | 452 | } |
5f131484 BA |
453 | }); |
454 | break; | |
71468011 | 455 | case "connect": |
efdfb4c7 | 456 | if (!this.people[data.from]) { |
a041d5d8 | 457 | this.people[data.from] = { focus: true }; |
51d87b52 | 458 | this.newConnect[data.from] = true; //for self multi-connects tests |
6808d7a1 | 459 | this.send("askidentity", { target: data.from }); |
51d87b52 | 460 | } |
71468011 BA |
461 | break; |
462 | case "disconnect": | |
463 | this.$delete(this.people, data.from); | |
464 | break; | |
a041d5d8 BA |
465 | case "getfocus": { |
466 | let player = this.people[data.from]; | |
467 | if (!!player) { | |
468 | player.focus = true; | |
469 | this.$forceUpdate(); //TODO: shouldn't be required | |
470 | } | |
471 | break; | |
472 | } | |
473 | case "losefocus": { | |
474 | let player = this.people[data.from]; | |
475 | if (!!player) { | |
476 | player.focus = false; | |
477 | this.$forceUpdate(); //TODO: shouldn't be required | |
478 | } | |
479 | break; | |
480 | } | |
51d87b52 BA |
481 | case "killed": |
482 | // I logged in elsewhere: | |
51d87b52 | 483 | this.conn = null; |
09d37571 | 484 | alert(this.st.tr["New connexion detected: tab now offline"]); |
51d87b52 | 485 | break; |
6808d7a1 | 486 | case "askidentity": { |
efdfb4c7 | 487 | // Request for identification |
51d87b52 BA |
488 | const me = { |
489 | // Decompose to avoid revealing email | |
490 | name: this.st.user.name, | |
491 | sid: this.st.user.sid, | |
6808d7a1 | 492 | id: this.st.user.id |
51d87b52 | 493 | }; |
6808d7a1 | 494 | this.send("identity", { data: me, target: data.from }); |
5f131484 | 495 | break; |
51d87b52 | 496 | } |
6808d7a1 | 497 | case "identity": { |
71468011 | 498 | const user = data.data; |
a041d5d8 BA |
499 | let player = this.people[user.sid]; |
500 | // player.focus is already set | |
501 | player.name = user.name; | |
502 | player.id = user.id; | |
503 | this.$forceUpdate(); //TODO: shouldn't be required | |
f9c36b2d BA |
504 | // If I multi-connect, kill current connexion if no mark (I'm older) |
505 | if (this.newConnect[user.sid]) { | |
6808d7a1 | 506 | if ( |
6808d7a1 BA |
507 | user.id > 0 && |
508 | user.id == this.st.user.id && | |
f9c36b2d BA |
509 | user.sid != this.st.user.sid && |
510 | !this.killed[this.st.user.sid] | |
6808d7a1 | 511 | ) { |
6808d7a1 | 512 | this.send("killme", { sid: this.st.user.sid }); |
51d87b52 | 513 | this.killed[this.st.user.sid] = true; |
51d87b52 | 514 | } |
f9c36b2d | 515 | delete this.newConnect[user.sid]; |
a0c41e7e | 516 | } |
dcff8e82 BA |
517 | if (!this.killed[this.st.user.sid]) { |
518 | // Ask potentially missed last state, if opponent and I play | |
519 | if ( | |
520 | !!this.game.mycolor && | |
521 | this.game.type == "live" && | |
522 | this.game.score == "*" && | |
523 | this.game.players.some(p => p.sid == user.sid) | |
524 | ) { | |
aae89b49 | 525 | this.send("asklastate", { target: user.sid }); |
e01e086d | 526 | let counter = 1; |
aae89b49 BA |
527 | this.askLastate = setInterval( |
528 | () => { | |
e01e086d BA |
529 | // Ask at most 3 times: |
530 | // if no reply after that there should be a network issue. | |
531 | if ( | |
532 | counter < 3 && | |
533 | !this.gotLastate && | |
534 | !!this.people[user.sid] | |
535 | ) { | |
aae89b49 | 536 | this.send("asklastate", { target: user.sid }); |
e01e086d BA |
537 | counter++; |
538 | } else { | |
aae89b49 | 539 | clearInterval(this.askLastate); |
e01e086d | 540 | } |
aae89b49 | 541 | }, |
e01e086d | 542 | 1500 |
aae89b49 | 543 | ); |
dcff8e82 BA |
544 | } |
545 | } | |
a0c41e7e | 546 | break; |
71468011 BA |
547 | } |
548 | case "askgame": | |
549 | // Send current (live) game if not asked by any of the players | |
6808d7a1 BA |
550 | if ( |
551 | this.game.type == "live" && | |
552 | this.game.players.every(p => p.sid != data.from[0]) | |
553 | ) { | |
71468011 BA |
554 | const myGame = { |
555 | id: this.game.id, | |
556 | fen: this.game.fen, | |
557 | players: this.game.players, | |
558 | vid: this.game.vid, | |
559 | cadence: this.game.cadence, | |
f54f4c26 | 560 | score: this.game.score |
71468011 | 561 | }; |
6808d7a1 | 562 | this.send("game", { data: myGame, target: data.from }); |
71468011 BA |
563 | } |
564 | break; | |
565 | case "askfullgame": | |
e8da204a BA |
566 | const gameToSend = Object.keys(this.game) |
567 | .filter(k => | |
568 | [ | |
569 | "id","fen","players","vid","cadence","fenStart","vname", | |
c292ebb2 | 570 | "moves","clocks","initime","score","drawOffer","rematchOffer" |
e8da204a BA |
571 | ].includes(k)) |
572 | .reduce( | |
573 | (obj, k) => { | |
574 | obj[k] = this.game[k]; | |
575 | return obj; | |
576 | }, | |
577 | {} | |
578 | ); | |
579 | this.send("fullgame", { data: gameToSend, target: data.from }); | |
71468011 BA |
580 | break; |
581 | case "fullgame": | |
582 | // Callback "roomInit" to poll clients only after game is loaded | |
f54f4c26 | 583 | this.loadVariantThenGame(data.data, this.roomInit); |
71468011 | 584 | break; |
a0c41e7e | 585 | case "asklastate": |
dcff8e82 | 586 | // Sending informative last state if I played a move or score != "*" |
584f81b9 BA |
587 | // If the game or moves aren't loaded yet, delay the sending: |
588 | if (!this.game || !this.game.moves) this.lastateAsked = true; | |
589 | else this.sendLastate(data.from); | |
c6788ecf | 590 | break; |
dcff8e82 BA |
591 | case "lastate": { |
592 | // Got opponent infos about last move | |
593 | this.gotLastate = true; | |
594 | if (!data.data.nothing) { | |
595 | this.lastate = data.data; | |
596 | if (this.game.rendered) | |
597 | // Game is rendered (Board component) | |
598 | this.processLastate(); | |
599 | // Else: will be processed when game is ready | |
600 | } | |
71468011 | 601 | break; |
dcff8e82 | 602 | } |
6808d7a1 | 603 | case "newmove": { |
dcff8e82 BA |
604 | const movePlus = data.data; |
605 | const movesCount = this.game.moves.length; | |
606 | if (movePlus.index > movesCount) { | |
607 | // This can only happen if I'm an observer and missed a move. | |
57eb158f BA |
608 | if (this.gotMoveIdx < movePlus.index) |
609 | this.gotMoveIdx = movePlus.index; | |
d6f08e56 BA |
610 | if (!this.gameIsLoading) this.askGameAgain(); |
611 | } | |
612 | else { | |
f9c36b2d | 613 | if ( |
dcff8e82 BA |
614 | movePlus.index < movesCount || |
615 | this.gotMoveIdx >= movePlus.index | |
f9c36b2d BA |
616 | ) { |
617 | // Opponent re-send but we already have the move: | |
618 | // (maybe he didn't receive our pingback...) | |
dcff8e82 | 619 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
f9c36b2d | 620 | } else { |
dcff8e82 BA |
621 | this.gotMoveIdx = movePlus.index; |
622 | const receiveMyMove = (movePlus.color == this.game.mycolor); | |
f9c36b2d BA |
623 | if (!receiveMyMove && !!this.game.mycolor) |
624 | // Notify opponent that I got the move: | |
dcff8e82 BA |
625 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
626 | if (movePlus.cancelDrawOffer) { | |
f9c36b2d BA |
627 | // Opponent refuses draw |
628 | this.drawOffer = ""; | |
629 | // NOTE for corr games: drawOffer reset by player in turn | |
630 | if ( | |
631 | this.game.type == "live" && | |
632 | !!this.game.mycolor && | |
633 | !receiveMyMove | |
634 | ) { | |
f54f4c26 | 635 | GameStorage.update(this.gameRef, { drawOffer: "" }); |
f9c36b2d BA |
636 | } |
637 | } | |
57eb158f BA |
638 | this.$refs["basegame"].play(movePlus.move, "received", null, true); |
639 | this.processMove( | |
dcff8e82 | 640 | movePlus.move, |
f9c36b2d | 641 | { |
e01e086d | 642 | clock: movePlus.clock, |
f9c36b2d BA |
643 | receiveMyMove: receiveMyMove |
644 | } | |
645 | ); | |
646 | } | |
633959bf | 647 | } |
a6088c90 | 648 | break; |
71468011 | 649 | } |
f9c36b2d BA |
650 | case "gotmove": { |
651 | this.opponentGotMove = true; | |
e01e086d BA |
652 | // Now his clock starts running: |
653 | const oppIdx = ['w','b'].indexOf(this.vr.turn); | |
654 | this.game.initime[oppIdx] = Date.now(); | |
655 | this.re_setClocks(); | |
f9c36b2d BA |
656 | break; |
657 | } | |
93d1d7a7 | 658 | case "resign": |
059228c9 BA |
659 | const score = (data.data == "b" ? "1-0" : "0-1"); |
660 | const side = (data.data == "w" ? "White" : "Black"); | |
8477e53d | 661 | this.gameOver(score, side + " surrender"); |
93d1d7a7 | 662 | break; |
93d1d7a7 | 663 | case "abort": |
8477e53d | 664 | this.gameOver("?", "Stop"); |
93d1d7a7 | 665 | break; |
2cc10cdb | 666 | case "draw": |
71468011 | 667 | this.gameOver("1/2", data.data); |
2cc10cdb BA |
668 | break; |
669 | case "drawoffer": | |
41c80bb6 BA |
670 | // NOTE: observers don't know who offered draw |
671 | this.drawOffer = "received"; | |
f54f4c26 BA |
672 | if (this.game.type == "live") { |
673 | GameStorage.update( | |
674 | this.gameRef, | |
675 | { drawOffer: V.GetOppCol(this.game.mycolor) } | |
676 | ); | |
677 | } | |
6d9f4315 | 678 | break; |
c292ebb2 BA |
679 | case "rematchoffer": |
680 | // NOTE: observers don't know who offered rematch | |
681 | this.rematchOffer = data.data ? "received" : ""; | |
f54f4c26 BA |
682 | if (this.game.type == "live") { |
683 | GameStorage.update( | |
684 | this.gameRef, | |
685 | { rematchOffer: V.GetOppCol(this.game.mycolor) } | |
686 | ); | |
687 | } | |
c292ebb2 BA |
688 | break; |
689 | case "newgame": { | |
690 | // A game started, redirect if I'm playing in | |
691 | const gameInfo = data.data; | |
584f81b9 | 692 | const gameType = this.getGameType(gameInfo); |
c292ebb2 | 693 | if ( |
584f81b9 BA |
694 | gameType == "live" && |
695 | gameInfo.players.some(p => p.sid == this.st.user.sid) | |
696 | ) { | |
697 | this.addAndGotoLiveGame(gameInfo); | |
698 | } else if ( | |
699 | gameType == "corr" && | |
0234201f | 700 | gameInfo.players.some(p => p.id == this.st.user.id) |
c292ebb2 BA |
701 | ) { |
702 | this.$router.push("/game/" + gameInfo.id); | |
703 | } else { | |
f54f4c26 | 704 | this.rematchId = gameInfo.id; |
c292ebb2 BA |
705 | document.getElementById("modalInfo").checked = true; |
706 | } | |
707 | break; | |
708 | } | |
71468011 | 709 | case "newchat": |
8be8238c | 710 | this.$refs["chatcomp"].newChat(data.data); |
71468011 | 711 | if (!document.getElementById("modalChat").checked) |
2f258c37 | 712 | document.getElementById("chatBtn").classList.add("somethingnew"); |
a6088c90 BA |
713 | break; |
714 | } | |
cdb34c93 | 715 | }, |
51d87b52 BA |
716 | socketCloseListener: function() { |
717 | this.conn = new WebSocket(this.connexionString); | |
6808d7a1 BA |
718 | this.conn.addEventListener("message", this.socketMessageListener); |
719 | this.conn.addEventListener("close", this.socketCloseListener); | |
51d87b52 | 720 | }, |
5aa14a21 | 721 | updateCorrGame: function(obj, callback) { |
aae89b49 BA |
722 | ajax( |
723 | "/games", | |
724 | "PUT", | |
725 | { | |
e57c4de4 | 726 | data: { |
f54f4c26 | 727 | gid: this.gameRef, |
e57c4de4 BA |
728 | newObj: obj |
729 | }, | |
730 | success: () => { | |
731 | if (!!callback) callback(); | |
732 | } | |
aae89b49 BA |
733 | } |
734 | ); | |
735 | }, | |
584f81b9 BA |
736 | sendLastate: function(target) { |
737 | if ( | |
738 | (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) || | |
739 | this.game.score != "*" || | |
740 | this.drawOffer == "sent" || | |
741 | this.rematchOffer == "sent" | |
742 | ) { | |
743 | // Send our "last state" informations to opponent | |
744 | const L = this.game.moves.length; | |
745 | const myIdx = ["w", "b"].indexOf(this.game.mycolor); | |
746 | const myLastate = { | |
747 | lastMove: L > 0 ? this.game.moves[L - 1] : undefined, | |
748 | clock: this.game.clocks[myIdx], | |
749 | // Since we played a move (or abort or resign), | |
750 | // only drawOffer=="sent" is possible | |
751 | drawSent: this.drawOffer == "sent", | |
752 | rematchSent: this.rematchOffer == "sent", | |
753 | score: this.game.score, | |
b83a675a | 754 | scoreMsg: this.game.scoreMsg, |
584f81b9 BA |
755 | movesCount: L, |
756 | initime: this.game.initime[1 - myIdx] //relevant only if I played | |
757 | }; | |
758 | this.send("lastate", { data: myLastate, target: target }); | |
759 | } else { | |
760 | this.send("lastate", { data: {nothing: true}, target: target }); | |
761 | } | |
762 | }, | |
760adbce BA |
763 | // lastate was received, but maybe game wasn't ready yet: |
764 | processLastate: function() { | |
765 | const data = this.lastate; | |
766 | this.lastate = undefined; //security... | |
767 | const L = this.game.moves.length; | |
6808d7a1 | 768 | if (data.movesCount > L) { |
760adbce | 769 | // Just got last move from him |
e01e086d BA |
770 | this.$refs["basegame"].play(data.lastMove, "received", null, true); |
771 | this.processMove(data.lastMove, { clock: data.clock }); | |
a0c41e7e | 772 | } |
6808d7a1 | 773 | if (data.drawSent) this.drawOffer = "received"; |
c292ebb2 | 774 | if (data.rematchSent) this.rematchOffer = "received"; |
6808d7a1 | 775 | if (data.score != "*") { |
a0c41e7e | 776 | this.drawOffer = ""; |
5aa14a21 | 777 | if (this.game.score == "*") |
a17ae317 | 778 | this.gameOver(data.score, data.scoreMsg); |
760adbce BA |
779 | } |
780 | }, | |
dcd68c41 | 781 | clickDraw: function() { |
6808d7a1 BA |
782 | if (!this.game.mycolor) return; //I'm just spectator |
783 | if (["received", "threerep"].includes(this.drawOffer)) { | |
784 | if (!confirm(this.st.tr["Accept draw?"])) return; | |
785 | const message = | |
786 | this.drawOffer == "received" | |
787 | ? "Mutual agreement" | |
788 | : "Three repetitions"; | |
789 | this.send("draw", { data: message }); | |
77c50966 | 790 | this.gameOver("1/2", message); |
6808d7a1 | 791 | } else if (this.drawOffer == "") { |
e71161fb | 792 | // No effect if drawOffer == "sent" |
9ee2826a | 793 | if (this.game.mycolor != this.vr.turn) { |
6808d7a1 | 794 | alert(this.st.tr["Draw offer only in your turn"]); |
6fba6e0c | 795 | return; |
6808d7a1 BA |
796 | } |
797 | if (!confirm(this.st.tr["Offer draw?"])) return; | |
760adbce | 798 | this.drawOffer = "sent"; |
71468011 | 799 | this.send("drawoffer"); |
aae89b49 BA |
800 | if (this.game.type == "live") { |
801 | GameStorage.update( | |
f54f4c26 | 802 | this.gameRef, |
aae89b49 BA |
803 | { drawOffer: this.game.mycolor } |
804 | ); | |
805 | } else this.updateCorrGame({ drawOffer: this.game.mycolor }); | |
a6088c90 BA |
806 | } |
807 | }, | |
584f81b9 BA |
808 | addAndGotoLiveGame: function(gameInfo, callback) { |
809 | const game = Object.assign( | |
810 | {}, | |
811 | gameInfo, | |
812 | { | |
813 | // (other) Game infos: constant | |
814 | fenStart: gameInfo.fen, | |
815 | vname: this.game.vname, | |
816 | created: Date.now(), | |
817 | // Game state (including FEN): will be updated | |
818 | moves: [], | |
819 | clocks: [-1, -1], //-1 = unstarted | |
820 | initime: [0, 0], //initialized later | |
821 | score: "*" | |
822 | } | |
823 | ); | |
824 | GameStorage.add(game, (err) => { | |
825 | // No error expected. | |
826 | if (!err) { | |
827 | if (this.st.settings.sound) | |
828 | new Audio("/sounds/newgame.flac").play().catch(() => {}); | |
585d0955 | 829 | if (!!callback) callback(); |
584f81b9 BA |
830 | this.$router.push("/game/" + gameInfo.id); |
831 | } | |
832 | }); | |
833 | }, | |
c292ebb2 BA |
834 | clickRematch: function() { |
835 | if (!this.game.mycolor) return; //I'm just spectator | |
836 | if (this.rematchOffer == "received") { | |
837 | // Start a new game! | |
838 | let gameInfo = { | |
839 | id: getRandString(), //ignored if corr | |
840 | fen: V.GenRandInitFen(this.game.randomness), | |
841 | players: this.game.players.reverse(), | |
842 | vid: this.game.vid, | |
843 | cadence: this.game.cadence | |
844 | }; | |
584f81b9 | 845 | const notifyNewGame = () => { |
f14572c4 | 846 | const oppsid = this.getOppsid(); //may be null |
584f81b9 | 847 | this.send("rnewgame", { data: gameInfo, oppsid: oppsid }); |
f14572c4 BA |
848 | // To main Hall if corr game: |
849 | if (this.game.type == "corr") | |
850 | this.send("newgame", { data: gameInfo }); | |
cafe0166 BA |
851 | // Also to MyGames page: |
852 | this.notifyMyGames("newgame", gameInfo); | |
584f81b9 BA |
853 | }; |
854 | if (this.game.type == "live") | |
855 | this.addAndGotoLiveGame(gameInfo, notifyNewGame); | |
c292ebb2 BA |
856 | else { |
857 | // corr game | |
858 | ajax( | |
859 | "/games", | |
860 | "POST", | |
861 | { | |
862 | // cid is useful to delete the challenge: | |
863 | data: { gameInfo: gameInfo }, | |
864 | success: (response) => { | |
865 | gameInfo.id = response.gameId; | |
584f81b9 | 866 | notifyNewGame(); |
c292ebb2 BA |
867 | this.$router.push("/game/" + response.gameId); |
868 | } | |
869 | } | |
870 | ); | |
871 | } | |
872 | } else if (this.rematchOffer == "") { | |
873 | this.rematchOffer = "sent"; | |
874 | this.send("rematchoffer", { data: true }); | |
875 | if (this.game.type == "live") { | |
876 | GameStorage.update( | |
f54f4c26 | 877 | this.gameRef, |
c292ebb2 BA |
878 | { rematchOffer: this.game.mycolor } |
879 | ); | |
880 | } else this.updateCorrGame({ rematchOffer: this.game.mycolor }); | |
881 | } else if (this.rematchOffer == "sent") { | |
882 | // Toggle rematch offer (on --> off) | |
883 | this.rematchOffer = ""; | |
884 | this.send("rematchoffer", { data: false }); | |
885 | if (this.game.type == "live") { | |
886 | GameStorage.update( | |
f54f4c26 | 887 | this.gameRef, |
c292ebb2 BA |
888 | { rematchOffer: '' } |
889 | ); | |
890 | } else this.updateCorrGame({ rematchOffer: 'n' }); | |
891 | } | |
892 | }, | |
7f3484bd | 893 | abortGame: function() { |
6808d7a1 | 894 | if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return; |
8477e53d | 895 | this.gameOver("?", "Stop"); |
71468011 | 896 | this.send("abort"); |
a6088c90 | 897 | }, |
6808d7a1 | 898 | resign: function() { |
77c50966 | 899 | if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"])) |
a6088c90 | 900 | return; |
6808d7a1 | 901 | this.send("resign", { data: this.game.mycolor }); |
059228c9 BA |
902 | const score = (this.game.mycolor == "w" ? "0-1" : "1-0"); |
903 | const side = (this.game.mycolor == "w" ? "White" : "Black"); | |
8477e53d | 904 | this.gameOver(score, side + " surrender"); |
a6088c90 | 905 | }, |
760adbce | 906 | loadGame: function(game, callback) { |
32f6285e BA |
907 | this.vr = new V(game.fen); |
908 | const gtype = this.getGameType(game); | |
909 | const tc = extractTime(game.cadence); | |
910 | const myIdx = game.players.findIndex(p => { | |
911 | return p.sid == this.st.user.sid || p.id == this.st.user.id; | |
912 | }); | |
913 | const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers | |
914 | if (!game.chats) game.chats = []; //live games don't have chat history | |
915 | if (gtype == "corr") { | |
916 | // NOTE: clocks in seconds, initime in milliseconds | |
917 | game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of | |
918 | game.clocks = [tc.mainTime, tc.mainTime]; | |
919 | const L = game.moves.length; | |
920 | if (game.score == "*") { | |
921 | // Set clocks + initime | |
f14572c4 | 922 | game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]; |
32f6285e BA |
923 | if (L >= 1) game.initime[L % 2] = game.moves[L-1].played; |
924 | // NOTE: game.clocks shouldn't be computed right now: | |
925 | // job will be done in re_setClocks() called soon below. | |
66d03f23 | 926 | } |
32f6285e BA |
927 | // Sort chat messages from newest to oldest |
928 | game.chats.sort((c1, c2) => { | |
929 | return c2.added - c1.added; | |
930 | }); | |
931 | if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) { | |
932 | // Did a chat message arrive after my last move? | |
933 | let dtLastMove = 0; | |
934 | if (L == 1 && myIdx == 0) | |
935 | dtLastMove = game.moves[0].played; | |
936 | else if (L >= 2) { | |
937 | if (L % 2 == 0) { | |
938 | // It's now white turn | |
939 | dtLastMove = game.moves[L-1-(1-myIdx)].played; | |
940 | } else { | |
941 | // Black turn: | |
942 | dtLastMove = game.moves[L-1-myIdx].played; | |
77c50966 BA |
943 | } |
944 | } | |
32f6285e BA |
945 | if (dtLastMove < game.chats[0].added) |
946 | document.getElementById("chatBtn").classList.add("somethingnew"); | |
947 | } | |
948 | // Now that we used idx and played, re-format moves as for live games | |
949 | game.moves = game.moves.map(m => m.squares); | |
950 | } | |
951 | if (gtype == "live" && game.clocks[0] < 0) { | |
952 | // Game is unstarted. clocks and initime are ignored until move 2 | |
953 | game.clocks = [tc.mainTime, tc.mainTime]; | |
954 | game.initime = [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER]; | |
955 | if (myIdx >= 0) { | |
956 | // I play in this live game | |
957 | GameStorage.update(game.id, { | |
958 | clocks: game.clocks, | |
959 | initime: game.initime | |
960 | }); | |
77c50966 | 961 | } |
32f6285e BA |
962 | } |
963 | // TODO: merge next 2 "if" conditions | |
964 | if (!!game.drawOffer) { | |
965 | if (game.drawOffer == "t") | |
966 | // Three repetitions | |
967 | this.drawOffer = "threerep"; | |
968 | else { | |
969 | // Draw offered by any of the players: | |
970 | if (myIdx < 0) this.drawOffer = "received"; | |
c292ebb2 BA |
971 | else { |
972 | // I play in this game: | |
973 | if ( | |
32f6285e BA |
974 | (game.drawOffer == "w" && myIdx == 0) || |
975 | (game.drawOffer == "b" && myIdx == 1) | |
c292ebb2 | 976 | ) |
32f6285e BA |
977 | this.drawOffer = "sent"; |
978 | else this.drawOffer = "received"; | |
c292ebb2 BA |
979 | } |
980 | } | |
32f6285e BA |
981 | } |
982 | if (!!game.rematchOffer) { | |
983 | if (myIdx < 0) this.rematchOffer = "received"; | |
984 | else { | |
985 | // I play in this game: | |
986 | if ( | |
987 | (game.rematchOffer == "w" && myIdx == 0) || | |
988 | (game.rematchOffer == "b" && myIdx == 1) | |
989 | ) | |
990 | this.rematchOffer = "sent"; | |
991 | else this.rematchOffer = "received"; | |
5aa14a21 | 992 | } |
32f6285e BA |
993 | } |
994 | this.repeat = {}; //reset: scan past moves' FEN: | |
995 | let repIdx = 0; | |
996 | let vr_tmp = new V(game.fenStart); | |
997 | let curTurn = "n"; | |
998 | game.moves.forEach(m => { | |
999 | playMove(m, vr_tmp); | |
1000 | const fenIdx = vr_tmp.getFen().replace(/ /g, "_"); | |
1001 | this.repeat[fenIdx] = this.repeat[fenIdx] | |
1002 | ? this.repeat[fenIdx] + 1 | |
1003 | : 1; | |
1004 | }); | |
1005 | if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep"; | |
1006 | this.game = Object.assign( | |
1007 | // NOTE: assign mycolor here, since BaseGame could also be VS computer | |
1008 | { | |
1009 | type: gtype, | |
1010 | increment: tc.increment, | |
1011 | mycolor: mycolor, | |
1012 | // opponent sid not strictly required (or available), but easier | |
1013 | // at least oppsid or oppid is available anyway: | |
1014 | oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid, | |
1015 | oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].id | |
1016 | }, | |
1017 | game | |
1018 | ); | |
1019 | this.$refs["basegame"].re_setVariables(this.game); | |
1020 | if (!this.gameIsLoading) { | |
1021 | // Initial loading: | |
1022 | this.gotMoveIdx = game.moves.length - 1; | |
1023 | // If we arrive here after 'nextGame' action, the board might be hidden | |
1024 | let boardDiv = document.querySelector(".game"); | |
1025 | if (!!boardDiv && boardDiv.style.visibility == "hidden") | |
1026 | boardDiv.style.visibility = "visible"; | |
1027 | } | |
1028 | this.re_setClocks(); | |
1029 | this.$nextTick(() => { | |
1030 | this.game.rendered = true; | |
1031 | // Did lastate arrive before game was rendered? | |
1032 | if (this.lastate) this.processLastate(); | |
1033 | }); | |
1034 | if (this.lastateAsked) { | |
1035 | this.lastateAsked = false; | |
1036 | this.sendLastate(game.oppsid); | |
1037 | } | |
1038 | if (this.gameIsLoading) { | |
1039 | this.gameIsLoading = false; | |
1040 | if (this.gotMoveIdx >= game.moves.length) | |
1041 | // Some moves arrived meanwhile... | |
1042 | this.askGameAgain(); | |
1043 | } | |
1044 | if (!!callback) callback(); | |
1045 | }, | |
f54f4c26 BA |
1046 | loadVariantThenGame: async function(game, callback) { |
1047 | await import("@/variants/" + game.vname + ".js") | |
1048 | .then((vModule) => { | |
1049 | window.V = vModule[game.vname + "Rules"]; | |
1050 | this.loadGame(game, callback); | |
1051 | }); | |
1052 | }, | |
1053 | // 3 cases for loading a game: | |
1054 | // - from indexedDB (running or completed live game I play) | |
1055 | // - from server (one correspondance game I play[ed] or not) | |
1056 | // - from remote peer (one live game I don't play, finished or not) | |
1057 | fetchGame: function(callback) { | |
1058 | if (Number.isInteger(this.gameRef) || !isNaN(parseInt(this.gameRef))) { | |
1059 | // corr games identifiers are integers | |
1060 | ajax( | |
1061 | "/games", | |
1062 | "GET", | |
1063 | { | |
1064 | data: { gid: this.gameRef }, | |
1065 | success: (res) => { | |
1066 | res.game.moves.forEach(m => { | |
1067 | m.squares = JSON.parse(m.squares); | |
1068 | }); | |
1069 | callback(res.game); | |
e57c4de4 | 1070 | } |
f54f4c26 BA |
1071 | } |
1072 | ); | |
1073 | } else | |
1074 | // Local game (or live remote) | |
1075 | GameStorage.get(this.gameRef, callback); | |
a6088c90 | 1076 | }, |
9ef63965 | 1077 | re_setClocks: function() { |
dcff8e82 | 1078 | if (this.game.moves.length < 2 || this.game.score != "*") { |
9ef63965 | 1079 | // 1st move not completed yet, or game over: freeze time |
57eb158f | 1080 | this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':')); |
9ef63965 BA |
1081 | return; |
1082 | } | |
1083 | const currentTurn = this.vr.turn; | |
8477e53d | 1084 | const currentMovesCount = this.game.moves.length; |
6808d7a1 BA |
1085 | const colorIdx = ["w", "b"].indexOf(currentTurn); |
1086 | let countdown = | |
1087 | this.game.clocks[colorIdx] - | |
1088 | (Date.now() - this.game.initime[colorIdx]) / 1000; | |
1089 | this.virtualClocks = [0, 1].map(i => { | |
1090 | const removeTime = | |
1091 | i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0; | |
57eb158f | 1092 | return ppt(this.game.clocks[i] - removeTime).split(':'); |
9ef63965 | 1093 | }); |
e01e086d BA |
1094 | this.clockUpdate = setInterval( |
1095 | () => { | |
1096 | if ( | |
1097 | countdown < 0 || | |
1098 | this.game.moves.length > currentMovesCount || | |
1099 | this.game.score != "*" | |
1100 | ) { | |
1101 | clearInterval(this.clockUpdate); | |
1102 | if (countdown < 0) | |
1103 | this.gameOver( | |
1104 | currentTurn == "w" ? "0-1" : "1-0", | |
1105 | "Time" | |
1106 | ); | |
1107 | } else | |
1108 | this.$set( | |
1109 | this.virtualClocks, | |
1110 | colorIdx, | |
1111 | ppt(Math.max(0, --countdown)).split(':') | |
6808d7a1 | 1112 | ); |
e01e086d BA |
1113 | }, |
1114 | 1000 | |
1115 | ); | |
9ef63965 | 1116 | }, |
57eb158f | 1117 | // Update variables and storage after a move: |
e71161fb | 1118 | processMove: function(move, data) { |
e5c1d0fb | 1119 | if (!data) data = {}; |
e71161fb BA |
1120 | const moveCol = this.vr.turn; |
1121 | const doProcessMove = () => { | |
1122 | const colorIdx = ["w", "b"].indexOf(moveCol); | |
1123 | const nextIdx = 1 - colorIdx; | |
dcff8e82 | 1124 | const origMovescount = this.game.moves.length; |
e01e086d | 1125 | let addTime = 0; //for live games |
f9c36b2d | 1126 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
e71161fb BA |
1127 | if (this.drawOffer == "received") |
1128 | // I refuse draw | |
1129 | this.drawOffer = ""; | |
dcff8e82 | 1130 | if (this.game.type == "live" && origMovescount >= 2) { |
e71161fb BA |
1131 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
1132 | // elapsed time is measured in milliseconds | |
1133 | addTime = this.game.increment - elapsed / 1000; | |
1134 | } | |
dce792f6 | 1135 | } |
dcff8e82 | 1136 | // Update current game object: |
e71161fb | 1137 | playMove(move, this.vr); |
e01e086d BA |
1138 | // The move is played: stop clock |
1139 | clearInterval(this.clockUpdate); | |
f54f4c26 BA |
1140 | if (!data.score) |
1141 | // Received move, score is computed in BaseGame, but maybe not yet. | |
1142 | // ==> Compute it here, although this is redundant (TODO) | |
1143 | data.score = this.vr.getCurrentScore(); | |
1144 | if (data.score != "*") this.gameOver(data.score); | |
dcff8e82 | 1145 | this.game.moves.push(move); |
e71161fb | 1146 | this.game.fen = this.vr.getFen(); |
e01e086d BA |
1147 | if (this.game.type == "live") { |
1148 | if (!!data.clock) this.game.clocks[colorIdx] = data.clock; | |
1149 | else this.game.clocks[colorIdx] += addTime; | |
8be8238c BA |
1150 | } else { |
1151 | // In corr games, just reset clock to mainTime: | |
e01e086d BA |
1152 | this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime; |
1153 | } | |
1154 | // NOTE: opponent's initime is reset after "gotmove" is received | |
1155 | if ( | |
1156 | !this.game.mycolor || | |
1157 | moveCol != this.game.mycolor || | |
1158 | !!data.receiveMyMove | |
1159 | ) { | |
1160 | this.game.initime[nextIdx] = Date.now(); | |
1161 | } | |
e71161fb | 1162 | // If repetition detected, consider that a draw offer was received: |
f9c36b2d | 1163 | const fenObj = this.vr.getFenForRepeat(); |
e01e086d BA |
1164 | this.repeat[fenObj] = |
1165 | !!this.repeat[fenObj] | |
1166 | ? this.repeat[fenObj] + 1 | |
1167 | : 1; | |
f9c36b2d | 1168 | if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep"; |
e71161fb | 1169 | else if (this.drawOffer == "threerep") this.drawOffer = ""; |
dcff8e82 BA |
1170 | if (!!this.game.mycolor && !data.receiveMyMove) { |
1171 | // NOTE: 'var' to see that variable outside this block | |
1172 | var filtered_move = getFilteredMove(move); | |
1173 | } | |
cafe0166 BA |
1174 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
1175 | // Notify turn on MyGames page: | |
1176 | this.notifyMyGames( | |
1177 | "turn", | |
1178 | { | |
f54f4c26 | 1179 | gid: this.gameRef, |
cafe0166 BA |
1180 | turn: this.vr.turn |
1181 | } | |
1182 | ); | |
1183 | } | |
aae89b49 BA |
1184 | // Since corr games are stored at only one location, update should be |
1185 | // done only by one player for each move: | |
e71161fb | 1186 | if ( |
f9c36b2d BA |
1187 | !!this.game.mycolor && |
1188 | !data.receiveMyMove && | |
e71161fb BA |
1189 | (this.game.type == "live" || moveCol == this.game.mycolor) |
1190 | ) { | |
1191 | let drawCode = ""; | |
1192 | switch (this.drawOffer) { | |
1193 | case "threerep": | |
1194 | drawCode = "t"; | |
1195 | break; | |
1196 | case "sent": | |
1197 | drawCode = this.game.mycolor; | |
1198 | break; | |
1199 | case "received": | |
1200 | drawCode = V.GetOppCol(this.game.mycolor); | |
1201 | break; | |
1202 | } | |
1203 | if (this.game.type == "corr") { | |
aae89b49 BA |
1204 | // corr: only move, fen and score |
1205 | this.updateCorrGame({ | |
e71161fb BA |
1206 | fen: this.game.fen, |
1207 | move: { | |
1208 | squares: filtered_move, | |
dcff8e82 | 1209 | idx: origMovescount |
e71161fb BA |
1210 | }, |
1211 | // Code "n" for "None" to force reset (otherwise it's ignored) | |
1212 | drawOffer: drawCode || "n" | |
1213 | }); | |
1214 | } | |
57eb158f BA |
1215 | else { |
1216 | const updateStorage = () => { | |
f54f4c26 | 1217 | GameStorage.update(this.gameRef, { |
57eb158f BA |
1218 | fen: this.game.fen, |
1219 | move: filtered_move, | |
1220 | moveIdx: origMovescount, | |
1221 | clocks: this.game.clocks, | |
1222 | initime: this.game.initime, | |
1223 | drawOffer: drawCode | |
1224 | }); | |
1225 | }; | |
1226 | // The active tab can update storage immediately | |
1227 | if (!document.hidden) updateStorage(); | |
1228 | // Small random delay otherwise | |
1229 | else setTimeout(updateStorage, 500 + 1000 * Math.random()); | |
e71161fb | 1230 | } |
e69f159d | 1231 | } |
dcff8e82 BA |
1232 | // Send move ("newmove" event) to people in the room (if our turn) |
1233 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { | |
e01e086d | 1234 | let sendMove = { |
dcff8e82 BA |
1235 | move: filtered_move, |
1236 | index: origMovescount, | |
1237 | // color is required to check if this is my move (if several tabs opened) | |
1238 | color: moveCol, | |
dcff8e82 BA |
1239 | cancelDrawOffer: this.drawOffer == "" |
1240 | }; | |
e01e086d BA |
1241 | if (this.game.type == "live") |
1242 | sendMove["clock"] = this.game.clocks[colorIdx]; | |
dcff8e82 BA |
1243 | this.opponentGotMove = false; |
1244 | this.send("newmove", {data: sendMove}); | |
1245 | // If the opponent doesn't reply gotmove soon enough, re-send move: | |
e01e086d BA |
1246 | // Do this at most 2 times, because mpore would mean network issues, |
1247 | // opponent would then be expected to disconnect/reconnect. | |
1248 | let counter = 1; | |
1249 | const currentUrl = document.location.href; | |
aae89b49 | 1250 | this.retrySendmove = setInterval( |
57eb158f | 1251 | () => { |
e01e086d BA |
1252 | if ( |
1253 | counter >= 3 || | |
1254 | this.opponentGotMove || | |
1255 | document.location.href != currentUrl //page change | |
1256 | ) { | |
aae89b49 | 1257 | clearInterval(this.retrySendmove); |
57eb158f BA |
1258 | return; |
1259 | } | |
c292ebb2 BA |
1260 | const oppsid = this.getOppsid(); |
1261 | if (!oppsid) | |
57eb158f | 1262 | // Opponent is disconnected: he'll ask last state |
aae89b49 | 1263 | clearInterval(this.retrySendmove); |
e01e086d BA |
1264 | else { |
1265 | this.send("newmove", { data: sendMove, target: oppsid }); | |
1266 | counter++; | |
1267 | } | |
57eb158f | 1268 | }, |
e01e086d | 1269 | 1500 |
57eb158f | 1270 | ); |
dcff8e82 | 1271 | } |
e01e086d BA |
1272 | else |
1273 | // Not my move or I'm an observer: just start other player's clock | |
1274 | this.re_setClocks(); | |
e71161fb | 1275 | }; |
f9c36b2d BA |
1276 | if ( |
1277 | this.game.type == "corr" && | |
1278 | moveCol == this.game.mycolor && | |
1279 | !data.receiveMyMove | |
1280 | ) { | |
a17ae317 | 1281 | let boardDiv = document.querySelector(".game"); |
5aa14a21 BA |
1282 | const afterSetScore = () => { |
1283 | doProcessMove(); | |
1284 | if (this.st.settings.gotonext && this.nextIds.length > 0) | |
1285 | this.showNextGame(); | |
1286 | else { | |
5aa14a21 | 1287 | // The board might have been hidden: |
5aa14a21 BA |
1288 | if (boardDiv.style.visibility == "hidden") |
1289 | boardDiv.style.visibility = "visible"; | |
e71161fb | 1290 | } |
5aa14a21 | 1291 | }; |
a17ae317 BA |
1292 | let el = document.querySelector("#buttonsConfirm > .acceptBtn"); |
1293 | // We may play several moves in a row: in case of, remove listener: | |
1294 | let elClone = el.cloneNode(true); | |
1295 | el.parentNode.replaceChild(elClone, el); | |
1296 | elClone.addEventListener( | |
1297 | "click", | |
1298 | () => { | |
1299 | document.getElementById("modalConfirm").checked = false; | |
1300 | if (!!data.score && data.score != "*") | |
1301 | // Set score first | |
1302 | this.gameOver(data.score, null, afterSetScore); | |
1303 | else afterSetScore(); | |
1304 | } | |
1305 | ); | |
1306 | // PlayOnBoard is enough, and more appropriate for Synchrone Chess | |
1307 | V.PlayOnBoard(this.vr.board, move); | |
1308 | const position = this.vr.getBaseFen(); | |
1309 | V.UndoOnBoard(this.vr.board, move); | |
5aa14a21 | 1310 | if (["all","byrow"].includes(V.ShowMoves)) { |
5aa14a21 BA |
1311 | this.curDiag = getDiagram({ |
1312 | position: position, | |
1313 | orientation: V.CanFlip ? this.game.mycolor : "w" | |
1314 | }); | |
f3fe29d8 BA |
1315 | document.querySelector("#confirmDiv > .card").style.width = |
1316 | boardDiv.offsetWidth + "px"; | |
5aa14a21 BA |
1317 | } else { |
1318 | // Incomplete information: just ask confirmation | |
a17ae317 | 1319 | // Hide the board, because otherwise it could reveal infos |
5aa14a21 | 1320 | boardDiv.style.visibility = "hidden"; |
a17ae317 | 1321 | this.moveNotation = getFullNotation(move); |
5aa14a21 | 1322 | } |
a17ae317 | 1323 | document.getElementById("modalConfirm").checked = true; |
6d68309a | 1324 | } |
aae89b49 | 1325 | else { |
5aa14a21 | 1326 | // Normal situation |
5aa14a21 | 1327 | if (!!data.score && data.score != "*") |
e01e086d BA |
1328 | this.gameOver(data.score, null, doProcessMove); |
1329 | else doProcessMove(); | |
aae89b49 | 1330 | } |
b4fb1612 | 1331 | }, |
5b4de147 | 1332 | cancelMove: function() { |
a17ae317 BA |
1333 | let boardDiv = document.querySelector(".game"); |
1334 | if (boardDiv.style.visibility == "hidden") | |
1335 | boardDiv.style.visibility = "visible"; | |
5b4de147 BA |
1336 | document.getElementById("modalConfirm").checked = false; |
1337 | this.$refs["basegame"].cancelLastMove(); | |
1338 | }, | |
5aa14a21 BA |
1339 | // In corr games, callback to change page only after score is set: |
1340 | gameOver: function(score, scoreMsg, callback) { | |
430a2038 | 1341 | this.game.score = score; |
5aa14a21 | 1342 | if (!scoreMsg) scoreMsg = getScoreMessage(score); |
a17ae317 | 1343 | this.game.scoreMsg = scoreMsg; |
5aa14a21 | 1344 | this.$set(this.game, "scoreMsg", scoreMsg); |
ab6f48ea | 1345 | const myIdx = this.game.players.findIndex(p => { |
0234201f | 1346 | return p.sid == this.st.user.sid || p.id == this.st.user.id; |
ab6f48ea | 1347 | }); |
6808d7a1 | 1348 | if (myIdx >= 0) { |
8477e53d | 1349 | // OK, I play in this game |
aae89b49 | 1350 | const scoreObj = { |
6808d7a1 BA |
1351 | score: score, |
1352 | scoreMsg: scoreMsg | |
aae89b49 | 1353 | }; |
5aa14a21 | 1354 | if (this.game.type == "live") { |
f54f4c26 | 1355 | GameStorage.update(this.gameRef, scoreObj); |
5aa14a21 BA |
1356 | if (!!callback) callback(); |
1357 | } | |
1358 | else this.updateCorrGame(scoreObj, callback); | |
48ab808f | 1359 | // Notify the score to main Hall. TODO: only one player (currently double send) |
6808d7a1 | 1360 | this.send("result", { gid: this.game.id, score: score }); |
cafe0166 BA |
1361 | // Also to MyGames page (TODO: doubled as well...) |
1362 | this.notifyMyGames( | |
1363 | "score", | |
1364 | { | |
f54f4c26 | 1365 | gid: this.gameRef, |
cafe0166 BA |
1366 | score: score |
1367 | } | |
1368 | ); | |
dcd68c41 | 1369 | } |
5aa14a21 | 1370 | else if (!!callback) callback(); |
6808d7a1 BA |
1371 | } |
1372 | } | |
a6088c90 BA |
1373 | }; |
1374 | </script> | |
7e1a1fe9 | 1375 | |
41c80bb6 | 1376 | <style lang="sass" scoped> |
c292ebb2 BA |
1377 | #infoDiv > .card |
1378 | padding: 15px 0 | |
1379 | max-width: 430px | |
1380 | ||
72ccbd67 | 1381 | .connected |
050ae3b5 | 1382 | background-color: lightgreen |
72ccbd67 | 1383 | |
ed06d9e9 BA |
1384 | #participants |
1385 | margin-left: 5px | |
1386 | ||
1387 | .anonymous | |
1388 | color: grey | |
1389 | font-style: italic | |
1390 | ||
ec905cbc BA |
1391 | #playersInfo > p |
1392 | margin: 0 | |
1393 | ||
430a2038 BA |
1394 | @media screen and (min-width: 768px) |
1395 | #actions | |
1396 | width: 300px | |
1397 | @media screen and (max-width: 767px) | |
1398 | .game | |
1399 | width: 100% | |
72ccbd67 | 1400 | |
430a2038 | 1401 | #actions |
cf94b843 | 1402 | display: inline-block |
1d6d7b1d | 1403 | margin: 0 |
feaf1bf7 BA |
1404 | |
1405 | button | |
1406 | display: inline-block | |
1407 | margin: 0 | |
1408 | display: inline-flex | |
1409 | img | |
1410 | height: 24px | |
1411 | display: flex | |
1412 | @media screen and (max-width: 767px) | |
1413 | height: 18px | |
a1c48034 | 1414 | |
050ae3b5 BA |
1415 | @media screen and (max-width: 767px) |
1416 | #aboveBoard | |
1417 | text-align: center | |
885d93a7 BA |
1418 | @media screen and (min-width: 768px) |
1419 | #aboveBoard | |
1420 | margin-left: 30% | |
050ae3b5 | 1421 | |
2f258c37 BA |
1422 | .variant-cadence |
1423 | padding-right: 10px | |
1424 | ||
1425 | .variant-name | |
8c5f5390 | 1426 | font-weight: bold |
77c50966 | 1427 | padding-right: 10px |
77c50966 | 1428 | |
feaf1bf7 BA |
1429 | span#nextGame |
1430 | background-color: #edda99 | |
1431 | cursor: pointer | |
1432 | display: inline-block | |
1433 | margin-right: 10px | |
1434 | ||
57eb158f | 1435 | span.name |
050ae3b5 | 1436 | font-size: 1.5rem |
57eb158f | 1437 | padding: 0 3px |
050ae3b5 | 1438 | |
57eb158f | 1439 | span.time |
050ae3b5 BA |
1440 | font-size: 2rem |
1441 | display: inline-block | |
57eb158f BA |
1442 | .time-left |
1443 | margin-left: 10px | |
1444 | .time-right | |
1445 | margin-left: 5px | |
1446 | .time-separator | |
1447 | margin-left: 5px | |
1448 | position: relative | |
1449 | top: -1px | |
1450 | ||
1451 | span.yourturn | |
1452 | color: #831B1B | |
1453 | .time-separator | |
1454 | animation: blink-animation 2s steps(3, start) infinite | |
1455 | @keyframes blink-animation | |
1456 | to | |
1457 | visibility: hidden | |
050ae3b5 BA |
1458 | |
1459 | .split-names | |
1460 | display: inline-block | |
1461 | margin: 0 15px | |
1462 | ||
5b4de147 | 1463 | #chatWrap > .card |
a1c48034 | 1464 | padding-top: 20px |
a154d45e | 1465 | max-width: 767px |
5b4de147 BA |
1466 | border: none |
1467 | ||
1468 | #confirmDiv > .card | |
1469 | max-width: 767px | |
1470 | max-height: 100% | |
cf94b843 | 1471 | |
dcd68c41 BA |
1472 | .draw-sent, .draw-sent:hover |
1473 | background-color: lightyellow | |
1474 | ||
1475 | .draw-received, .draw-received:hover | |
1476 | background-color: lightgreen | |
1477 | ||
1478 | .draw-threerep, .draw-threerep:hover | |
1479 | background-color: #e4d1fc | |
2f258c37 | 1480 | |
c292ebb2 BA |
1481 | .rematch-sent, .rematch-sent:hover |
1482 | background-color: lightyellow | |
1483 | ||
1484 | .rematch-received, .rematch-received:hover | |
1485 | background-color: lightgreen | |
1486 | ||
2f258c37 BA |
1487 | .somethingnew |
1488 | background-color: #c5fefe | |
5b4de147 BA |
1489 | |
1490 | .diagram | |
1491 | margin: 0 auto | |
5b4de147 BA |
1492 | width: 100% |
1493 | ||
1494 | #buttonsConfirm | |
1495 | margin: 0 | |
1496 | & > button > span | |
1497 | width: 100% | |
1498 | text-align: center | |
1499 | ||
1500 | button.acceptBtn | |
1501 | background-color: lightgreen | |
1502 | button.refuseBtn | |
1503 | background-color: red | |
7e1a1fe9 | 1504 | </style> |