Given 4 players in a hearts card game where players play anticlockwise :p1 -> p2 -> p3 -> p4.
If p3 has to play first, select card for p3 and p4, then wait for user to select card, then resume to p2 to select card.
If p4 starts, select for p4, wait for p1 and resume for p2 and p3...
This is the alternation I am trying to figure out.
Example: computer chooses
{p2: ['A', '♣'], p3:['2', '♣'], p4:['J', '♣'] }
and player chooses
p1:['Q', '♣']
In this turn, p3 starts ,then p4, then wait for p1 (user) and finally resume for p2
I tried having two states:
const [playerCard, setplayerCard] = useState(null)
const [compCards, setCompCard] = useState(null)
but am having difficulty in switching between the two. I also tried generators but am new to that topic. Any code or pseudocode that can be of guidance will be appreciated.
You will have to define a bunch of functions (just like any game), whether or not the goal is reached, the current state and function to update the current state, the current turn, and a list of a actions that can be completed based on the current state of the game.
const enum PLAYER_TYPES {
COMPUTER, HUMAN,
}
const gameConfig = [
PLAYER_TYPES.HUMAN,
PLAYER_TYPES.COMPUTER,
PLAYER_TYPES.COMPUTER,
PLAYER_TYPES.COMPUTER,
];
const nextTurn = (turn) => {
return (turn % gameConfig.length) + 1;
};
const Game = () => {
const [turn, setTurn] = useState(1);
// Define actions that can happen based on the state of the game
const actions = (turn) => {
if (gameIsOver()) {
return;
}
const type = gameConfig[turn - 1];
let choice;
switch(type) {
case PLAYER_TYPES.HUMAN: {
choice = await userChoice(turn);
break;
}
case PLAYER_TYPES.COMPUTER: {
choice = aiChoice(turn);
break;
}
}
setCards(turn, choice);
setTurn(nextTurn(turn));
};
// Run the action for this turn
useEffect(() => {
actions(turn);
}, [turn]);
};