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