| 1 | <template lang="pug"> |
| 2 | main |
| 3 | input#modalChat.modal( |
| 4 | type="checkbox" |
| 5 | @click="resetChatColor()" |
| 6 | ) |
| 7 | div#chatWrap( |
| 8 | role="dialog" |
| 9 | data-checkbox="modalChat" |
| 10 | ) |
| 11 | #chat.card |
| 12 | label.modal-close(for="modalChat") |
| 13 | #participants |
| 14 | span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }} |
| 15 | span( |
| 16 | v-for="p in Object.values(people)" |
| 17 | v-if="p.name" |
| 18 | ) |
| 19 | | {{ p.name }} |
| 20 | span.anonymous(v-if="Object.values(people).some(p => !p.name && p.id === 0)") |
| 21 | | + @nonymous |
| 22 | Chat( |
| 23 | :players="game.players" |
| 24 | :pastChats="game.chats" |
| 25 | :newChat="newChat" |
| 26 | @mychat="processChat" |
| 27 | @chatcleared="clearChat" |
| 28 | ) |
| 29 | .row |
| 30 | #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2 |
| 31 | span.variant-cadence {{ game.cadence }} |
| 32 | span.variant-name {{ game.vname }} |
| 33 | span#nextGame( |
| 34 | v-if="nextIds.length > 0" |
| 35 | @click="showNextGame()" |
| 36 | ) |
| 37 | | {{ st.tr["Next_g"] }} |
| 38 | button#chatBtn.tooltip( |
| 39 | onClick="window.doClick('modalChat')" |
| 40 | aria-label="Chat" |
| 41 | ) |
| 42 | img(src="/images/icons/chat.svg") |
| 43 | #actions(v-if="game.score=='*'") |
| 44 | button.tooltip( |
| 45 | @click="clickDraw()" |
| 46 | :class="{['draw-' + drawOffer]: true}" |
| 47 | :aria-label="st.tr['Draw']" |
| 48 | ) |
| 49 | img(src="/images/icons/draw.svg") |
| 50 | button.tooltip( |
| 51 | v-if="!!game.mycolor" |
| 52 | @click="abortGame()" |
| 53 | :aria-label="st.tr['Abort']" |
| 54 | ) |
| 55 | img(src="/images/icons/abort.svg") |
| 56 | button.tooltip( |
| 57 | v-if="!!game.mycolor" |
| 58 | @click="resign()" |
| 59 | :aria-label="st.tr['Resign']" |
| 60 | ) |
| 61 | img(src="/images/icons/resign.svg") |
| 62 | button.tooltip( |
| 63 | v-else-if="!!game.mycolor" |
| 64 | @click="rematch()" |
| 65 | :aria-label="st.tr['Rematch']" |
| 66 | ) |
| 67 | img(src="/images/icons/rematch.svg") |
| 68 | #playersInfo |
| 69 | p |
| 70 | span.name(:class="{connected: isConnected(0)}") |
| 71 | | {{ game.players[0].name || "@nonymous" }} |
| 72 | span.time( |
| 73 | v-if="game.score=='*'" |
| 74 | :class="{yourturn: !!vr && vr.turn == 'w'}" |
| 75 | ) |
| 76 | span.time-left {{ virtualClocks[0][0] }} |
| 77 | span.time-separator(v-if="!!virtualClocks[0][1]") : |
| 78 | span.time-right(v-if="!!virtualClocks[0][1]") {{ virtualClocks[0][1] }} |
| 79 | span.split-names - |
| 80 | span.name(:class="{connected: isConnected(1)}") |
| 81 | | {{ game.players[1].name || "@nonymous" }} |
| 82 | span.time( |
| 83 | v-if="game.score=='*'" |
| 84 | :class="{yourturn: !!vr && vr.turn == 'b'}" |
| 85 | ) |
| 86 | span.time-left {{ virtualClocks[1][0] }} |
| 87 | span.time-separator(v-if="!!virtualClocks[1][1]") : |
| 88 | span.time-right(v-if="!!virtualClocks[1][1]") {{ virtualClocks[1][1] }} |
| 89 | BaseGame( |
| 90 | ref="basegame" |
| 91 | :game="game" |
| 92 | @newmove="processMove" |
| 93 | @gameover="gameOver" |
| 94 | ) |
| 95 | </template> |
| 96 | |
| 97 | <script> |
| 98 | import BaseGame from "@/components/BaseGame.vue"; |
| 99 | import Chat from "@/components/Chat.vue"; |
| 100 | import { store } from "@/store"; |
| 101 | import { GameStorage } from "@/utils/gameStorage"; |
| 102 | import { ppt } from "@/utils/datetime"; |
| 103 | import { ajax } from "@/utils/ajax"; |
| 104 | import { extractTime } from "@/utils/timeControl"; |
| 105 | import { getRandString } from "@/utils/alea"; |
| 106 | import { processModalClick } from "@/utils/modalClick"; |
| 107 | import { getFullNotation } from "@/utils/notation"; |
| 108 | import { playMove, getFilteredMove } from "@/utils/playUndo"; |
| 109 | import { getScoreMessage } from "@/utils/scoring"; |
| 110 | import { ArrayFun } from "@/utils/array"; |
| 111 | import params from "@/parameters"; |
| 112 | export default { |
| 113 | name: "my-game", |
| 114 | components: { |
| 115 | BaseGame, |
| 116 | Chat |
| 117 | }, |
| 118 | // gameRef: to find the game in (potentially remote) storage |
| 119 | data: function() { |
| 120 | return { |
| 121 | st: store.state, |
| 122 | gameRef: { |
| 123 | // rid = remote (socket) ID |
| 124 | id: "", |
| 125 | rid: "" |
| 126 | }, |
| 127 | game: { |
| 128 | // Passed to BaseGame |
| 129 | players: [{ name: "" }, { name: "" }], |
| 130 | chats: [], |
| 131 | rendered: false |
| 132 | }, |
| 133 | nextIds: [], |
| 134 | virtualClocks: [[0,0], [0,0]], //initialized with true game.clocks |
| 135 | vr: null, //"variant rules" object initialized from FEN |
| 136 | drawOffer: "", |
| 137 | people: {}, //players + observers |
| 138 | onMygames: [], //opponents (or me) on "MyGames" page |
| 139 | lastate: undefined, //used if opponent send lastate before game is ready |
| 140 | repeat: {}, //detect position repetition |
| 141 | newChat: "", |
| 142 | conn: null, |
| 143 | roomInitialized: false, |
| 144 | // If newmove has wrong index: ask fullgame again: |
| 145 | askGameTime: 0, |
| 146 | gameIsLoading: false, |
| 147 | // If asklastate got no reply, ask again: |
| 148 | gotLastate: false, |
| 149 | gotMoveIdx: -1, //last move index received |
| 150 | // If newmove got no pingback, send again: |
| 151 | opponentGotMove: false, |
| 152 | connexionString: "", |
| 153 | // Related to (killing of) self multi-connects: |
| 154 | newConnect: {}, |
| 155 | killed: {} |
| 156 | }; |
| 157 | }, |
| 158 | watch: { |
| 159 | $route: function(to) { |
| 160 | this.gameRef.id = to.params["id"]; |
| 161 | this.gameRef.rid = to.query["rid"]; |
| 162 | this.loadGame(); |
| 163 | } |
| 164 | }, |
| 165 | // NOTE: some redundant code with Hall.vue (mostly related to people array) |
| 166 | created: function() { |
| 167 | // Always add myself to players' list |
| 168 | const my = this.st.user; |
| 169 | this.$set(this.people, my.sid, { id: my.id, name: my.name }); |
| 170 | this.gameRef.id = this.$route.params["id"]; |
| 171 | // rid = remote ID to find an observed live game, |
| 172 | // next = next corr games IDs to navigate faster |
| 173 | // (Both might be undefined) |
| 174 | this.gameRef.rid = this.$route.query["rid"]; |
| 175 | this.nextIds = JSON.parse(this.$route.query["next"] || "[]"); |
| 176 | // Initialize connection |
| 177 | this.connexionString = |
| 178 | params.socketUrl + |
| 179 | "/?sid=" + |
| 180 | this.st.user.sid + |
| 181 | "&tmpId=" + |
| 182 | getRandString() + |
| 183 | "&page=" + |
| 184 | encodeURIComponent(this.$route.path); |
| 185 | this.conn = new WebSocket(this.connexionString); |
| 186 | this.conn.onmessage = this.socketMessageListener; |
| 187 | this.conn.onclose = this.socketCloseListener; |
| 188 | // Socket init required before loading remote game: |
| 189 | const socketInit = callback => { |
| 190 | if (!!this.conn && this.conn.readyState == 1) |
| 191 | // 1 == OPEN state |
| 192 | callback(); |
| 193 | else |
| 194 | // Socket not ready yet (initial loading) |
| 195 | // NOTE: it's important to call callback without arguments, |
| 196 | // otherwise first arg is Websocket object and loadGame fails. |
| 197 | this.conn.onopen = () => callback(); |
| 198 | }; |
| 199 | if (!this.gameRef.rid) |
| 200 | // Game stored locally or on server |
| 201 | this.loadGame(null, () => socketInit(this.roomInit)); |
| 202 | else |
| 203 | // Game stored remotely: need socket to retrieve it |
| 204 | // NOTE: the callback "roomInit" will be lost, so we don't provide it. |
| 205 | // --> It will be given when receiving "fullgame" socket event. |
| 206 | socketInit(this.loadGame); |
| 207 | }, |
| 208 | mounted: function() { |
| 209 | document |
| 210 | .getElementById("chatWrap") |
| 211 | .addEventListener("click", processModalClick); |
| 212 | }, |
| 213 | beforeDestroy: function() { |
| 214 | this.send("disconnect"); |
| 215 | }, |
| 216 | methods: { |
| 217 | roomInit: function() { |
| 218 | if (!this.roomInitialized) { |
| 219 | // Notify the room only now that I connected, because |
| 220 | // messages might be lost otherwise (if game loading is slow) |
| 221 | this.send("connect"); |
| 222 | this.send("pollclients"); |
| 223 | // We may ask fullgame several times if some moves are lost, |
| 224 | // but room should be init only once: |
| 225 | this.roomInitialized = true; |
| 226 | } |
| 227 | }, |
| 228 | send: function(code, obj) { |
| 229 | if (!!this.conn) |
| 230 | this.conn.send(JSON.stringify(Object.assign({ code: code }, obj))); |
| 231 | }, |
| 232 | isConnected: function(index) { |
| 233 | const player = this.game.players[index]; |
| 234 | // Is it me ? |
| 235 | if (this.st.user.sid == player.sid || this.st.user.id == player.uid) |
| 236 | // Still have to check for name (because of potential multi-accounts |
| 237 | // on same browser, although this should be rare...) |
| 238 | return (!this.st.user.name || this.st.user.name == player.name); |
| 239 | // Try to find a match in people: |
| 240 | return ( |
| 241 | ( |
| 242 | player.sid && |
| 243 | Object.keys(this.people).some(sid => sid == player.sid) |
| 244 | ) |
| 245 | || |
| 246 | ( |
| 247 | player.uid && |
| 248 | Object.values(this.people).some(p => p.id == player.uid) |
| 249 | ) |
| 250 | ); |
| 251 | }, |
| 252 | resetChatColor: function() { |
| 253 | // TODO: this is called twice, once on opening an once on closing |
| 254 | document.getElementById("chatBtn").classList.remove("somethingnew"); |
| 255 | }, |
| 256 | processChat: function(chat) { |
| 257 | this.send("newchat", { data: chat }); |
| 258 | // NOTE: anonymous chats in corr games are not stored on server (TODO?) |
| 259 | if (this.game.type == "corr" && this.st.user.id > 0) |
| 260 | GameStorage.update(this.gameRef.id, { chat: chat }); |
| 261 | }, |
| 262 | clearChat: function() { |
| 263 | // Nothing more to do if game is live (chats not recorded) |
| 264 | if (this.game.type == "corr") { |
| 265 | if (!!this.game.mycolor) |
| 266 | ajax("/chats", "DELETE", {gid: this.game.id}); |
| 267 | this.$set(this.game, "chats", []); |
| 268 | } |
| 269 | }, |
| 270 | // Notify turn after a new move (to opponent and me on MyGames page) |
| 271 | notifyTurn: function(sid) { |
| 272 | const player = this.people[sid]; |
| 273 | const colorIdx = this.game.players.findIndex( |
| 274 | p => p.sid == sid || p.uid == player.id); |
| 275 | const color = ["w","b"][colorIdx]; |
| 276 | const movesCount = this.game.moves.length; |
| 277 | const yourTurn = |
| 278 | (color == "w" && movesCount % 2 == 0) || |
| 279 | (color == "b" && movesCount % 2 == 1); |
| 280 | this.send("turnchange", { target: sid, yourTurn: yourTurn }); |
| 281 | }, |
| 282 | showNextGame: function() { |
| 283 | // Did I play in current game? If not, add it to nextIds list |
| 284 | if (this.game.score == "*" && this.vr.turn == this.game.mycolor) |
| 285 | this.nextIds.unshift(this.game.id); |
| 286 | const nextGid = this.nextIds.pop(); |
| 287 | this.$router.push( |
| 288 | "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds)); |
| 289 | }, |
| 290 | rematch: function() { |
| 291 | alert("Unimplemented yet (soon :) )"); |
| 292 | // TODO: same logic as for draw, but re-click remove rematch offer (toggle) |
| 293 | }, |
| 294 | askGameAgain: function() { |
| 295 | this.gameIsLoading = true; |
| 296 | const doAskGame = () => { |
| 297 | if (!this.gameRef.rid) |
| 298 | // This is my game: just reload. |
| 299 | this.loadGame(); |
| 300 | else { |
| 301 | // Just ask fullgame again (once!), this is much simpler. |
| 302 | // If this fails, the user could just reload page :/ |
| 303 | let self = this; |
| 304 | (function askIfPeerConnected() { |
| 305 | if (!!self.people[self.gameRef.rid]) |
| 306 | self.send("askfullgame", { target: self.gameRef.rid }); |
| 307 | else setTimeout(askIfPeerConnected, 1000); |
| 308 | })(); |
| 309 | } |
| 310 | }; |
| 311 | // Delay of at least 2s between two game requests |
| 312 | const now = Date.now(); |
| 313 | const delay = Math.max(2000 - (now - this.askGameTime), 0); |
| 314 | this.askGameTime = now; |
| 315 | setTimeout(doAskGame, delay); |
| 316 | }, |
| 317 | socketMessageListener: function(msg) { |
| 318 | if (!this.conn) return; |
| 319 | const data = JSON.parse(msg.data); |
| 320 | switch (data.code) { |
| 321 | case "pollclients": |
| 322 | data.sockIds.forEach(sid => { |
| 323 | if (sid != this.st.user.sid) |
| 324 | this.send("askidentity", { target: sid }); |
| 325 | }); |
| 326 | break; |
| 327 | case "connect": |
| 328 | if (!this.people[data.from]) { |
| 329 | this.newConnect[data.from] = true; //for self multi-connects tests |
| 330 | this.send("askidentity", { target: data.from }); |
| 331 | } |
| 332 | break; |
| 333 | case "disconnect": |
| 334 | this.$delete(this.people, data.from); |
| 335 | break; |
| 336 | case "mconnect": { |
| 337 | // TODO: from MyGames page : send mconnect message with the list of gid (live and corr) |
| 338 | // Either me (another tab) or opponent |
| 339 | const sid = data.from; |
| 340 | if (!this.onMygames.some(s => s == sid)) |
| 341 | { |
| 342 | this.onMygames.push(sid); |
| 343 | this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity) |
| 344 | } |
| 345 | break; |
| 346 | if (!this.people[sid]) |
| 347 | this.send("askidentity", { target: sid }); |
| 348 | } |
| 349 | case "mdisconnect": |
| 350 | ArrayFun.remove(this.onMygames, sid => sid == data.from); |
| 351 | break; |
| 352 | case "killed": |
| 353 | // I logged in elsewhere: |
| 354 | this.conn = null; |
| 355 | alert(this.st.tr["New connexion detected: tab now offline"]); |
| 356 | break; |
| 357 | case "askidentity": { |
| 358 | // Request for identification |
| 359 | const me = { |
| 360 | // Decompose to avoid revealing email |
| 361 | name: this.st.user.name, |
| 362 | sid: this.st.user.sid, |
| 363 | id: this.st.user.id |
| 364 | }; |
| 365 | this.send("identity", { data: me, target: data.from }); |
| 366 | break; |
| 367 | } |
| 368 | case "identity": { |
| 369 | const user = data.data; |
| 370 | this.$set(this.people, user.sid, { name: user.name, id: user.id }); |
| 371 | // If I multi-connect, kill current connexion if no mark (I'm older) |
| 372 | if (this.newConnect[user.sid]) { |
| 373 | if ( |
| 374 | user.id > 0 && |
| 375 | user.id == this.st.user.id && |
| 376 | user.sid != this.st.user.sid && |
| 377 | !this.killed[this.st.user.sid] |
| 378 | ) { |
| 379 | this.send("killme", { sid: this.st.user.sid }); |
| 380 | this.killed[this.st.user.sid] = true; |
| 381 | } |
| 382 | delete this.newConnect[user.sid]; |
| 383 | } |
| 384 | if (!this.killed[this.st.user.sid]) { |
| 385 | // Ask potentially missed last state, if opponent and I play |
| 386 | if ( |
| 387 | !!this.game.mycolor && |
| 388 | this.game.type == "live" && |
| 389 | this.game.score == "*" && |
| 390 | this.game.players.some(p => p.sid == user.sid) |
| 391 | ) { |
| 392 | let self = this; |
| 393 | (function askLastate() { |
| 394 | self.send("asklastate", { target: user.sid }); |
| 395 | setTimeout( |
| 396 | () => { |
| 397 | // Ask until we got a reply (or opponent disconnect): |
| 398 | if (!self.gotLastate && !!self.people[user.sid]) |
| 399 | askLastate(); |
| 400 | }, |
| 401 | 1000 |
| 402 | ); |
| 403 | })(); |
| 404 | } |
| 405 | } |
| 406 | break; |
| 407 | } |
| 408 | case "askgame": |
| 409 | // Send current (live) game if not asked by any of the players |
| 410 | if ( |
| 411 | this.game.type == "live" && |
| 412 | this.game.players.every(p => p.sid != data.from[0]) |
| 413 | ) { |
| 414 | const myGame = { |
| 415 | id: this.game.id, |
| 416 | fen: this.game.fen, |
| 417 | players: this.game.players, |
| 418 | vid: this.game.vid, |
| 419 | cadence: this.game.cadence, |
| 420 | score: this.game.score, |
| 421 | rid: this.st.user.sid //useful in Hall if I'm an observer |
| 422 | }; |
| 423 | this.send("game", { data: myGame, target: data.from }); |
| 424 | } |
| 425 | break; |
| 426 | case "askfullgame": |
| 427 | const gameToSend = Object.keys(this.game) |
| 428 | .filter(k => |
| 429 | [ |
| 430 | "id","fen","players","vid","cadence","fenStart","vname", |
| 431 | "moves","clocks","initime","score","drawOffer" |
| 432 | ].includes(k)) |
| 433 | .reduce( |
| 434 | (obj, k) => { |
| 435 | obj[k] = this.game[k]; |
| 436 | return obj; |
| 437 | }, |
| 438 | {} |
| 439 | ); |
| 440 | this.send("fullgame", { data: gameToSend, target: data.from }); |
| 441 | break; |
| 442 | case "fullgame": |
| 443 | // Callback "roomInit" to poll clients only after game is loaded |
| 444 | this.loadGame(data.data, this.roomInit); |
| 445 | break; |
| 446 | case "asklastate": |
| 447 | // Sending informative last state if I played a move or score != "*" |
| 448 | if ( |
| 449 | (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) || |
| 450 | this.game.score != "*" || |
| 451 | this.drawOffer == "sent" |
| 452 | ) { |
| 453 | // Send our "last state" informations to opponent |
| 454 | const L = this.game.moves.length; |
| 455 | const myIdx = ["w", "b"].indexOf(this.game.mycolor); |
| 456 | const myLastate = { |
| 457 | lastMove: L > 0 ? this.game.moves[L - 1] : undefined, |
| 458 | addTime: L > 0 ? this.game.addTimes[L - 1] : undefined, |
| 459 | // Since we played a move (or abort or resign), |
| 460 | // only drawOffer=="sent" is possible |
| 461 | drawSent: this.drawOffer == "sent", |
| 462 | score: this.game.score, |
| 463 | movesCount: L, |
| 464 | initime: this.game.initime[1 - myIdx] //relevant only if I played |
| 465 | }; |
| 466 | this.send("lastate", { data: myLastate, target: data.from }); |
| 467 | } else { |
| 468 | this.send("lastate", { data: {nothing: true}, target: data.from }); |
| 469 | } |
| 470 | break; |
| 471 | case "lastate": { |
| 472 | // Got opponent infos about last move |
| 473 | this.gotLastate = true; |
| 474 | if (!data.data.nothing) { |
| 475 | this.lastate = data.data; |
| 476 | if (this.game.rendered) |
| 477 | // Game is rendered (Board component) |
| 478 | this.processLastate(); |
| 479 | // Else: will be processed when game is ready |
| 480 | } |
| 481 | break; |
| 482 | } |
| 483 | case "newmove": { |
| 484 | const movePlus = data.data; |
| 485 | const movesCount = this.game.moves.length; |
| 486 | if (movePlus.index > movesCount) { |
| 487 | // This can only happen if I'm an observer and missed a move. |
| 488 | if (this.gotMoveIdx < movePlus.index) |
| 489 | this.gotMoveIdx = movePlus.index; |
| 490 | if (!this.gameIsLoading) this.askGameAgain(); |
| 491 | } |
| 492 | else { |
| 493 | if ( |
| 494 | movePlus.index < movesCount || |
| 495 | this.gotMoveIdx >= movePlus.index |
| 496 | ) { |
| 497 | // Opponent re-send but we already have the move: |
| 498 | // (maybe he didn't receive our pingback...) |
| 499 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
| 500 | } else { |
| 501 | this.gotMoveIdx = movePlus.index; |
| 502 | const receiveMyMove = (movePlus.color == this.game.mycolor); |
| 503 | if (!receiveMyMove && !!this.game.mycolor) |
| 504 | // Notify opponent that I got the move: |
| 505 | this.send("gotmove", {data: movePlus.index, target: data.from}); |
| 506 | if (movePlus.cancelDrawOffer) { |
| 507 | // Opponent refuses draw |
| 508 | this.drawOffer = ""; |
| 509 | // NOTE for corr games: drawOffer reset by player in turn |
| 510 | if ( |
| 511 | this.game.type == "live" && |
| 512 | !!this.game.mycolor && |
| 513 | !receiveMyMove |
| 514 | ) { |
| 515 | GameStorage.update(this.gameRef.id, { drawOffer: "" }); |
| 516 | } |
| 517 | } |
| 518 | this.$refs["basegame"].play(movePlus.move, "received", null, true); |
| 519 | this.processMove( |
| 520 | movePlus.move, |
| 521 | { |
| 522 | addTime: movePlus.addTime, |
| 523 | receiveMyMove: receiveMyMove |
| 524 | } |
| 525 | ); |
| 526 | } |
| 527 | } |
| 528 | break; |
| 529 | } |
| 530 | case "gotmove": { |
| 531 | this.opponentGotMove = true; |
| 532 | break; |
| 533 | } |
| 534 | case "resign": |
| 535 | const score = data.side == "b" ? "1-0" : "0-1"; |
| 536 | const side = data.side == "w" ? "White" : "Black"; |
| 537 | this.gameOver(score, side + " surrender"); |
| 538 | break; |
| 539 | case "abort": |
| 540 | this.gameOver("?", "Stop"); |
| 541 | break; |
| 542 | case "draw": |
| 543 | this.gameOver("1/2", data.data); |
| 544 | break; |
| 545 | case "drawoffer": |
| 546 | // NOTE: observers don't know who offered draw |
| 547 | this.drawOffer = "received"; |
| 548 | break; |
| 549 | case "newchat": |
| 550 | this.newChat = data.data; |
| 551 | if (!document.getElementById("modalChat").checked) |
| 552 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 553 | break; |
| 554 | } |
| 555 | }, |
| 556 | socketCloseListener: function() { |
| 557 | this.conn = new WebSocket(this.connexionString); |
| 558 | this.conn.addEventListener("message", this.socketMessageListener); |
| 559 | this.conn.addEventListener("close", this.socketCloseListener); |
| 560 | }, |
| 561 | // lastate was received, but maybe game wasn't ready yet: |
| 562 | processLastate: function() { |
| 563 | const data = this.lastate; |
| 564 | this.lastate = undefined; //security... |
| 565 | const L = this.game.moves.length; |
| 566 | if (data.movesCount > L) { |
| 567 | // Just got last move from him |
| 568 | this.$refs["basegame"].play( |
| 569 | data.lastMove, |
| 570 | "received", |
| 571 | null, |
| 572 | {addTime: data.addTime, initime: data.initime} |
| 573 | ); |
| 574 | } |
| 575 | if (data.drawSent) this.drawOffer = "received"; |
| 576 | if (data.score != "*") { |
| 577 | this.drawOffer = ""; |
| 578 | if (this.game.score == "*") this.gameOver(data.score); |
| 579 | } |
| 580 | }, |
| 581 | clickDraw: function() { |
| 582 | if (!this.game.mycolor) return; //I'm just spectator |
| 583 | if (["received", "threerep"].includes(this.drawOffer)) { |
| 584 | if (!confirm(this.st.tr["Accept draw?"])) return; |
| 585 | const message = |
| 586 | this.drawOffer == "received" |
| 587 | ? "Mutual agreement" |
| 588 | : "Three repetitions"; |
| 589 | this.send("draw", { data: message }); |
| 590 | this.gameOver("1/2", message); |
| 591 | } else if (this.drawOffer == "") { |
| 592 | // No effect if drawOffer == "sent" |
| 593 | if (this.game.mycolor != this.vr.turn) { |
| 594 | alert(this.st.tr["Draw offer only in your turn"]); |
| 595 | return; |
| 596 | } |
| 597 | if (!confirm(this.st.tr["Offer draw?"])) return; |
| 598 | this.drawOffer = "sent"; |
| 599 | this.send("drawoffer"); |
| 600 | GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor }); |
| 601 | } |
| 602 | }, |
| 603 | abortGame: function() { |
| 604 | if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return; |
| 605 | this.gameOver("?", "Stop"); |
| 606 | this.send("abort"); |
| 607 | }, |
| 608 | resign: function() { |
| 609 | if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"])) |
| 610 | return; |
| 611 | this.send("resign", { data: this.game.mycolor }); |
| 612 | const score = this.game.mycolor == "w" ? "0-1" : "1-0"; |
| 613 | const side = this.game.mycolor == "w" ? "White" : "Black"; |
| 614 | this.gameOver(score, side + " surrender"); |
| 615 | }, |
| 616 | // 3 cases for loading a game: |
| 617 | // - from indexedDB (running or completed live game I play) |
| 618 | // - from server (one correspondance game I play[ed] or not) |
| 619 | // - from remote peer (one live game I don't play, finished or not) |
| 620 | loadGame: function(game, callback) { |
| 621 | const afterRetrieval = async game => { |
| 622 | const vModule = await import("@/variants/" + game.vname + ".js"); |
| 623 | window.V = vModule.VariantRules; |
| 624 | this.vr = new V(game.fen); |
| 625 | const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live"; |
| 626 | const tc = extractTime(game.cadence); |
| 627 | const myIdx = game.players.findIndex(p => { |
| 628 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 629 | }); |
| 630 | const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers |
| 631 | if (!game.chats) game.chats = []; //live games don't have chat history |
| 632 | if (gtype == "corr") { |
| 633 | if (game.players[0].color == "b") { |
| 634 | // Adopt the same convention for live and corr games: [0] = white |
| 635 | [game.players[0], game.players[1]] = [ |
| 636 | game.players[1], |
| 637 | game.players[0] |
| 638 | ]; |
| 639 | } |
| 640 | // NOTE: clocks in seconds, initime in milliseconds |
| 641 | game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of |
| 642 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 643 | const L = game.moves.length; |
| 644 | if (game.score == "*") { |
| 645 | // Set clocks + initime |
| 646 | game.initime = [0, 0]; |
| 647 | if (L >= 1) { |
| 648 | const gameLastupdate = game.moves[L-1].played; |
| 649 | game.initime[L % 2] = gameLastupdate; |
| 650 | if (L >= 2) { |
| 651 | game.clocks[L % 2] = |
| 652 | tc.mainTime - (Date.now() - gameLastupdate) / 1000; |
| 653 | } |
| 654 | } |
| 655 | } |
| 656 | // Sort chat messages from newest to oldest |
| 657 | game.chats.sort((c1, c2) => { |
| 658 | return c2.added - c1.added; |
| 659 | }); |
| 660 | if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) { |
| 661 | // Did a chat message arrive after my last move? |
| 662 | let dtLastMove = 0; |
| 663 | if (L == 1 && myIdx == 0) |
| 664 | dtLastMove = game.moves[0].played; |
| 665 | else if (L >= 2) { |
| 666 | if (L % 2 == 0) { |
| 667 | // It's now white turn |
| 668 | dtLastMove = game.moves[L-1-(1-myIdx)].played; |
| 669 | } else { |
| 670 | // Black turn: |
| 671 | dtLastMove = game.moves[L-1-myIdx].played; |
| 672 | } |
| 673 | } |
| 674 | if (dtLastMove < game.chats[0].added) |
| 675 | document.getElementById("chatBtn").classList.add("somethingnew"); |
| 676 | } |
| 677 | // Now that we used idx and played, re-format moves as for live games |
| 678 | game.moves = game.moves.map(m => m.squares); |
| 679 | } |
| 680 | if (gtype == "live" && game.clocks[0] < 0) { |
| 681 | // Game is unstarted |
| 682 | game.clocks = [tc.mainTime, tc.mainTime]; |
| 683 | if (game.score == "*") { |
| 684 | game.initime[0] = Date.now(); |
| 685 | if (myIdx >= 0) { |
| 686 | // I play in this live game; corr games don't have clocks+initime |
| 687 | GameStorage.update(game.id, { |
| 688 | clocks: game.clocks, |
| 689 | initime: game.initime |
| 690 | }); |
| 691 | } |
| 692 | } |
| 693 | } |
| 694 | if (!!game.drawOffer) { |
| 695 | if (game.drawOffer == "t") |
| 696 | // Three repetitions |
| 697 | this.drawOffer = "threerep"; |
| 698 | else { |
| 699 | // Draw offered by any of the players: |
| 700 | if (myIdx < 0) this.drawOffer = "received"; |
| 701 | else { |
| 702 | // I play in this game: |
| 703 | if ( |
| 704 | (game.drawOffer == "w" && myIdx == 0) || |
| 705 | (game.drawOffer == "b" && myIdx == 1) |
| 706 | ) |
| 707 | this.drawOffer = "sent"; |
| 708 | else this.drawOffer = "received"; |
| 709 | } |
| 710 | } |
| 711 | } |
| 712 | this.repeat = {}; //reset: scan past moves' FEN: |
| 713 | let repIdx = 0; |
| 714 | let vr_tmp = new V(game.fenStart); |
| 715 | let curTurn = "n"; |
| 716 | game.moves.forEach(m => { |
| 717 | playMove(m, vr_tmp); |
| 718 | const fenIdx = vr_tmp.getFen().replace(/ /g, "_"); |
| 719 | this.repeat[fenIdx] = this.repeat[fenIdx] |
| 720 | ? this.repeat[fenIdx] + 1 |
| 721 | : 1; |
| 722 | }); |
| 723 | if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep"; |
| 724 | this.game = Object.assign( |
| 725 | // NOTE: assign mycolor here, since BaseGame could also be VS computer |
| 726 | { |
| 727 | type: gtype, |
| 728 | increment: tc.increment, |
| 729 | mycolor: mycolor, |
| 730 | // opponent sid not strictly required (or available), but easier |
| 731 | // at least oppsid or oppid is available anyway: |
| 732 | oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid, |
| 733 | oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid, |
| 734 | addTimes: [], //used for live games |
| 735 | }, |
| 736 | game, |
| 737 | ); |
| 738 | if (this.gameIsLoading) |
| 739 | // Re-load game because we missed some moves: |
| 740 | // artificially reset BaseGame (required if moves arrived in wrong order) |
| 741 | this.$refs["basegame"].re_setVariables(); |
| 742 | this.re_setClocks(); |
| 743 | this.$nextTick(() => { |
| 744 | this.game.rendered = true; |
| 745 | // Did lastate arrive before game was rendered? |
| 746 | if (this.lastate) this.processLastate(); |
| 747 | }); |
| 748 | if (this.gameIsLoading) { |
| 749 | this.gameIsLoading = false; |
| 750 | if (this.gotMoveIdx >= game.moves.length) |
| 751 | // Some moves arrived meanwhile... |
| 752 | this.askGameAgain(); |
| 753 | } |
| 754 | if (!!callback) callback(); |
| 755 | }; |
| 756 | if (!!game) { |
| 757 | afterRetrieval(game); |
| 758 | return; |
| 759 | } |
| 760 | if (this.gameRef.rid) { |
| 761 | // Remote live game: forgetting about callback func... (TODO: design) |
| 762 | this.send("askfullgame", { target: this.gameRef.rid }); |
| 763 | } else { |
| 764 | // Local or corr game |
| 765 | // NOTE: afterRetrieval() is never called if game not found |
| 766 | GameStorage.get(this.gameRef.id, afterRetrieval); |
| 767 | } |
| 768 | }, |
| 769 | re_setClocks: function() { |
| 770 | if (this.game.moves.length < 2 || this.game.score != "*") { |
| 771 | // 1st move not completed yet, or game over: freeze time |
| 772 | this.virtualClocks = this.game.clocks.map(s => ppt(s).split(':')); |
| 773 | return; |
| 774 | } |
| 775 | const currentTurn = this.vr.turn; |
| 776 | const currentMovesCount = this.game.moves.length; |
| 777 | const colorIdx = ["w", "b"].indexOf(currentTurn); |
| 778 | let countdown = |
| 779 | this.game.clocks[colorIdx] - |
| 780 | (Date.now() - this.game.initime[colorIdx]) / 1000; |
| 781 | this.virtualClocks = [0, 1].map(i => { |
| 782 | const removeTime = |
| 783 | i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0; |
| 784 | return ppt(this.game.clocks[i] - removeTime).split(':'); |
| 785 | }); |
| 786 | let clockUpdate = setInterval(() => { |
| 787 | if ( |
| 788 | countdown < 0 || |
| 789 | this.game.moves.length > currentMovesCount || |
| 790 | this.game.score != "*" |
| 791 | ) { |
| 792 | clearInterval(clockUpdate); |
| 793 | if (countdown < 0) |
| 794 | this.gameOver( |
| 795 | currentTurn == "w" ? "0-1" : "1-0", |
| 796 | "Time" |
| 797 | ); |
| 798 | } else |
| 799 | this.$set( |
| 800 | this.virtualClocks, |
| 801 | colorIdx, |
| 802 | ppt(Math.max(0, --countdown)).split(':') |
| 803 | ); |
| 804 | }, 1000); |
| 805 | }, |
| 806 | // Update variables and storage after a move: |
| 807 | processMove: function(move, data) { |
| 808 | if (!data) data = {}; |
| 809 | const moveCol = this.vr.turn; |
| 810 | const doProcessMove = () => { |
| 811 | const colorIdx = ["w", "b"].indexOf(moveCol); |
| 812 | const nextIdx = 1 - colorIdx; |
| 813 | const origMovescount = this.game.moves.length; |
| 814 | let addTime = |
| 815 | this.game.type == "live" |
| 816 | ? (data.addTime || 0) |
| 817 | : undefined; |
| 818 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
| 819 | if (this.drawOffer == "received") |
| 820 | // I refuse draw |
| 821 | this.drawOffer = ""; |
| 822 | if (this.game.type == "live" && origMovescount >= 2) { |
| 823 | const elapsed = Date.now() - this.game.initime[colorIdx]; |
| 824 | // elapsed time is measured in milliseconds |
| 825 | addTime = this.game.increment - elapsed / 1000; |
| 826 | } |
| 827 | } |
| 828 | // Update current game object: |
| 829 | playMove(move, this.vr); |
| 830 | // TODO: notifyTurn: "changeturn" message |
| 831 | this.game.moves.push(move); |
| 832 | // (add)Time indication: useful in case of lastate infos requested |
| 833 | if (this.game.type == "live") |
| 834 | this.game.addTimes.push(addTime); |
| 835 | this.game.fen = this.vr.getFen(); |
| 836 | if (this.game.type == "live") this.game.clocks[colorIdx] += addTime; |
| 837 | // In corr games, just reset clock to mainTime: |
| 838 | else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime; |
| 839 | // data.initime is set only when I receive a "lastate" move from opponent |
| 840 | this.game.initime[nextIdx] = data.initime || Date.now(); |
| 841 | this.re_setClocks(); |
| 842 | // If repetition detected, consider that a draw offer was received: |
| 843 | const fenObj = this.vr.getFenForRepeat(); |
| 844 | this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1; |
| 845 | if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep"; |
| 846 | else if (this.drawOffer == "threerep") this.drawOffer = ""; |
| 847 | // Since corr games are stored at only one location, update should be |
| 848 | // done only by one player for each move: |
| 849 | if (!!this.game.mycolor && !data.receiveMyMove) { |
| 850 | // NOTE: 'var' to see that variable outside this block |
| 851 | var filtered_move = getFilteredMove(move); |
| 852 | } |
| 853 | if ( |
| 854 | !!this.game.mycolor && |
| 855 | !data.receiveMyMove && |
| 856 | (this.game.type == "live" || moveCol == this.game.mycolor) |
| 857 | ) { |
| 858 | let drawCode = ""; |
| 859 | switch (this.drawOffer) { |
| 860 | case "threerep": |
| 861 | drawCode = "t"; |
| 862 | break; |
| 863 | case "sent": |
| 864 | drawCode = this.game.mycolor; |
| 865 | break; |
| 866 | case "received": |
| 867 | drawCode = V.GetOppCol(this.game.mycolor); |
| 868 | break; |
| 869 | } |
| 870 | if (this.game.type == "corr") { |
| 871 | GameStorage.update(this.gameRef.id, { |
| 872 | fen: this.game.fen, |
| 873 | move: { |
| 874 | squares: filtered_move, |
| 875 | played: Date.now(), |
| 876 | idx: origMovescount |
| 877 | }, |
| 878 | // Code "n" for "None" to force reset (otherwise it's ignored) |
| 879 | drawOffer: drawCode || "n" |
| 880 | }); |
| 881 | } |
| 882 | else { |
| 883 | const updateStorage = () => { |
| 884 | GameStorage.update(this.gameRef.id, { |
| 885 | fen: this.game.fen, |
| 886 | move: filtered_move, |
| 887 | moveIdx: origMovescount, |
| 888 | clocks: this.game.clocks, |
| 889 | initime: this.game.initime, |
| 890 | drawOffer: drawCode |
| 891 | }); |
| 892 | }; |
| 893 | // The active tab can update storage immediately |
| 894 | if (!document.hidden) updateStorage(); |
| 895 | // Small random delay otherwise |
| 896 | else setTimeout(updateStorage, 500 + 1000 * Math.random()); |
| 897 | } |
| 898 | } |
| 899 | // Send move ("newmove" event) to people in the room (if our turn) |
| 900 | if (moveCol == this.game.mycolor && !data.receiveMyMove) { |
| 901 | const sendMove = { |
| 902 | move: filtered_move, |
| 903 | index: origMovescount, |
| 904 | // color is required to check if this is my move (if several tabs opened) |
| 905 | color: moveCol, |
| 906 | addTime: addTime, //undefined for corr games |
| 907 | cancelDrawOffer: this.drawOffer == "" |
| 908 | }; |
| 909 | this.opponentGotMove = false; |
| 910 | this.send("newmove", {data: sendMove}); |
| 911 | // If the opponent doesn't reply gotmove soon enough, re-send move: |
| 912 | let retrySendmove = setInterval( |
| 913 | () => { |
| 914 | if (this.opponentGotMove) { |
| 915 | clearInterval(retrySendmove); |
| 916 | return; |
| 917 | } |
| 918 | let oppsid = this.game.players[nextIdx].sid; |
| 919 | if (!oppsid) { |
| 920 | oppsid = Object.keys(this.people).find( |
| 921 | sid => this.people[sid].id == this.game.players[nextIdx].uid |
| 922 | ); |
| 923 | } |
| 924 | if (!oppsid || !this.people[oppsid]) |
| 925 | // Opponent is disconnected: he'll ask last state |
| 926 | clearInterval(retrySendmove); |
| 927 | else this.send("newmove", {data: sendMove, target: oppsid}); |
| 928 | }, |
| 929 | 1000 |
| 930 | ); |
| 931 | } |
| 932 | }; |
| 933 | if ( |
| 934 | this.game.type == "corr" && |
| 935 | moveCol == this.game.mycolor && |
| 936 | !data.receiveMyMove |
| 937 | ) { |
| 938 | setTimeout(() => { |
| 939 | // TODO: remplacer cette confirm box par qqch de plus discret |
| 940 | // (et de même pour challenge accepté / refusé) |
| 941 | if ( |
| 942 | !confirm( |
| 943 | this.st.tr["Move played:"] + |
| 944 | " " + |
| 945 | getFullNotation(move) + |
| 946 | "\n" + |
| 947 | this.st.tr["Are you sure?"] |
| 948 | ) |
| 949 | ) { |
| 950 | this.$refs["basegame"].cancelLastMove(); |
| 951 | return; |
| 952 | } |
| 953 | doProcessMove(); |
| 954 | // Let small time to finish drawing current move attempt: |
| 955 | }, 500); |
| 956 | } |
| 957 | else doProcessMove(); |
| 958 | }, |
| 959 | gameOver: function(score, scoreMsg) { |
| 960 | this.game.score = score; |
| 961 | this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score)); |
| 962 | const myIdx = this.game.players.findIndex(p => { |
| 963 | return p.sid == this.st.user.sid || p.uid == this.st.user.id; |
| 964 | }); |
| 965 | if (myIdx >= 0) { |
| 966 | // OK, I play in this game |
| 967 | GameStorage.update(this.gameRef.id, { |
| 968 | score: score, |
| 969 | scoreMsg: scoreMsg |
| 970 | }); |
| 971 | // Notify the score to main Hall. TODO: only one player (currently double send) |
| 972 | this.send("result", { gid: this.game.id, score: score }); |
| 973 | } |
| 974 | } |
| 975 | } |
| 976 | }; |
| 977 | </script> |
| 978 | |
| 979 | <style lang="sass" scoped> |
| 980 | .connected |
| 981 | background-color: lightgreen |
| 982 | |
| 983 | #participants |
| 984 | margin-left: 5px |
| 985 | |
| 986 | .anonymous |
| 987 | color: grey |
| 988 | font-style: italic |
| 989 | |
| 990 | #playersInfo > p |
| 991 | margin: 0 |
| 992 | |
| 993 | @media screen and (min-width: 768px) |
| 994 | #actions |
| 995 | width: 300px |
| 996 | @media screen and (max-width: 767px) |
| 997 | .game |
| 998 | width: 100% |
| 999 | |
| 1000 | #actions |
| 1001 | display: inline-block |
| 1002 | margin: 0 |
| 1003 | |
| 1004 | button |
| 1005 | display: inline-block |
| 1006 | margin: 0 |
| 1007 | display: inline-flex |
| 1008 | img |
| 1009 | height: 24px |
| 1010 | display: flex |
| 1011 | @media screen and (max-width: 767px) |
| 1012 | height: 18px |
| 1013 | |
| 1014 | @media screen and (max-width: 767px) |
| 1015 | #aboveBoard |
| 1016 | text-align: center |
| 1017 | @media screen and (min-width: 768px) |
| 1018 | #aboveBoard |
| 1019 | margin-left: 30% |
| 1020 | |
| 1021 | .variant-cadence |
| 1022 | padding-right: 10px |
| 1023 | |
| 1024 | .variant-name |
| 1025 | font-weight: bold |
| 1026 | padding-right: 10px |
| 1027 | |
| 1028 | span#nextGame |
| 1029 | background-color: #edda99 |
| 1030 | cursor: pointer |
| 1031 | display: inline-block |
| 1032 | margin-right: 10px |
| 1033 | |
| 1034 | span.name |
| 1035 | font-size: 1.5rem |
| 1036 | padding: 0 3px |
| 1037 | |
| 1038 | span.time |
| 1039 | font-size: 2rem |
| 1040 | display: inline-block |
| 1041 | .time-left |
| 1042 | margin-left: 10px |
| 1043 | .time-right |
| 1044 | margin-left: 5px |
| 1045 | .time-separator |
| 1046 | margin-left: 5px |
| 1047 | position: relative |
| 1048 | top: -1px |
| 1049 | |
| 1050 | span.yourturn |
| 1051 | color: #831B1B |
| 1052 | .time-separator |
| 1053 | animation: blink-animation 2s steps(3, start) infinite |
| 1054 | @keyframes blink-animation |
| 1055 | to |
| 1056 | visibility: hidden |
| 1057 | |
| 1058 | .split-names |
| 1059 | display: inline-block |
| 1060 | margin: 0 15px |
| 1061 | |
| 1062 | #chat |
| 1063 | padding-top: 20px |
| 1064 | max-width: 767px |
| 1065 | border: none; |
| 1066 | |
| 1067 | .draw-sent, .draw-sent:hover |
| 1068 | background-color: lightyellow |
| 1069 | |
| 1070 | .draw-received, .draw-received:hover |
| 1071 | background-color: lightgreen |
| 1072 | |
| 1073 | .draw-threerep, .draw-threerep:hover |
| 1074 | background-color: #e4d1fc |
| 1075 | |
| 1076 | .somethingnew |
| 1077 | background-color: #c5fefe |
| 1078 | </style> |