| 1 | // TODO: envoyer juste "light move", sans FEN ni notation ...etc |
| 2 | // TODO: also "observers" prop, we should send moves to them too (in a web worker ? webRTC ?) |
| 3 | // Game logic on a variant page: 3 modes, analyze, computer or human |
| 4 | Vue.component('my-game', { |
| 5 | // gameId: to find the game in storage (assumption: it exists) |
| 6 | // fen: to start from a FEN without identifiers (analyze mode) |
| 7 | props: ["conn","gameId","fen","mode","allowChat","allowMovelist"], |
| 8 | data: function() { |
| 9 | return { |
| 10 | oppConnected: false, //TODO? |
| 11 | // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always |
| 12 | sound: parseInt(localStorage["sound"] || "2"), |
| 13 | // Web worker to play computer moves without freezing interface: |
| 14 | compWorker: new Worker('/javascripts/playCompMove.js'), |
| 15 | timeStart: undefined, //time when computer starts thinking |
| 16 | vr: null, //VariantRules object, describing the game state + rules |
| 17 | endgameMessage: "", |
| 18 | orientation: "w", |
| 19 | |
| 20 | // if oppid == "computer" then mode = "computer" (otherwise human) |
| 21 | oppid: "", //opponent ID in case of HH game |
| 22 | score: "*", //'*' means 'unfinished' |
| 23 | // userColor: given by gameId, or fen (if no game Id) |
| 24 | mycolor: "w", |
| 25 | fenStart: "", |
| 26 | moves: [], //TODO: initialize if gameId is defined... |
| 27 | cursor: 0, |
| 28 | lastMove: null, |
| 29 | }; |
| 30 | }, |
| 31 | watch: { |
| 32 | fen: function(newFen) { |
| 33 | this.vr = new VariantRules(newFen); |
| 34 | }, |
| 35 | gameId: function() { |
| 36 | this.loadGame(); |
| 37 | }, |
| 38 | }, |
| 39 | computed: { |
| 40 | showChat: function() { |
| 41 | return this.allowChat && this.mode=='human' && this.score != '*'; |
| 42 | }, |
| 43 | showMoves: function() { |
| 44 | return true; |
| 45 | return this.allowMovelist && window.innerWidth >= 768; |
| 46 | }, |
| 47 | showFen: function() { |
| 48 | return variant.name != "Dark" || this.score != "*"; |
| 49 | }, |
| 50 | }, |
| 51 | // Modal end of game, and then sub-components |
| 52 | // TODO: provide chat parameters (connection, players ID...) |
| 53 | // TODO: controls: abort, clear, resign, draw (avec confirm box) |
| 54 | template: ` |
| 55 | <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2"> |
| 56 | <input id="modal-eog" type="checkbox" class="modal"/> |
| 57 | <div role="dialog" aria-labelledby="eogMessage"> |
| 58 | <div class="card smallpad small-modal text-center"> |
| 59 | <label for="modal-eog" class="modal-close"> |
| 60 | </label> |
| 61 | <h3 id="eogMessage" class="section"> |
| 62 | {{ endgameMessage }} |
| 63 | </h3> |
| 64 | </div> |
| 65 | </div> |
| 66 | <my-chat v-if="showChat"> |
| 67 | </my-chat> |
| 68 | <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play"> |
| 69 | </my-board> |
| 70 | <div class="button-group"> |
| 71 | <button @click="() => play()">Play</button> |
| 72 | <button @click="() => undo()">Undo</button> |
| 73 | <button @click="flip">Flip</button> |
| 74 | <button @click="gotoBegin">GotoBegin</button> |
| 75 | <button @click="gotoEnd">GotoEnd</button> |
| 76 | </div> |
| 77 | <div v-if="showFen && !!vr" id="fen-div" class="section-content"> |
| 78 | <p id="fen-string" class="text-center"> |
| 79 | {{ vr.getFen() }} |
| 80 | </p> |
| 81 | </div> |
| 82 | <div id="pgn-div" class="section-content"> |
| 83 | <a id="download" href="#"> |
| 84 | </a> |
| 85 | <button id="downloadBtn" @click="download"> |
| 86 | {{ translate("Download PGN") }} |
| 87 | </button> |
| 88 | </div> |
| 89 | <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove"> |
| 90 | </my-move-list> |
| 91 | </div> |
| 92 | `, |
| 93 | created: function() { |
| 94 | if (!!this.gameId) |
| 95 | this.loadGame(); |
| 96 | else if (!!this.fen) |
| 97 | { |
| 98 | this.vr = new VariantRules(this.fen); |
| 99 | this.fenStart = this.fen; |
| 100 | } |
| 101 | // TODO: after game, archive in indexedDB |
| 102 | // TODO: this events listener is central. Refactor ? How ? |
| 103 | const socketMessageListener = msg => { |
| 104 | const data = JSON.parse(msg.data); |
| 105 | let L = undefined; |
| 106 | switch (data.code) |
| 107 | { |
| 108 | case "newmove": //..he played! |
| 109 | this.play(data.move, (variant.name!="Dark" ? "animate" : null)); |
| 110 | break; |
| 111 | case "pong": //received if we sent a ping (game still alive on our side) |
| 112 | if (this.gameId != data.gameId) |
| 113 | break; //games IDs don't match: definitely over... |
| 114 | this.oppConnected = true; |
| 115 | // Send our "last state" informations to opponent |
| 116 | L = this.vr.moves.length; |
| 117 | this.conn.send(JSON.stringify({ |
| 118 | code: "lastate", |
| 119 | oppid: this.oppid, |
| 120 | gameId: this.gameId, |
| 121 | lastMove: (L>0?this.vr.moves[L-1]:undefined), |
| 122 | movesCount: L, |
| 123 | })); |
| 124 | break; |
| 125 | case "lastate": //got opponent infos about last move |
| 126 | L = this.vr.moves.length; |
| 127 | if (this.gameId != data.gameId) |
| 128 | break; //games IDs don't match: nothing we can do... |
| 129 | // OK, opponent still in game (which might be over) |
| 130 | if (this.score != "*") |
| 131 | { |
| 132 | // We finished the game (any result possible) |
| 133 | this.conn.send(JSON.stringify({ |
| 134 | code: "lastate", |
| 135 | oppid: data.oppid, |
| 136 | gameId: this.gameId, |
| 137 | score: this.score, |
| 138 | })); |
| 139 | } |
| 140 | else if (!!data.score) //opponent finished the game |
| 141 | this.endGame(data.score); |
| 142 | else if (data.movesCount < L) |
| 143 | { |
| 144 | // We must tell last move to opponent |
| 145 | this.conn.send(JSON.stringify({ |
| 146 | code: "lastate", |
| 147 | oppid: this.oppid, |
| 148 | gameId: this.gameId, |
| 149 | lastMove: this.vr.moves[L-1], |
| 150 | movesCount: L, |
| 151 | })); |
| 152 | } |
| 153 | else if (data.movesCount > L) //just got last move from him |
| 154 | this.play(data.lastMove, "animate"); |
| 155 | break; |
| 156 | case "resign": //..you won! |
| 157 | this.endGame(this.mycolor=="w"?"1-0":"0-1"); |
| 158 | break; |
| 159 | // TODO: also use (dis)connect info to count online players? |
| 160 | case "connect": |
| 161 | case "disconnect": |
| 162 | if (this.mode=="human" && this.oppid == data.id) |
| 163 | this.oppConnected = (data.code == "connect"); |
| 164 | if (this.oppConnected && this.score != "*") |
| 165 | { |
| 166 | // Send our name to the opponent, in case of he hasn't it |
| 167 | this.conn.send(JSON.stringify({ |
| 168 | code:"myname", name:this.myname, oppid: this.oppid})); |
| 169 | } |
| 170 | break; |
| 171 | } |
| 172 | }; |
| 173 | |
| 174 | const socketCloseListener = () => { |
| 175 | this.conn.addEventListener('message', socketMessageListener); |
| 176 | this.conn.addEventListener('close', socketCloseListener); |
| 177 | }; |
| 178 | this.conn.onmessage = socketMessageListener; |
| 179 | this.conn.onclose = socketCloseListener; |
| 180 | |
| 181 | // Computer moves web worker logic: (TODO: also for observers in HH games) |
| 182 | this.compWorker.postMessage(["scripts",variant.name]); |
| 183 | const self = this; |
| 184 | this.compWorker.onmessage = function(e) { |
| 185 | let compMove = e.data; |
| 186 | if (!compMove) |
| 187 | return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...) |
| 188 | if (!Array.isArray(compMove)) |
| 189 | compMove = [compMove]; //to deal with MarseilleRules |
| 190 | // TODO: imperfect attempt to avoid ghost move: |
| 191 | compMove.forEach(m => { m.computer = true; }); |
| 192 | // (first move) HACK: small delay to avoid selecting elements |
| 193 | // before they appear on page: |
| 194 | const delay = Math.max(500-(Date.now()-self.timeStart), 0); |
| 195 | setTimeout(() => { |
| 196 | const animate = (variant.name!="Dark" ? "animate" : null); |
| 197 | if (self.mode == "computer") //warning: mode could have changed! |
| 198 | self.play(compMove[0], animate); |
| 199 | if (compMove.length == 2) |
| 200 | setTimeout( () => { |
| 201 | if (self.mode == "computer") |
| 202 | self.play(compMove[1], animate); |
| 203 | }, 750); |
| 204 | }, delay); |
| 205 | } |
| 206 | }, |
| 207 | // this.conn est une prop, donnée depuis variant.js |
| 208 | //dans variant.js (plutôt room.js) conn gère aussi les challenges |
| 209 | // Puis en webRTC, repenser tout ça. |
| 210 | methods: { |
| 211 | translate: translate, |
| 212 | loadGame: function() { |
| 213 | const game = getGameFromStorage(this.gameId); |
| 214 | this.oppid = game.oppid; //opponent ID in case of running HH game |
| 215 | this.score = game.score; |
| 216 | this.mycolor = game.mycolor || "w"; |
| 217 | this.fenStart = game.fenStart; |
| 218 | this.moves = game.moves; |
| 219 | this.cursor = game.moves.length; |
| 220 | this.lastMove = (game.moves.length > 0 ? game.moves[this.cursor-1] : null); |
| 221 | }, |
| 222 | setEndgameMessage: function(score) { |
| 223 | let eogMessage = "Undefined"; |
| 224 | switch (score) |
| 225 | { |
| 226 | case "1-0": |
| 227 | eogMessage = translations["White win"]; |
| 228 | break; |
| 229 | case "0-1": |
| 230 | eogMessage = translations["Black win"]; |
| 231 | break; |
| 232 | case "1/2": |
| 233 | eogMessage = translations["Draw"]; |
| 234 | break; |
| 235 | case "?": |
| 236 | eogMessage = "Unfinished"; |
| 237 | break; |
| 238 | } |
| 239 | this.endgameMessage = eogMessage; |
| 240 | }, |
| 241 | download: function() { |
| 242 | const content = this.getPgn(); |
| 243 | // Prepare and trigger download link |
| 244 | let downloadAnchor = document.getElementById("download"); |
| 245 | downloadAnchor.setAttribute("download", "game.pgn"); |
| 246 | downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content); |
| 247 | downloadAnchor.click(); |
| 248 | }, |
| 249 | getPgn: function() { |
| 250 | let pgn = ""; |
| 251 | pgn += '[Site "vchess.club"]\n'; |
| 252 | const opponent = (this.mode=="human" ? "Anonymous" : "Computer"); |
| 253 | pgn += '[Variant "' + variant.name + '"]\n'; |
| 254 | pgn += '[Date "' + getDate(new Date()) + '"]\n'; |
| 255 | const whiteName = ["human","computer"].includes(this.mode) |
| 256 | ? (this.mycolor=='w'?'Myself':opponent) |
| 257 | : "analyze"; |
| 258 | const blackName = ["human","computer"].includes(this.mode) |
| 259 | ? (this.mycolor=='b'?'Myself':opponent) |
| 260 | : "analyze"; |
| 261 | pgn += '[White "' + whiteName + '"]\n'; |
| 262 | pgn += '[Black "' + blackName + '"]\n'; |
| 263 | pgn += '[Fen "' + this.fenStart + '"]\n'; |
| 264 | pgn += '[Result "' + this.score + '"]\n\n'; |
| 265 | let counter = 1; |
| 266 | let i = 0; |
| 267 | while (i < this.moves.length) |
| 268 | { |
| 269 | pgn += (counter++) + "."; |
| 270 | for (let color of ["w","b"]) |
| 271 | { |
| 272 | let move = ""; |
| 273 | while (i < this.moves.length && this.moves[i].color == color) |
| 274 | move += this.moves[i++].notation[0] + ","; |
| 275 | move = move.slice(0,-1); //remove last comma |
| 276 | pgn += move + (i < this.moves.length-1 ? " " : ""); |
| 277 | } |
| 278 | } |
| 279 | return pgn + "\n"; |
| 280 | }, |
| 281 | showScoreMsg: function(score) { |
| 282 | this.setEndgameMessage(score); |
| 283 | let modalBox = document.getElementById("modal-eog"); |
| 284 | modalBox.checked = true; |
| 285 | setTimeout(() => { modalBox.checked = false; }, 2000); |
| 286 | }, |
| 287 | endGame: function(score) { |
| 288 | this.score = score; |
| 289 | if (["human","computer"].includes(this.mode)) |
| 290 | { |
| 291 | const prefix = (this.mode=="computer" ? "comp-" : ""); |
| 292 | localStorage.setItem(prefix+"score", score); |
| 293 | } |
| 294 | this.showScoreMsg(score); |
| 295 | if (this.mode == "human" && this.oppConnected) |
| 296 | { |
| 297 | // Send our nickname to opponent |
| 298 | this.conn.send(JSON.stringify({ |
| 299 | code:"myname", name:this.myname, oppid:this.oppid})); |
| 300 | } |
| 301 | // TODO: what about cursor ? |
| 302 | //this.cursor = this.vr.moves.length; //to navigate in finished game |
| 303 | }, |
| 304 | resign: function(e) { |
| 305 | this.getRidOfTooltip(e.currentTarget); |
| 306 | if (this.mode == "human" && this.oppConnected) |
| 307 | { |
| 308 | try { |
| 309 | this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid})); |
| 310 | } catch (INVALID_STATE_ERR) { |
| 311 | return; //socket is not ready (and not yet reconnected) |
| 312 | } |
| 313 | } |
| 314 | this.endGame(this.mycolor=="w"?"0-1":"1-0"); |
| 315 | }, |
| 316 | playComputerMove: function() { |
| 317 | this.timeStart = Date.now(); |
| 318 | this.compWorker.postMessage(["askmove"]); |
| 319 | }, |
| 320 | animateMove: function(move) { |
| 321 | let startSquare = document.getElementById(this.getSquareId(move.start)); |
| 322 | let endSquare = document.getElementById(this.getSquareId(move.end)); |
| 323 | let rectStart = startSquare.getBoundingClientRect(); |
| 324 | let rectEnd = endSquare.getBoundingClientRect(); |
| 325 | let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y}; |
| 326 | let movingPiece = |
| 327 | document.querySelector("#" + this.getSquareId(move.start) + " > img.piece"); |
| 328 | // HACK for animation (with positive translate, image slides "under background") |
| 329 | // Possible improvement: just alter squares on the piece's way... |
| 330 | squares = document.getElementsByClassName("board"); |
| 331 | for (let i=0; i<squares.length; i++) |
| 332 | { |
| 333 | let square = squares.item(i); |
| 334 | if (square.id != this.getSquareId(move.start)) |
| 335 | square.style.zIndex = "-1"; |
| 336 | } |
| 337 | movingPiece.style.transform = "translate(" + translation.x + "px," + |
| 338 | translation.y + "px)"; |
| 339 | movingPiece.style.transitionDuration = "0.2s"; |
| 340 | movingPiece.style.zIndex = "3000"; |
| 341 | setTimeout( () => { |
| 342 | for (let i=0; i<squares.length; i++) |
| 343 | squares.item(i).style.zIndex = "auto"; |
| 344 | movingPiece.style = {}; //required e.g. for 0-0 with KR swap |
| 345 | this.play(move); //TODO: plutôt envoyer message "please play" |
| 346 | }, 250); |
| 347 | }, |
| 348 | play: function(move, programmatic) { |
| 349 | // Forbid playing outside analyze mode when cursor isn't at moves.length-1 |
| 350 | if (this.mode != "analyze" && this.cursor < this.moves.length-1) |
| 351 | return; |
| 352 | let navigate = !move; |
| 353 | if (navigate) |
| 354 | { |
| 355 | if (this.cursor == this.moves.length) |
| 356 | return; //no more moves |
| 357 | move = this.moves[this.cursor]; |
| 358 | } |
| 359 | if (!!programmatic) //computer or human opponent |
| 360 | return this.animateMove(move); |
| 361 | // Not programmatic, or animation is over |
| 362 | if (!move.notation) |
| 363 | move.notation = this.vr.getNotation(move); |
| 364 | if (!move.color) |
| 365 | move.color = this.vr.turn; |
| 366 | this.vr.play(move); |
| 367 | this.cursor++; |
| 368 | this.lastMove = move; |
| 369 | if (!move.fen) |
| 370 | move.fen = this.vr.getFen(); |
| 371 | if (this.sound == 2) |
| 372 | new Audio("/sounds/move.mp3").play().catch(err => {}); |
| 373 | if (this.mode == "human") |
| 374 | { |
| 375 | updateStorage(move); //after our moves and opponent moves |
| 376 | if (this.vr.turn == this.userColor) |
| 377 | this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid})); |
| 378 | } |
| 379 | else if (this.mode == "computer") |
| 380 | { |
| 381 | // Send the move to web worker (including his own moves) |
| 382 | this.compWorker.postMessage(["newmove",move]); |
| 383 | } |
| 384 | if (!navigate && (this.score == "*" || this.mode == "analyze")) |
| 385 | { |
| 386 | // Stack move on movesList at current cursor |
| 387 | if (this.cursor == this.moves.length) |
| 388 | this.moves.push(move); |
| 389 | else |
| 390 | this.moves = this.moves.slice(0,this.cursor-1).concat([move]); |
| 391 | } |
| 392 | // Is opponent in check? |
| 393 | this.incheck = this.vr.getCheckSquares(this.vr.turn); |
| 394 | const score = this.vr.getCurrentScore(); |
| 395 | if (score != "*") |
| 396 | { |
| 397 | if (["human","computer"].includes(this.mode)) |
| 398 | this.endGame(score); |
| 399 | else //just show score on screen (allow undo) |
| 400 | this.showScoreMsg(score); |
| 401 | // TODO: notify end of game (give score) |
| 402 | } |
| 403 | else if (this.mode == "computer" && this.vr.turn != this.userColor) |
| 404 | this.playComputerMove(); |
| 405 | // https://vuejs.org/v2/guide/list.html#Caveats (also for undo) |
| 406 | if (navigate) |
| 407 | this.$children[0].$forceUpdate(); //TODO!? |
| 408 | }, |
| 409 | undo: function(move) { |
| 410 | let navigate = !move; |
| 411 | if (navigate) |
| 412 | { |
| 413 | if (this.cursor == 0) |
| 414 | return; //no more moves |
| 415 | move = this.moves[this.cursor-1]; |
| 416 | } |
| 417 | this.vr.undo(move); |
| 418 | this.cursor--; |
| 419 | this.lastMove = (this.cursor > 0 ? this.moves[this.cursor-1] : undefined); |
| 420 | if (navigate) |
| 421 | this.$children[0].$forceUpdate(); //TODO!? |
| 422 | if (this.sound == 2) |
| 423 | new Audio("/sounds/undo.mp3").play().catch(err => {}); |
| 424 | this.incheck = this.vr.getCheckSquares(this.vr.turn); |
| 425 | if (!navigate && this.mode == "analyze") |
| 426 | this.moves.pop(); |
| 427 | if (navigate) |
| 428 | this.$forceUpdate(); //TODO!? |
| 429 | }, |
| 430 | gotoMove: function(index) { |
| 431 | this.vr = new VariantRules(this.moves[index].fen); |
| 432 | this.cursor = index+1; |
| 433 | this.lastMove = this.moves[index]; |
| 434 | }, |
| 435 | gotoBegin: function() { |
| 436 | this.vr = new VariantRules(this.fenStart); |
| 437 | this.cursor = 0; |
| 438 | this.lastMove = null; |
| 439 | }, |
| 440 | gotoEnd: function() { |
| 441 | this.gotoMove(this.moves.length-1); |
| 442 | this.lastMove = this.moves[this.moves.length-1]; |
| 443 | }, |
| 444 | flip: function() { |
| 445 | this.orientation = V.GetNextCol(this.orientation); |
| 446 | }, |
| 447 | }, |
| 448 | }) |
| 449 | //TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle" |
| 450 | //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions, |
| 451 | //comme sur lichess |
| 452 | //TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB |