Add Ambiguous. Fix a few issues with FEN generation / options
[xogo.git] / server.js
index 0382e37..dc8bd97 100644 (file)
--- a/server.js
+++ b/server.js
@@ -7,6 +7,7 @@ const wss = new WebSocket.Server({
 
 let challenges = {}; //variantName --> socketId, name
 let games = {}; //gameId --> gameInfo (vname, fen, players, options, time)
+let moveHash = {}; //gameId --> set of hashes seen so far
 let sockets = {}; //socketId --> socket
 const variants = require("./variants.js");
 const Crypto = require("crypto");
@@ -34,16 +35,14 @@ function initializeGame(vname, players, options) {
 
 // Provide seed in case of, so that both players initialize with same FEN
 function launchGame(gid) {
+  moveHash[gid] = {};
   const gameInfo = Object.assign(
-    {seed: Math.floor(Math.random() * 1984), gid: gid},
+    {seed: Math.floor(Math.random() * 19840), gid: gid},
     games[gid]
   );
   // players array is supposed to be full:
-  for (const p of games[gid].players) {
-    send(p.sid,
-         "gamestart",
-         Object.assign({randvar: p.randvar}, gameInfo));
-  }
+  for (const p of games[gid].players)
+    send(p.sid, "gamestart", gameInfo);
 }
 
 function getRandomVariant() {
@@ -135,11 +134,10 @@ wss.on("connection", (socket, req) => {
             const allrand = games[obj.gid].rematch.every(r => r == 2);
             if (allrand)
               vname = getRandomVariant();
-            games[obj.gid].players.forEach(p =>
-              p.randvar = allrand ? true : false);
+            games[obj.gid].players.forEach(p => p.randvar = allrand);
             const gid = initializeGame(vname,
-                           games[obj.gid].players.reverse(),
-                           games[obj.gid].options);
+                                       games[obj.gid].players.reverse(),
+                                       games[obj.gid].options);
             launchGame(gid);
           }
         }
@@ -193,6 +191,13 @@ wss.on("connection", (socket, req) => {
         break;
       // Relay a move + update games object
       case "newmove":
+        // NOTE: still potential racing issues, but... fingers crossed
+        const hash = Crypto.createHash("md5")
+                     .update(JSON.stringify(obj.fen))
+                     .digest("hex");
+        if (moveHash[hash])
+          break;
+        moveHash[hash] = true;
         games[obj.gid].fen = obj.fen;
         games[obj.gid].time = Date.now(); //update timestamp in case of
         const playingWhite = (games[obj.gid].players[0].sid == sid);