Update on game.clocks. Unfinished
[vchess.git] / client / src / views / Game.vue
index 9be8806..d3a4bd7 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: virtualClocks[...], not "clockState"
+    div Time: {{ clockState }}
     .button-group(v-if="game.mode!='analyze' && game.score=='*'")
       button(@click="offerDraw") Draw
       button(@click="() => abortGame()") Abort
@@ -25,7 +27,8 @@ import BaseGame from "@/components/BaseGame.vue";
 //import Chat from "@/components/Chat.vue";
 //import MoveList from "@/components/MoveList.vue";
 import { store } from "@/store";
-import { GameStorage } from "@/utils/storage";
+import { GameStorage } from "@/utils/gameStorage";
+import { ppt } from "@/utils/datetime";
 
 export default {
   name: 'my-game',
@@ -41,11 +44,23 @@ export default {
         rid: ""
       },
       game: { }, //passed to BaseGame
+      virtualClocks: [ ], //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)
     };
   },
+
+  // TODO: this method should disappear and virtualClocks already be "prettified":
+  // all computations are done when game.clocks are updated (see below)
+  computed: {
+    clockState: function() {
+      if (this.virtualClocks.length == 0)
+        return; //nothing to display for now
+      return ppt(this.virtualClocks[0]) + " - " + ppt(this.virtualClocks[1]);
+    },
+  },
+
   watch: {
     '$route' (to, from) {
       if (!!to.params["id"])
@@ -55,6 +70,18 @@ export default {
         this.loadGame();
       }
     },
+    "game.clocks": function(newState) {
+      this.virtualClocks = newState;
+      setInterval(function() {
+
+        // TODO: run clock of current turn, stop at 0, clearInterval in the end
+        // https://www.geeksforgeeks.org/create-countdown-timer-using-javascript/
+        // if it was my turn, call gameOver. Otherwise just stay at 0 and wait.
+        if ( ...........)
+//à 0, bloquer puis si mon temps : perte au temps. Sinon attendre message adversaire (il peut être offline).
+
+      });
+    },
   },
   created: function() {
     if (!!this.$route.params["id"])
@@ -250,13 +277,12 @@ 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");
     },
-    // 4 cases for loading a game:
-    //  - from localStorage (one running game I play)
-    //  - from indexedDB (one completed live game)
+    // 3 cases for loading a game:
+    //  - from indexedDB (running or completed live game I play)
     //  - from server (one correspondance game I play[ed] or not)
     //  - from remote peer (one live game I don't play, finished or not)
-    loadGame: function() {
-      GameStorage.get(this.gameRef, async (game) => {
+    loadGame: function(game) {
+      const afterRetrieval = async (game) => {
         const vModule = await import("@/variants/" + game.vname + ".js");
         window.V = vModule.VariantRules;
         this.vr = new V(game.fenStart);
@@ -266,7 +292,23 @@ export default {
           {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
             p => p.sid == this.st.user.sid)]},
         );
-      });
+      };
+      if (!!game)
+        return afterRetrival(game);
+      if (!!this.gameRef.rid)
+      {
+        // TODO: just send a game request message to the remote player,
+        // and when receiving answer just call loadGame(received_game)
+        // + remote peer should have registered us as an observer
+        // (send moves updates + resign/abort/draw actions)
+        return;
+      }
+      else
+      {
+        GameStorage.get(this.gameRef.id, async (game) => {
+          afterRetrieval(game);
+        });
+      }
 //    // Poll all players except me (if I'm playing) to know online status.
 //    // --> Send ping to server (answer pong if players[s] are connected)
 //    if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
@@ -296,37 +338,45 @@ 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() - GameStorage.getInitime();
+        const elapsed = Date.now() - this.game.initime;
+        // 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;
       }
-      GameStorage.update({
+      else
+        addTime = move.addTime; //supposed transmitted
+      const myTurnNow = (this.vr.turn == this.game.mycolor);
+      GameStorage.update(this.gameRef.id,
+      {
         colorIdx: colorIdx,
         move: filtered_move,
         fen: move.fen,
         addTime: addTime,
-        initime: (this.vr.turn == this.game.mycolor), //my turn now?
+        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: 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,
       });
     },