Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda