Home > Software design >  Javascript alternate player turn
Javascript alternate player turn

Time:07-31

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.

CodePudding user response:

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  

CodePudding user response:

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"...
}

CodePudding user response:

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

  • Related