Be more selective about when to display buttons for joining a team
authorCarl Worth <cworth@cworth.org>
Sat, 6 Jun 2020 11:17:53 +0000 (04:17 -0700)
committerCarl Worth <cworth@cworth.org>
Sat, 6 Jun 2020 11:46:51 +0000 (04:46 -0700)
Specifically, before the first move, we never want any buttons,
(instead, the first player will commit to a team by making a move).

After the first move, there are two cases:

1. A player is already on a team:

In this case we want only one button, labeled "Switch" to
change to the other team.

2. A player is just spectating:

This is the only case where we need to display two buttons,
one labeled "Join X" and one labeled "Join O".

tictactoe/tictactoe.jsx

index 49c6005c38fe395c610502853f1ec69ab28d3438..ca0bce3fd4985bf8636893cbfeae92ea4235508b 100644 (file)
@@ -91,15 +91,52 @@ function GameInfo(props) {
   );
 }
 
+function TeamButton(props) {
+  return <button className="inline"
+                 onClick={() => props.game.join_team(props.team)}>
+           {props.label}
+         </button>;
+}
+
+function TeamChoices(props) {
+  let other_team;
+  if (props.player.team === "X")
+    other_team = "O";
+  else
+    other_team = "X";
+
+  if (props.player.team === "") {
+    if (props.first_move) {
+      return null;
+    } else {
+      return [
+        <TeamButton key="X" game={props.game} team="X" label="Join X" />,
+        " ",
+        <TeamButton key="O" game={props.game} team="O" label="Join O" />
+      ];
+    }
+  } else {
+    return <TeamButton game={props.game} team={other_team} label="Switch" />;
+  }
+}
+
 function PlayerInfo(props) {
   if (! props.player.id)
     return null;
 
+  const choices = <TeamChoices
+                    game={props.game}
+                    first_move={props.first_move}
+                    player={props.player}
+                  />;
+
   return (
     <div className="player-info">
       <h2>Players</h2>
       {props.player.name}
       {props.player.team ? ` (${props.player.team})` : ""}
+      {props.first_move ? "" : " "}
+      {choices}
       {props.opponents.map(opponent => (
         <span key={opponent.id}>
           {", "}
@@ -332,15 +369,12 @@ class Game extends React.Component {
       />,
       <PlayerInfo
         key="player-info"
+        game={this}
+        first_move={first_move}
         player={state.player_info}
         opponents={state.opponent_info}
       />,
       <div key="game" className="game">
-        <button className="inline"
-                onClick={() => this.join_team('X')}>Join Team X</button>
-        {" "}
-        <button className="inline"
-                onClick={() => this.join_team('O')}>Join Team O</button>
         <div>{status}</div>
         <div className="game-board">
           <Board