Categories
React Projects

Create a Hi-Low Card Game with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a hi-low card game with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app hi-low-card-game

with NPM to create our React project.

Create the Hi-Low Card Game

To create the hi-low card game, we write:

import React, { useEffect, useState } from "react";

const suits = ["diamonds", "clubs", "hearts", "spades"];
const values = ["ace", 2, 3, 4, 5, 6, 7, 8, 9, 10];
const initCards = [];
for (const s of suits) {
  for (const v of values) {
    initCards.push(`${s}_${v}`);
  }
}

export default function App() {
  const [score, setScore] = useState(0);
  const [cards, setCards] = useState(
    [...initCards].sort(() => Math.random() - 0.5)
  );
  const [drawnCards, setDrawnCards] = useState([]);
  const [guess, setGuess] = useState("lower");

  const draw = (e) => {
    e.preventDefault();
    setCards((cards) => cards.slice(0, cards.length - 1));
    setDrawnCards((drawnCards) => [...drawnCards, cards[cards.length - 1]]);
  };

  useEffect(() => {
    const indexLastCard = initCards.indexOf(drawnCards[drawnCards.length - 2]);
    const indexDrawnCard = initCards.indexOf(drawnCards[drawnCards.length - 1]);

    if (
      (indexLastCard < indexDrawnCard && guess === "higher") ||
      (indexLastCard > indexDrawnCard && guess === "lower")
    ) {
      setScore((score) => score + 1);
    }
  }, [drawnCards, guess, cards]);

  return (
    <div className="App">
      <form onSubmit={draw}>
        <select value={guess} onChange={(e) => setGuess(e.target.value)}>
          <option>lower</option>
          <option>higher</option>
        </select>
        <button type="submit">guess</button>
      </form>
      <p>score: {score}</p>
      <p>last drawn card</p>
      {drawnCards[drawnCards.length - 2] && (
        <img
          alt="last drawn card"
          src={`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
            drawnCards[drawnCards.length - 2]
          }.svg`}
        />
      )}

      <p>currently drawrn card</p>
      {drawnCards[drawnCards.length - 1] && (
        <img
          alt="currently drawn card"
          src={`https://tekeye.uk/playing_cards/images/svg_playing_cards/fronts/${
            drawnCards[drawnCards.length - 1]
          }.svg`}
        />
      )}
    </div>
  );
}

We have the suits and values arrays which are used to create the initCards array with all the card values.

Then we define the score , cards , drawnCartds , and guess states.

score has the player’s score.

cards have the cards that haven’t been drawn yet.

drawnCards have the drawn cards.

guess has the guess value.

Next, we defined the draw function.

Inside it, we call e.preventDefault() to let us do client-side submission.

Then we call setCards to draw the cards by call slice to get rid of the last entry from cards .

Also, we update the drawnCards state by passing in a callback that returns an array with the existing drawnCards entry and the last card from cards .

Next, we have the useEffect hook that gets the index of the last drawn card stored in indexLastCard .

And we also have the index of the currently drawn card stored in indexDrawnCard .

Then we see if the guess value matches the comparison of the magnitude of the last drawn card and the currently drawn card.

We can compare by their indexes since initCards have the cards in order from smallest to largest.

If the condition is true , then we call setScore to increment the score by 1.

Next, we define the form with the select dropdown to let us choose lower or higher.

We get the selected value with value and set the value with the onChange callback.

onSubmit is set to submit so we run it when we click on guess.

Below that, we display the score .

Then we display the last drawn card and currently drawn card by getting the index of drawnCards .

Conclusion

We can create a hi-low card game with React and JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *