Categories
React Projects

Create a Hangman 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 hangman 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 hangman

with NPM to create our React project.

Create the Hangman Game

To create the hangman game, we write:

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

export default function App() {
  const [answer] = useState("hangman");
  const [guesses, setGuesses] = useState([]);
  const [guessLetter, setGuessLetter] = useState("");
  const guessesLeft = useMemo(() => {
    return (
      6 -
      guesses.filter((g) => {
        return !answer.includes(g);
      }).length
    );
  }, [answer, guesses]);

  const lettersToShow = useMemo(() => {
    return answer.split("").map((a) => {
      if (guesses.includes(a)) {
        return a;
      }
      return "_";
    });
  }, [answer, guesses]);

  const isWin = useMemo(() => {
    const includedLetters = guesses.filter((g) => {
      return answer.includes(g);
    });
    return answer.split("").every((a) => {
      return includedLetters.includes(a);
    });
  }, [answer, guesses]);

  const guess = (e) => {
    e.preventDefault();
    const formValid = /[a-z]{1}/.test(guessLetter);
    if (!formValid) {
      return;
    }
    setGuesses((guesses) => [...guesses, guessLetter]);
    setGuessLetter("");
  };

  const reset = () => {
    setGuesses([]);
    setGuessLetter("");
  };

  if (isWin) {
    return (
      <div className="App">
        you win
        <button type="button" onClick={reset}>
          reset
        </button>
      </div>
    );
  } else {
    if (guessesLeft > 0) {
      return (
        <div>
          <p>guesses left: {guessesLeft}</p>
          <form onSubmit={guess}>
            <div>
              <label>guess</label>
              <input
                value={guessLetter}
                onChange={(e) => setGuessLetter(e.target.value)}
              />
            </div>
            <button type="submit">guess</button>
          </form>
          {lettersToShow.map((l, i) => {
            return <span>{l}</span>;
          })}
        </div>
      );
    } else {
      return (
        <div>
          you lost
          <button type="button" onClick={reset}>
            reset
          </button>
        </div>
      );
    }
  }
}

The answer state has the right answer.

guesses has an array of letters we’ve guessed.

guessLetter has the letter we typed into the guess input.

Next, we create a few variables with useMemo .

We compute the guessesLeft in the callback by subtracting the number of guessed letters that aren’t in the answer word from 6.

We watch answer and guesses so that the returned value will be updated whenever they’re updated.

Likewise, we create the lettersToShow state by splitting the answer into letters.

Then if the guessed letter is in answer , we return the letter.

Otherwise, we return an underscore.

This lets us display what’s guessed correctly so far.

The isWin variable has a boolean value to indicate whether the player won or not.

We create includedLetters to get the letters that has the letters in the guesses array that are included in answer .

And we return the if every letter in includedLetters are in the split answer string.

This lets the player know whether all the letters in the answer word has been guessed.

The guess function lets the player enter the guess.

In it, we call e.preventDefault() to do client-side submission.

Then we check if the player entered a letter into the input box before append the guessed letter to the guesses array.

To do that, we call setGuesses with a callback that returns an array with the existing guesses and the guessLetter with the latest letter guessed.

We also set setGuessLetter to an empty string to empty the input box.

The reset function reset guesses and guessLetter to their original values.

Then we check is isWin is true .

If it is, then we render the ‘you win’ message and a reset button.

The button calls reset when we click it.

Otherwise, if guessLeft is bigger than 0, this means the player can keep guessing.

We render the guessesLeft value and the form.

In the form, we render an input to set guessLetter .

The onChange prop has a function that gets the e.target.value , which has the inputted value, to set it.

The guess function is run when we click guess because of the onSubmit prop.

Below that, we display the lettersToShow .

In the eise block, we show ‘you lost’ ti the player is guessesLeft is 0, which means no more guesses are left.

We also show the reset button there.

Conclusion

We can create a hangman game easily 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 *