Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

105
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda