Fix clocks update
[vchess.git] / client / src / views / Game.vue
index ab6ae7a..f8cf2a7 100644 (file)
@@ -11,6 +11,8 @@
         button(@click="abortGame") {{ st.tr["Game is too boring"] }}
     BaseGame(:game="game" :vr="vr" ref="basegame"
       @newmove="processMove" @gameover="gameOver")
+    // TODO: show players names + clocks state
+    div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
     .button-group(v-if="game.mode!='analyze' && game.score=='*'")
       button(@click="offerDraw") Draw
       button(@click="() => abortGame()") Abort
@@ -26,6 +28,7 @@ import BaseGame from "@/components/BaseGame.vue";
 //import MoveList from "@/components/MoveList.vue";
 import { store } from "@/store";
 import { GameStorage } from "@/utils/gameStorage";
+import { ppt } from "@/utils/datetime";
 
 export default {
   name: 'my-game',
@@ -41,6 +44,7 @@ export default {
         rid: ""
       },
       game: { }, //passed to BaseGame
+      virtualClocks: [0, 0], //initialized with true game.clocks
       vr: null, //"variant rules" object initialized from FEN
       drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
       people: [ ], //potential observers (TODO)
@@ -55,6 +59,36 @@ export default {
         this.loadGame();
       }
     },
+    "game.clocks": function(newState) {
+      this.virtualClocks = newState.map(s => ppt(s));
+      const currentTurn = this.vr.turn;
+      const colorIdx = ["w","b","g","r"].indexOf(currentTurn);
+      let countdown = newState[colorIdx] -
+        (Date.now() - this.game.initime[colorIdx])/1000;
+      const myTurn = (currentTurn == this.game.mycolor);
+      let clockUpdate = setInterval(() => {
+        if (countdown <= 0 || this.vr.turn != currentTurn)
+        {
+          clearInterval(clockUpdate);
+          if (countdown <= 0 && myTurn)
+          {
+            this.$refs["basegame"].endGame(
+              this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
+            this.game.players.forEach(p => {
+              if (p.sid != this.st.user.sid)
+              {
+                this.st.conn.send(JSON.stringify({
+                  code: "timeover",
+                  target: p.sid,
+                }));
+              }
+            });
+          }
+        }
+        // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
+        this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
+      }, 1000);
+    },
   },
   created: function() {
     if (!!this.$route.params["id"])
@@ -222,7 +256,7 @@ export default {
         return;
         //const message = event.
         // Next line will trigger a "gameover" event, bubbling up till here
-        this.$refs["basegame"].endGame("?");
+        this.$refs["basegame"].endGame("?", "Abort: " + event.msg); //TODO
         this.game.players.forEach(p => {
           if (!!p.sid && p.sid != this.st.user.sid)
           {
@@ -248,7 +282,8 @@ export default {
         }
       });
       // Next line will trigger a "gameover" event, bubbling up till here
-      this.$refs["basegame"].endGame(this.game.mycolor=="w" ? "0-1" : "1-0");
+      this.$refs["basegame"].endGame(
+        this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
     },
     // 3 cases for loading a game:
     //  - from indexedDB (running or completed live game I play)
@@ -258,7 +293,7 @@ export default {
       const afterRetrieval = async (game) => {
         const vModule = await import("@/variants/" + game.vname + ".js");
         window.V = vModule.VariantRules;
-        this.vr = new V(game.fenStart);
+        this.vr = new V(game.fen);
         this.game = Object.assign({},
           game,
           // NOTE: assign mycolor here, since BaseGame could also bs VS computer
@@ -311,44 +346,47 @@ export default {
           return obj;
         }, {});
       // Send move ("newmove" event) to opponent(s) (if ours)
-      // (otherwise move.elapsed is supposed to be already transmitted)
       let addTime = undefined;
       if (move.color == this.game.mycolor)
       {
-        const elapsed = Date.now() - this.game.initime;
+        const elapsed = Date.now() - this.game.initime[colorIdx];
+        // elapsed time is measured in milliseconds
+        addTime = this.game.increment - elapsed/1000;
         this.game.players.forEach(p => {
           if (p.sid != this.st.user.sid)
           {
             this.st.conn.send(JSON.stringify({
               code: "newmove",
               target: p.sid,
-              move: Object.assign({}, filtered_move, {elapsed: elapsed}),
+              move: Object.assign({}, filtered_move, {addTime: addTime}),
             }));
           }
         });
-        move.elapsed = elapsed;
-        // elapsed time is measured in milliseconds
-        addTime = this.game.increment - elapsed/1000;
       }
-      const myTurnNow = (this.vr.turn == this.game.mycolor);
+      else
+        addTime = move.addTime; //supposed transmitted
+      const nextIdx = ["w","b","g","r"].indexOf(this.vr.turn);
       GameStorage.update(this.gameRef.id,
       {
         colorIdx: colorIdx,
+        nextIdx: nextIdx,
         move: filtered_move,
         fen: move.fen,
         addTime: addTime,
-        initime: myTurnNow,
       });
       // Also update current game object:
       this.game.moves.push(move);
       this.game.fen = move.fen;
-      this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
-      this.game.initime = (myTurnNow ? Date.now() : undefined);
+      //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
+      this.$set(this.game.clocks, colorIdx,
+        this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
+      this.game.initime[nextIdx] = Date.now();
     },
     // TODO: this update function should also work for corr games
     gameOver: function(score) {
       this.game.mode = "analyze";
-      GameStorage.update({
+      GameStorage.update(this.gameRef.id,
+      {
         score: score,
       });
     },