Implement basic observing logic
[vchess.git] / client / src / views / Game.vue
index 114b86b..984a66b 100644 (file)
@@ -8,32 +8,21 @@
         h3#abortBoxTitle.section {{ st.tr["Terminate game?"] }}
         button(@click="abortGame") {{ st.tr["Sorry I have to go"] }}
         button(@click="abortGame") {{ st.tr["Game seems over"] }}
-        button(@click="abortGame") {{ st.tr["Game is too boring"] }}
     BaseGame(:game="game" :vr="vr" ref="basegame"
       @newmove="processMove" @gameover="gameOver")
     div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
-    div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
+    div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
     .button-group(v-if="game.mode!='analyze' && game.score=='*'")
       button(@click="offerDraw") Draw
       button(@click="() => abortGame()") Abort
       button(@click="resign") Resign
-    div(v-if="game.mode=='corr'")
-      textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
-      div(v-show="cursor>=0") {{ moves[cursor].message }}
+    textarea(v-if="game.score=='*'" v-model="corrMsg")
+    Chat(:players="game.players")
 </template>
 
-<!--
-// TODO: movelist dans basegame et chat ici
-// ==> après, implémenter/vérifier les passages de challenges + parties en cours
-// observer,
-// + problèmes, habiller et publier. (+ corr...)
-// when send to chat (or a move), reach only this group (send gid along)
--->
-
 <script>
 import BaseGame from "@/components/BaseGame.vue";
-//import Chat from "@/components/Chat.vue";
-//import MoveList from "@/components/MoveList.vue";
+import Chat from "@/components/Chat.vue";
 import { store } from "@/store";
 import { GameStorage } from "@/utils/gameStorage";
 import { ppt } from "@/utils/datetime";
@@ -44,6 +33,7 @@ export default {
   name: 'my-game',
   components: {
     BaseGame,
+    Chat,
   },
   // gameRef: to find the game in (potentially remote) storage
   data: function() {
@@ -84,23 +74,14 @@ export default {
           : 0;
         return ppt(newState[i] - removeTime);
       });
-      const myTurn = (currentTurn == this.game.mycolor);
       let clockUpdate = setInterval(() => {
-        if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
+        if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
         {
           clearInterval(clockUpdate);
-          if (countdown <= 0 && myTurn)
+          if (countdown < 0)
           {
             this.$refs["basegame"].endGame(
-              this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
-            const oppsid = this.getOppSid();
-            if (!!oppsid)
-            {
-              this.st.conn.send(JSON.stringify({
-                code: "timeover",
-                target: oppsid,
-              }));
-            }
+              this.vr.turn=="w" ? "0-1" : "1-0", "Time");
           }
         }
         else
@@ -116,20 +97,23 @@ export default {
     // Always add myself to players' list
     const my = this.st.user;
     this.people.push({sid:my.sid, id:my.id, name:my.name});
-    if (!!this.$route.params["id"])
-    {
-      this.gameRef.id = this.$route.params["id"];
-      this.gameRef.rid = this.$route.query["rid"];
-      this.loadGame();
-    }
+    this.gameRef.id = this.$route.params["id"];
+    this.gameRef.rid = this.$route.query["rid"]; //may be undefined
+    if (!this.gameRef.rid)
+      this.loadGame(); //local or corr: can load from now
+    // TODO: mode analyse (/analyze/Atomic/rn
+    // ... fen = query[], vname=params[] ...
     // 0.1] Ask server for room composition:
-    const funcPollClients = () => {
+    const initialize = () => {
+      // Poll clients + load game if stored remotely
       this.st.conn.send(JSON.stringify({code:"pollclients"}));
+      if (!!this.gameRef.rid)
+        this.loadGame();
     };
     if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
-      funcPollClients();
+      initialize();
     else //socket not ready yet (initial loading)
-      this.st.conn.onopen = funcPollClients;
+      this.st.conn.onopen = initialize;
     this.st.conn.onmessage = this.socketMessageListener;
     const socketCloseListener = () => {
       store.socketCloseListener(); //reinitialize connexion (in store.js)
@@ -173,6 +157,10 @@ export default {
         case "identity":
         {
           let player = this.people.find(p => p.sid == data.user.sid);
+          // NOTE: sometimes player.id fails because player is undefined...
+          // Probably because the event was meant for Hall?
+          if (!player)
+            return;
           player.id = data.user.id;
           player.name = data.user.name;
           // Sending last state only for live games: corr games are complete
@@ -195,6 +183,19 @@ export default {
           }
           break;
         }
+        case "askgame":
+          // Send current (live) game
+          const myGame =
+          {
+            // Minimal game informations:
+            id: this.game.id,
+            players: this.game.players.map(p => p.name),
+            vid: this.game.vid,
+            timeControl: this.game.timeControl,
+          };
+          this.st.conn.send(JSON.stringify({code:"game",
+            game:myGame, target:data.from}));
+          break;
         case "newmove":
           // NOTE: this call to play() will trigger processMove()
           this.$refs["basegame"].play(data.move,
@@ -223,10 +224,6 @@ export default {
           this.$refs["basegame"].endGame(
             this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
           break;
-        case "timeover":
-          this.$refs["basegame"].endGame(
-            this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
-          break;
         case "abort":
           this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
           break;
@@ -237,12 +234,10 @@ export default {
           this.drawOffer = "received";
           break;
         case "askfullgame":
-          // TODO: just give game; observers are listed here anyway:
-          // ==> mark request SID as someone to send moves to
-          // NOT to all people array: our opponent can send moves too!
+          // TODO: use data.id to retrieve game in indexedDB (but for now only one running game so OK)
+          this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
           break;
         case "fullgame":
-          // and when receiving answer just call loadGame(received_game)
           this.loadGame(data.game);
           break;
         // TODO: drawaccepted (click draw button before sending move
@@ -250,12 +245,12 @@ export default {
         // ==> on "newmove", check "drawOffer" field
         case "connect":
         {
-          this.people.push({name:"", id:0, sid:data.sid});
-          this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
+          this.people.push({name:"", id:0, sid:data.from});
+          this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
           break;
         }
         case "disconnect":
-          ArrayFun.remove(this.people, p => p.sid == data.sid);
+          ArrayFun.remove(this.people, p => p.sid == data.from);
           break;
       }
     },
@@ -349,6 +344,7 @@ export default {
           game.clocks = [tc.mainTime, tc.mainTime];
           game.initime = [0, 0];
           const L = game.moves.length;
+          game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
           if (L >= 3)
           {
             let addTime = [0, 0];
@@ -362,6 +358,17 @@ export default {
           }
           if (L >= 1)
             game.initime[L%2] = game.moves[L-1].played;
+          // Now that we used idx and played, re-format moves as for live games
+          game.moves = game.moves.map( (m) => {
+            const s = m.squares;
+            return {
+              appear: s.appear,
+              vanish: s.vanish,
+              start: s.start,
+              end: s.end,
+              message: m.message,
+            };
+          });
         }
         const myIdx = game.players.findIndex(p => {
           return p.sid == this.st.user.sid || p.uid == this.st.user.id;
@@ -395,10 +402,12 @@ export default {
         );
       };
       if (!!game)
-        return afterRetrival(game);
+        return afterRetrieval(game);
       if (!!this.gameRef.rid)
       {
         // Remote live game
+        // (TODO: send game ID as well, and receiver would pick the corresponding
+        // game in his current games; if allowed to play several)
         this.st.conn.send(JSON.stringify(
           {code:"askfullgame", target:this.gameRef.rid}));
         // (send moves updates + resign/abort/draw actions)
@@ -406,9 +415,7 @@ export default {
       else
       {
         // Local or corr game
-        GameStorage.get(this.gameRef.id, (game) => {
-          afterRetrieval(game);
-        });
+        GameStorage.get(this.gameRef.id, afterRetrieval);
       }
     },
     // Post-process a move (which was just played)
@@ -425,7 +432,7 @@ export default {
           obj[key] = move[key];
           return obj;
         }, {});
-      // Send move ("newmove" event) to opponent(s) (if ours)
+      // Send move ("newmove" event) to people in the room (if our turn)
       let addTime = 0;
       if (move.color == this.game.mycolor)
       {
@@ -435,41 +442,73 @@ export default {
           // elapsed time is measured in milliseconds
           addTime = this.game.increment - elapsed/1000;
         }
-        this.st.conn.send(JSON.stringify({
-          code: "newmove",
-          target: this.game.oppid,
-          move: Object.assign({}, filtered_move, {addTime: addTime}),
-        }));
+        let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
+        if (this.game.type == "corr")
+          sendMove.message = this.corrMsg;
+        const oppsid = this.getOppSid();
+        this.people.forEach(p => {
+          if (p.sid != this.st.user.sid)
+          {
+            this.st.conn.send(JSON.stringify({
+              code: "newmove",
+              target: p.sid,
+              move: sendMove,
+            }));
+          }
+        });
+        if (this.game.type == "corr" && this.corrMsg != "")
+        {
+          // Add message to last move in BaseGame:
+          // TODO: not very good style...
+          this.$refs["basegame"].setCurrentMessage(this.corrMsg);
+        }
       }
       else
         addTime = move.addTime; //supposed transmitted
       const nextIdx = ["w","b"].indexOf(this.vr.turn);
-      GameStorage.update(this.gameRef.id,
+      // Since corr games are stored at only one location, update should be
+      // done only by one player for each move:
+      if (this.game.type == "live" || move.color == this.game.mycolor)
       {
-        fen: move.fen,
-        move:
+        if (this.game.type == "corr")
         {
-          squares: filtered_move,
-          message: this.corrMsg, //TODO
-          played: Date.now(), //TODO: on server?
-          idx: this.game.moves.length,
-          color: move.color,
-        },
-        clocks: this.game.clocks.map((t,i) => i==colorIdx
-          ? this.game.clocks[i] + addTime
-          : this.game.clocks[i]),
-        initime: this.game.initime.map((t,i) => i==nextIdx
-          ? Date.now()
-          : this.game.initime[i]),
-      });
+          GameStorage.update(this.gameRef.id,
+          {
+            fen: move.fen,
+            move:
+            {
+              squares: filtered_move,
+              message: this.corrMsg,
+              played: Date.now(), //TODO: on server?
+              idx: this.game.moves.length,
+            },
+          });
+        }
+        else //live
+        {
+          GameStorage.update(this.gameRef.id,
+          {
+            fen: move.fen,
+            move: filtered_move,
+            clocks: this.game.clocks.map((t,i) => i==colorIdx
+              ? this.game.clocks[i] + addTime
+              : this.game.clocks[i]),
+            initime: this.game.initime.map((t,i) => i==nextIdx
+              ? Date.now()
+              : this.game.initime[i]),
+          });
+        }
+      }
       // Also update current game object:
       this.game.moves.push(move);
       this.game.fen = move.fen;
       //TODO: just this.game.clocks[colorIdx] += addTime;
       this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
       this.game.initime[nextIdx] = Date.now();
+      // Finally reset curMoveMessage if needed
+      if (this.game.type == "corr" && move.color == this.game.mycolor)
+        this.corrMsg = "";
     },
-    // TODO: this update function should also work for corr games
     gameOver: function(score) {
       this.game.mode = "analyze";
       this.game.score = score;