Bootcamp
Search…
7.ICE.3: React Cards

Introduction

Implement a 2-player High Card game using React. In each round of High Card each player draws 1 card from the deck and the player with the highest card wins.

Setup

  1. 2.
    Copy getRandomIndex, shuffleCards and makeDeck functions from Module 1.3: High Card DOM and paste them into src/App.jsx below the import statements
  2. 3.
    Add useState to imports like in this example so we can use useState in the App component
  3. 4.
    Copy the App component starter code below into App.jsx. The code initialises the card deck state array variable and deals cards into player hands.
export default function App() {
// Set the default value of the deck
const [cardDeck, setCardDeck] = useState(shuffleCards(makeDeck()));
​
// Set the default player hand as empty
const [playerHand, setPlayerHand] = useState([]);
​
// Deal 2 cards into the player's hand and update the deck
const dealCards = () => {
const hand = [cardDeck.pop(), cardDeck.pop()];
setPlayerHand(hand);
setCardDeck([...cardDeck]);
};
​
// Render cards in the player hand
// Note that when this renders the first time and the hand is
// empty, it does not require a special condition.
const handElems = playerHand.map(({ name, suit }) => (
<div>
{name}
{suit}
</div>
));
​
return (
<div>
<div>
<h3>Cards:</h3>
{handElems}
</div>
<p>
<button onClick={dealCards}>Deal</button>
</p>
</div>
);
}

Base

Create a game of High Card by comparing the 2 cards drawn from the deck and determining a winner.

Comfortable

  1. 1.
    Update the game to add a Play Hand button. The user can continue to deal cards to themselves with the Deal button.
  2. 2.
    When the user clicks the Play Hand button the computer is dealt the same amount of cards in the user's hand, and the player with the highest card in both hands wins.
  3. 3.
    The game ends when the deck is out of cards. When the deck is out of cards, reset the game to the starting values.

More Comfortable

Update a scoreboard when the deck runs out of cards. The player who had more winning hands gets 1 point.