Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
Alternate between user and computer turn (react.js card game)

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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]);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!