Separate timeControl logic into utils/timeControl
[vchess.git] / client / src / views / Hall.vue
index 145d898..1dd72b4 100644 (file)
@@ -1,5 +1,3 @@
-<!-- Main playing hall: online players + current challenges + button "new game" -->
-
 <template lang="pug">
 main
   input#modalNewgame.modal(type="checkbox")
@@ -13,7 +11,7 @@ main
       fieldset
         label(for="selectNbPlayers") {{ st.tr["Number of players"] }}
         select#selectNbPlayers(v-model="newchallenge.nbPlayers")
-          option(v-show="possibleNbplayers(2)" value="2") 2
+          option(v-show="possibleNbplayers(2)" value="2" selected) 2
           option(v-show="possibleNbplayers(3)" value="3") 3
           option(v-show="possibleNbplayers(4)" value="4") 4
       fieldset
@@ -23,11 +21,11 @@ main
       fieldset(v-if="st.user.id > 0")
         label(for="selectPlayers") {{ st.tr["Play with? (optional)"] }}
         #selectPlayers
-          input(type="text" v-model="newchallenge.to[0].name")
+          input(type="text" v-model="newchallenge.to[0]")
           input(v-show="newchallenge.nbPlayers>=3" type="text"
-            v-model="newchallenge.to[1].name")
+            v-model="newchallenge.to[1]")
           input(v-show="newchallenge.nbPlayers==4" type="text"
-            v-model="newchallenge.to[2].name")
+            v-model="newchallenge.to[2]")
       fieldset(v-if="st.user.id > 0")
         label(for="inputFen") {{ st.tr["FEN (optional)"] }}
         input#inputFen(type="text" v-model="newchallenge.fen")
@@ -41,7 +39,9 @@ main
         :challenges="challenges" @click-challenge="clickChallenge")
       #players(v-show="cpdisplay=='players'")
         h3 Online players
-        div(v-for="p in uniquePlayers" @click="tryChallenge(p)")
+        .player(v-for="p in uniquePlayers" @click="tryChallenge(p)"
+          :class="{anonymous: !!p.count}"
+        )
           | {{ p.name + (!!p.count ? " ("+p.count+")" : "") }}
   .row
     .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
@@ -63,6 +63,7 @@ import { NbPlayers } from "@/data/nbPlayers";
 import { checkChallenge } from "@/data/challengeCheck";
 import { ArrayFun } from "@/utils/array";
 import { ajax } from "@/utils/ajax";
+import { getRandString } from "@/utils/alea";
 import GameList from "@/components/GameList.vue";
 import ChallengeList from "@/components/ChallengeList.vue";
 export default {
@@ -84,54 +85,122 @@ export default {
         fen: "",
         vid: 0,
         nbPlayers: 0,
-        // NOTE: id (server DB) and sid (socket ID).
-        // Anonymous players just have a socket ID.
-        to: [
-          {id:0, sid:"", name:""},
-          {id:0, sid:"", name:""},
-          {id:0, sid:"", name:""}
-        ],
-        timeControl: "",
+        to: ["", "", ""], //name of challenged players
+        timeControl: "", //"2m+2s" ...etc
       },
     };
   },
   computed: {
     uniquePlayers: function() {
       // Show e.g. "5 @nonymous", and do nothing on click on anonymous
-      let playerList = [{id:0, name:"@nonymous", count:0}];
+      let anonymous = {id:0, name:"@nonymous", count:0};
+      let playerList = [];
       this.players.forEach(p => {
         if (p.id > 0)
           playerList.push(p);
         else
-          playerList[0].count++;
+          anonymous.count++;
       });
+      if (anonymous.count > 0)
+        playerList.push(anonymous);
       return playerList;
     },
   },
-  // TODO: this looks ugly... (use VueX ?!)
-  watch: {
-    "st.conn": function() {
-      this.st.conn.onmessage = this.socketMessageListener;
-      this.st.conn.onclose = this.socketCloseListener;
-    },
-  },
   created: function() {
-    // TODO: ask server for current corr games (all but mines: names, ID, time control)
-    // also ask for corr challenges
-    // TODO: add myself to players
-    // --> when sending something, send to all players but NOT me !
-    if (!!this.st.conn)
-    {
-      this.st.conn.onmessage = this.socketMessageListener;
-      this.st.conn.onclose = this.socketCloseListener;
-    }
+    // Always add myself to players' list
     this.players.push(this.st.user);
+    // Ask server for current corr games (all but mines)
+//    ajax(
+//      "",
+//      "GET",
+//      response => {
+//
+//      }
+//    );
+//    // Also ask for corr challenges (all)
+//    ajax(
+//      "",
+//      "GET",
+//      response => {
+//
+//      }
+//    );
+    // 0.1] Ask server for for room composition:
+    const socketOpenListener = () => {
+      this.st.conn.send(JSON.stringify({code:"pollclients"}));
+    };
+    this.st.conn.onopen = socketOpenListener;
+    // TODO: is this required here?
+    this.oldOnmessage = this.st.conn.onmessage || Function.prototype;
+    this.st.conn.onmessage = this.socketMessageListener;
+    const oldOnclose = this.st.conn.onclose;
+    const socketCloseListener = () => {
+      oldOnclose(); //reinitialize connexion (in store.js)
+      this.st.conn.addEventListener('message', this.socketMessageListener);
+      this.st.conn.addEventListener('close', socketCloseListener);
+    };
+    this.st.conn.onclose = socketCloseListener;
   },
   methods: {
     socketMessageListener: function(msg) {
+      // Save and call current st.conn.onmessage if one was already defined
+      // --> also needed in future Game.vue (also in Chat.vue component)
+      // TODO: merge Game.vue and MoveList.vue (one logic entity, no ?)
+      this.oldOnmessage(msg);
       const data = JSON.parse(msg.data);
       switch (data.code)
       {
+        // 0.2] Receive clients list (just socket IDs)
+        case "pollclients":
+          data.sockIds.forEach(sid => {
+            this.players.push({sid:sid, id:0, name:""});
+            // Ask identity, challenges and game(s)
+            this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
+            this.st.conn.send(JSON.stringify({code:"askchallenges", target:sid}));
+            this.st.conn.send(JSON.stringify({code:"askgame", target:sid}));
+          });
+          break;
+        case "askidentity":
+          // Request for identification
+          this.st.conn.send(JSON.stringify(
+            {code:"identity", user:this.st.user, target:data.from}));
+          break;
+        case "askchallenge":
+          // Send my current live challenge
+          const cIdx = this.challenges
+            .findIndex(c => c.from.sid == this.st.user.sid && c.liveGame);
+          if (cIdx >= 0)
+          {
+            const c = this.challenges[cIdx];
+            const myChallenge =
+            {
+              // Minimal challenge informations: (from not required)
+              to: c.to,
+              fen: c.fen,
+              vid: c.vid,
+              timeControl: c.timeControl
+            };
+            this.st.conn.send(JSON.stringify({code:"challenge",
+              challenge:myChallenge, target:data.from})
+          }
+          break;
+        case "askgame":
+          // TODO: Send my current live game (if any): variant, players, movesCount
+          break;
+        case "identity":
+          if (data.user.id > 0) //otherwise "anonymous", nothing to retrieve
+          {
+            const pIdx = this.players.findIndex(p => p.sid == data.user.sid);
+            this.players[pIdx].id = data.user.id;
+            this.players[pIdx].name = data.user.name;
+          }
+          break;
+        case "challenge":
+          // Receive challenge from some player (+sid)
+          break;
+        case "game":
+          // Receive live game from some player (+sid)
+          break;
 // *  - receive "new game": if live, store locally + redirect to game
 // *    If corr: notify "new game has started", give link, but do not redirect
         case "newgame":
@@ -154,6 +223,7 @@ export default {
 // *  - receive new challenge: if targeted, replace our name with sender name
         case "newchallenge":
           // receive live or corr challenge
+          this.challenges.push(data.chall);
           break;
 // *  - receive "accept/withdraw/cancel challenge": apply action to challenges list
         case "acceptchallenge":
@@ -175,23 +245,19 @@ export default {
 // *  - receive "player connect": send all our current challenges (to him or global)
 // *    Also send all our games (live - max 1 - and corr) [in web worker ?]
 // *    + all our sent challenges.
-          this.players.push({name:data.name, id:data.uid});
+          this.players.push({name:"", id:0, sid:data.sid});
+          this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
           // TODO: si on est en train de jouer une partie, le notifier au nouveau connecté
           // envoyer aussi nos défis
           break;
 // *  - receive "player disconnect": remove from players list
         case "disconnect":
-          ArrayFun.remove(this.players, p => p.id == data.uid);
+          ArrayFun.remove(this.players, p => p.sid == data.sid);
           // TODO: also remove all challenges sent by this player,
           // and all live games where he plays and no other opponent is online
           break;
       }
     },
-    socketCloseListener: function() {
-      // connexion is reinitialized in store.js
-      this.st.conn.addEventListener('message', this.socketMessageListener);
-      this.st.conn.addEventListener('close', this.socketCloseListener);
-    },
     showGame: function(game) {
       // NOTE: if we are an observer, the game will be found in main games list
       // (sent by connected remote players)
@@ -201,11 +267,7 @@ export default {
     tryChallenge: function(player) {
       if (player.id == 0)
         return; //anonymous players cannot be challenged
-      this.newchallenge.players[0] = {
-        name: player.name,
-        id: player.id,
-        sid: player.sid,
-      };
+      this.newchallenge.to[0] = player.name;
       doClick("modalNewgame");
     },
 // *  - accept challenge (corr or live) --> send info to all concerned players
@@ -218,14 +280,14 @@ export default {
 // *    --> include challenge ID (so that opponents can delete the challenge too)
 // *    Also send to all connected players (only from me)
     clickChallenge: function(challenge) {
+      // TODO: also correspondance case (send to server)
       const index = this.challenges.findIndex(c => c.id == challenge.id);
-      const toIdx = challenge.to.findIndex(p => p.id == user.id);
-      const me = {name:user.name,id:user.id};
+      const toIdx = challenge.to.findIndex(name => name == this.st.user.name);
       if (toIdx >= 0)
       {
         // It's a multiplayer challenge I accepted: withdraw
         this.st.conn.send(JSON.stringify({code:"withdrawchallenge",
-          cid:challenge.id, user:me}));
+          cid:challenge.id, user:this.st.user.sid}));
         this.challenges.to.splice(toIdx, 1);
       }
       else if (challenge.from.id == user.id) //it's my challenge: cancel it
@@ -256,78 +318,117 @@ export default {
 //      if (this.settings.sound >= 1)
 //        new Audio("/sounds/newgame.mp3").play().catch(err => {});
 //    },
-    // Send new challenge (corr or live, cf. time control), with button or click on player
-    newChallenge: async function() {
-      const idxInVariants =
-        this.st.variants.findIndex(v => v.id == this.newchallenge.vid);
-      const vname = this.st.variants[idxInVariants].name;
+    // Load a variant file (TODO: should probably be global)
+    loadVariant: async function(vid, variantArray) {
+      const idxInVariants = variantArray.findIndex(v => v.id == vid);
+      const vname = variantArray[idxInVariants].name;
       const vModule = await import("@/variants/" + vname + ".js");
       window.V = vModule.VariantRules;
-      // checkChallenge side-effect = set FEN, and mainTime + increment in seconds
+      return vname;
+    },
+    // Send new challenge (corr or live, cf. time control), with button or click on player
+    newChallenge: async function() {
+      // TODO: put this "load variant" block elsewhere
+      const vname = this.loadVariant(this.newchallenge.vid, this.st.variants);
+      // checkChallenge side-effect = , and mainTime + increment in seconds
+      // TODO: should not be a side-effect but set here ; for received server challenges we do not have mainTime+increment
       const error = checkChallenge(this.newchallenge);
       if (!!error)
         return alert(error);
-      // Less than 3 days ==> live game (TODO: heuristic... 40 moves also)
-      const liveGame =
-        this.newchallenge.mainTime + 40 * this.newchallenge.increment < 3*24*60*60;
+      if (this.challenges.some(c => c.from.sid == this.st.user.sid && c.liveGame))
+      {
+        document.getElementById("modalNewgame").checked = false;
+        return alert("You already have a pending live challenge");
+        // TODO: better to just replace current challenge
+      }
       // Check that the players (if any indicated) are online
-      for (let p of this.newchallenge.to)
+      let chall = Object.Assign(
+        {},
+        this.newchallenge,
+        {
+          from: this.st.user,
+          added: Date.now(),
+        fen: this.newchallenge.fen || V.GenRandInitFen(),
+        variant: {id: this.newchallenge.vid, name: vname},
+        nbPlayers: this.newchallenge.nbPlayers,
+        to: [
+          {id: 0, name: this.newchallenge.to[0], sid: ""},
+          {id: 0, name: this.newchallenge.to[1], sid: ""},
+          {id: 0, name: this.newchallenge.to[2], sid: ""},
+        ],
+        timeControl: this.newchallenge.timeControl,
+      };
+      for (let p of chall.to)
       {
         if (p.name != "")
         {
           const pIdx = this.players.findIndex(pl => pl.name == p.name);
-          if (pIdx === -1)
+          // NOTE: id (server DB) and sid (socket ID).
+          // Anonymous players just have a socket ID.
+          // NOTE: for correspondance play we don't require players to be online
+          // (==> we don't have IDs, and no sid)
+          if (liveGame && pIdx === -1)
             return alert(p.name + " is not connected");
           p.id = this.players[pIdx].id;
           p.sid = this.players[pIdx].sid;
         }
       }
-      // TODO: clarify challenge format (too many fields for now :/ )
       const finishAddChallenge = (cid) => {
-        const chall = Object.assign(
-          {},
-          this.newchallenge,
-          {
-            id: cid,
-            from: this.st.user,
-            added: Date.now(),
-            vname: vname,
-          }
-        );
+        chall.id = cid || "c" + getRandString();
         this.challenges.push(chall);
         // Send challenge to peers
-        const chall = JSON.stringify({
+        let challSock =
+        {
           code: "newchallenge",
-          sender: {name:this.st.user.name, id:this.st.user.id, sid:this.st.user.sid},
-        });
-        if (this.newchallenge.to[0].id > 0)
+          chall: chall,
+          target: "",
+        };
+        const sendChallengeTo = (sid) => {
+          challSock.target = sid;
+          this.st.conn.send(JSON.stringify(challSock));
+        };
+        if (chall.to[0].id > 0)
         {
           // Challenge with targeted players
-          this.newchallenge.to.forEach(p => {
+          chall.to.forEach(p => {
             if (p.id > 0)
-              this.st.conn.send(Object.assign({}, chall, {receiver: p.sid}));
+              sendChallengeTo(p.sid);
           });
         }
         else
         {
-          // Open challenge: send to all connected players
-          this.players.forEach(p => { this.st.conn.send(chall); });
+          // Open challenge: send to all connected players (except us)
+          this.players.forEach(p => {
+            if (p.sid != this.st.user.sid) //only sid is always set
+              sendChallengeTo(p.sid);
+          });
         }
         document.getElementById("modalNewgame").checked = false;
       };
-      if (liveGame)
+      if (this.newchallenge.liveGame)
       {
         // Live challenges have cid = 0
-        finishAddChallenge(0);
+        finishAddChallenge();
       }
       else
       {
+        const chall = {
+          uid: req.body["from"],
+          vid: req.body["vid"],
+          fen: req.body["fen"],
+          timeControl: req.body["timeControl"],
+          nbPlayers: req.body["nbPlayers"],
+          to: req.body["to"], //array of IDs
+        };
         // Correspondance game: send challenge to server
         ajax(
           "/challenges/" + this.newchallenge.vid,
           "POST",
-          this.newchallenge,
-          response => { finishAddChallenge(cid); }
+          chall,
+          response => {
+            chall.id = response.cid;
+            finishAddChallenge();
+          }
         );
       }
     },