Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
How to stop game, after the player wins in [XO game] with react?

I create this game with React. I want to finish the game after the first player wins an XO game in React. In other words: After the first player wins, the next player can not continue the game and the game ends. this is my code:

function App() {
    const [state,setstate]=useState({
        player: "CIRCLE",
        positions: [
            'EMPTY', 'EMPTY','EMPTY',
            'EMPTY', 'EMPTY','EMPTY',
            'EMPTY', 'EMPTY','EMPTY',
        ]
    })

   
    // mark X or O
    function takeTurn(position) {
        const positions=[...state.positions];
        
        positions[position] = state.player;

        setstate({
            player:state.player === 'CIRCLE' ? 'CROSS' : 'CIRCLE',
            positions,
        })
    }


    return(
        <div >
            <div className="player"> Player :  [{state.player}] </div>
          
            <div  className="total">
                <Square position={0}  value={state.positions[0]} takeTurn={takeTurn}  />            
                <Square position={1}  value={state.positions[1]} takeTurn={takeTurn}  />            
                <Square position={2}  value={state.positions[2]} takeTurn={takeTurn}   />            
                <Square position={3}  value={state.positions[3]} takeTurn={takeTurn}  />            
                <Square position={4}  value={state.positions[4]} takeTurn={takeTurn}  />            
                <Square position={5}  value={state.positions[5]} takeTurn={takeTurn}  />            
                <Square position={6}  value={state.positions[6]} takeTurn={takeTurn}  />            
                <Square position={7}  value={state.positions[7]} takeTurn={takeTurn}  />            
                <Square position={8}  value={state.positions[8]} takeTurn={takeTurn}  /> 
            </div>
            <div className="caption">
                Winner = &nbsp; {winner && <Result winner={winner} />}    
            </div>
            <div className="reset"><button onClick={reset} >Reset</button></div>
        </div>
    )
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So it looks like you need a few things.

  • A way to determine if there is a winner
  • The definition of the winner variable

You could add the winner to your state, and change the winner calculation line to:

Winner = &nbsp; {state.winner && <Result winner={state.winner} />}

To calculate the winner, the app needs to know the winning lines and check if the same symbol is in all 3:

function calculateWinner(positions) {
    const lines = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    for (let i = 0; i < lines.length; i++) {
        const [a, b, c] = lines[i];
        if (positions[a] && positions[a] === positions[b] && positions[a] === positions[c]) {
            return positions[a];
        }
    }
    return null;
}

You can then use this in your takeTurn function to return early if there is already a winner and therefore not update the board, and also to recalculate if there is a winner each time:

function takeTurn(position) {
    const positions = [...state.positions];
    if (!state.winners) return;

    positions[position] = state.player;

    setstate({
        player: state.player === 'CIRCLE' ? 'CROSS' : 'CIRCLE',
        positions,
        winner: calculateWinner(positions)
    });
}

With functional components, it is also a best practice to not have a single state object, but to have one for each property you would usually have. This makes it easier to set and manage each on properly, so you may consider changing your state code to:

const [player, setPlayer] = useState('CIRCLE');
const [positions, setPositions = useState([
        'EMPTY', 'EMPTY','EMPTY',
        'EMPTY', 'EMPTY','EMPTY',
        'EMPTY', 'EMPTY','EMPTY',
      ]);
const [winner, setWinner] = useState(null);

and update the setter code accordingly.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda