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 :)