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