How to update property inside object, but turn by turn(like a game), using reactJs?

Viewed 30

I am making a simple game using reactJs. But i am facing a problem with that. I want to alternate the turns for the players to generate a random number b/w 1 to 10 and that generated random number should get stored inside of each player's object.

Here is my code

export default function SetPlayers(){
const [playerCount, setPlayerCount] = useState<number>(2);
const [valid, setValid] = useState<boolean>(true);
const [count, setCount] = useState();
const [turn, setTurn] = useState<any>({});

useEffect(()=> {
for (let i = 1; i <= playerCount; i++) {
turn[`Player${i}`] = {
initialValue : count
}
console.log(turn);
}}, [playerCount])

function setPlayer (event : any) => {
const {value} = event.target;
if(value > 4 || value < 2){ //only 4 players are allowed with a minimum of 2 players
setValid(false);
}
setPlayerCount(value);
}

function randomNumberGenerate(min: any, max: any) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};


return(
<TextField type="number" onChange={setPlayers} value={playerCount} />
<Button onClick = {setCount(randomNumberGenerate(1, 10))}>Generate</Button>
)};

I want to store the random number generated so far onClick event, into each turn {} object, one turn by turn. for eg, say Player 1 generates the number(say 4) then the count should only reflect inside the Player1's object.Rest all other objects should have count set to 0/null. Then we again click on the button to generate the number, then property count, should only update inside of the player 2's object, (but retaining the player1's count as before and the count for Player 3 & Player 4 is null/0).

In the same manner if we press the button 4 times, it should update count property inside of the player object one by one and into the loop.

It should give the visualisation of 4 players generating random numbers turn by turn dynamically.

Player 1 -> Player 2 -> Player 3 -> Player 4 -> Player 1 -> Player 2 -> Player 3 ....

How could I implement this functionality in code. All suggestions are welcome :)

1 Answers

First of all, I fixed some obvious TS errors (and fixed some of the existing logic). Please, do not use any. Also I believe you want to pass numbers to the randomNumberGenerate function and count must be a number. I changed used components to regular html tags, because you did not provide the other code. randomNumberGenerate function can be extracted since it does not depend on the component. valid and setTurn variables are not used at all.

Decide where do you want to store data of players. Now it does not seem obvious to me if what and where do you want to store.

import { useEffect, useState } from "react";

function randomNumberGenerate(min: number, max: number) {
 return Math.floor(Math.random() * (max - min + 1)) + min;
};

export default function SetPlayers() {
 const [playerCount, setPlayerCount] = useState<number>(2);
 const [valid, setValid] = useState<boolean>(true);
 const [count, setCount] = useState<number>();
 const [turn, setTurn] = useState<any>({});

 useEffect(() => {
  for (let i = 1; i <= playerCount; i++) {
   turn[`Player${i}`] = {
    initialValue: count
   }
   console.log(turn);
  }
 }, [playerCount])

 function setPlayer(event: React.FormEvent<HTMLInputElement>) {
  const { value: playerCountInputValueString } = event.currentTarget;
  const playerCountInputValue = parseInt(playerCountInputValueString);
  const isPlayerCountInputValueValid = !(playerCountInputValue > 4 || playerCountInputValue < 2); // only 4 players are allowed with a minimum of 2 players
  setValid(isPlayerCountInputValueValid);
  isPlayerCountInputValueValid && setPlayerCount(playerCountInputValue); // I believe you only want to set playerCount if its value is valid, so set only if input value is valid.
 }

 function handleRandomNumberGeneratorButtonClick() {
  const randomNumber = randomNumberGenerate(1, 10);
  setCount(randomNumber);
 }

 return (
  <>
   <input type="number" onChange={setPlayer} value={playerCount} />
   <button onClick={handleRandomNumberGeneratorButtonClick}>Generate</button>
  </>
 )
};
Related