]> git.cworth.org Git - lmno.games/blobdiff - tictactoe/tictactoe.jsx
tictactoe: Adapt to new server event type: game-state
[lmno.games] / 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];