On update + clocks thinking
[vchess.git] / client / src / utils / storage.js
index eb04078..8605158 100644 (file)
@@ -1,5 +1,4 @@
 import { extractTime } from "@/utils/timeControl";
-import { shuffle } from "@/utils/alea";
 
 // TODO: show game structure
 //const newItem = [
@@ -79,10 +78,6 @@ export const GameStorage =
   // localStorage:
   init: function(o)
   {
-    // NOTE: when >= 3 players, better use an array + shuffle for mycolor
-    const mycolor = (Math.random() < 0.5 ? "w" : "b");
-    // Shuffle players order (white then black then other colors).
-    const players = shuffle(o.players);
     // Extract times (in [milli]seconds), set clocks, store in localStorage
     const tc = extractTime(o.timeControl);
 
@@ -91,9 +86,8 @@ export const GameStorage =
     {
       gameId: o.gameId,
       vname: o.vname,
-      mycolor: mycolor,
       fenStart: o.fenStart,
-      players: players,
+      players: o.players,
       timeControl: o.timeControl,
       increment: tc.increment,
       mode: "live", //function for live games only
@@ -114,23 +108,33 @@ export const GameStorage =
   },
 
   // localStorage:
-  // TODO: also option to takeback a move ? Is fen included in move ?
+  // TODO: also option to takeback a move ?
   // NOTE: for live games only (all on server for corr)
-  update: function(fen, moves, clocks, started, score)
+  update: function(o) //move, clock, initime, score, colorIdx
   {
+    // TODO: finish this --> colorIdx must be computed before entering the function
     let gameState = JSON.parse(localStorage.getItem("gameState"));
-    if (!!fen)
+    if (!!o.move)
     {
-      gameState.moves = moves;
-      gameState.fen = fen;
-      gameState.clocks = clocks;
+      // https://stackoverflow.com/a/38750895
+      const allowed = ['appear', 'vanish', 'start', 'end'];
+      const filtered_move = Object.keys(o.move)
+        .filter(key => allowed.includes(key))
+        .reduce((obj, key) => {
+          obj[key] = raw[key];
+          return obj;
+        }, {});
+      gameState.moves.push(filtered_move);
+      gameState.fen = o.move.fen;
+      const colorIdx = ["w","b","g","r"][o.move.color];
+      gameState.clocks[colorIdx] = o.move.clock;
     }
-    if (!!started)
-      gameState.started = started;
-    if (!!score)
-      gameState.score = score;
+    if (!!o.initime) //just a flag (true)
+      gameState.initime = Date.now();
+    if (!!o.score)
+      gameState.score = o.score;
     localStorage.setItem("gameState", JSON.stringify(gameState));
-    if (!!score && score != "*")
+    if (!!o.score && o.score != "*")
       transferToDb(); //game is over
   },