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

103
Vistas
Javascript alternate player turn

I am currently working on a board game like chess.

I can't seem to make alternate turn work.

const clickPiece = (e: React.MouseEvent) => {
    const element = e.target as HTMLElement;
    const shogiBoard = shogiBoardRef.current;
    let steps = 1;

    if (steps % 2 === 1) {
      setActivePlayer(Player.US);
      steps++;
    } else if (steps % 2 === 0) {
      setActivePlayer(Player.ENEMY);
      steps++;
    }

    if (element.classList.contains("shogiPiece") && shogiBoard && activePlayer) {
      const takeX = Math.floor((e.clientX - shogiBoard.offsetLeft) / CELL_SIZE);
      const takeY = Math.abs(Math.ceil((e.clientY - shogiBoard.offsetTop - BOARD_SIZE) / CELL_SIZE));
      setTakePosition({
        x: takeX,
        y: takeY,
      });

      const x = e.clientX - CELL_SIZE / 2;
      const y = e.clientY - CELL_SIZE / 2;
      element.style.position = "absolute";
      element.style.left = `${x}px`;
      element.style.top = `${y}px`;

      setActivePiece(element);
    }
  };

activePlayer initially Player.US which comes from an enum:

export enum Player {
  ENEMY,
  US,
}

activePlayer useState:

const [activePlayer, setActivePlayer] = useState<Player>(Player.US);

For me to alternate turns seemed the easiest when grabbing a piece, check which player is up then change, tried it with increasing the number of steps and check for remainder but it is not working.

Thank you in advance for the suggestions and help.

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

The root cause your code is not working is how you are using step.

Step is part of your application's state, so this should be an state, not a simple variable. Your are actually resetting step = 1 in each render

First define [step, setStep] using useState:

const [step, setStep] = useState<number>(1); // instead of let steps = 1

and then update the step like this:

setStep(i => i+1) // instead of steps++
about 4 years ago · Santiago Trujillo Denunciar

0

This is because you if condition is wrong !

Change your if statement to this:

if (steps % 2 === 0) {   
     setActivePlayer(Player.ENEMY);
      steps++;
 } else {
     setActivePlayer(Player.US);
     steps++;
 }

This will work

about 4 years ago · Santiago Trujillo Denunciar

0

You can use this function to toggle the active player: check which is the current player and then set the other one:

TS Playground

import {useCallback, useState} from 'react';

enum Player { ENEMY, US }

function Component () {
  const [activePlayer, setActivePlayer] = useState<Player>(Player.US);

  const setAlternatePlayer = useCallback(
    () => setActivePlayer(player => player === Player.US ? Player.ENEMY : Player.US),
    [],
  );

  // Use function "setAlternatePlayer"...
}
about 4 years ago · Santiago Trujillo 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