tictactoe: Adapt to new server event type: game-state
authorCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 17:52:19 +0000 (10:52 -0700)
committerCarl Worth <cworth@cworth.org>
Mon, 1 Jun 2020 17:52:19 +0000 (10:52 -0700)
Previously, when a client joined a game in progress the server would
send all previous moves as "move" events (just the same as if a player
were making those moves live).

The server was recently changed to instead a single "game-state" event
in this case, (which also does contain the entire move history). So
when we receive that, we reset the game state, then replay the moves
from that history.

tictactoe/tictactoe.jsx

index 849a6f2a113f6141ceaf1e33927bb10d2bbadd23..17c966dc9453a2ffebdb2581b7a696be9ba691b0 100644 (file)
@@ -25,6 +25,16 @@ events.addEventListener("move", event => {
   window.game.receiveMove(square);
 });
 
+events.addEventListener("game-state", event => {
+  const state = JSON.parse(event.data);
+
+  window.game.resetState();
+
+  for (let square of state.moves) {
+    window.game.receiveMove(square);
+  }
+});
+
 function Square(props) {
   return (
     <button className="square" onClick={props.onClick}>
@@ -95,6 +105,18 @@ class Game extends React.Component {
     return fetch_post_json("move", { square: i });
   }
 
+  resetState() {
+    this.setState({
+      history: [
+        {
+          squares: Array(9).fill(null)
+        }
+      ],
+      stepNumber: 0,
+      xIsNext: true
+    });
+  }
+
   receiveMove(i) {
     const history = this.state.history.slice(0, this.state.stepNumber + 1);
     const current = history[history.length - 1];