React Wordle Game – JavaScript Exercise #9

Overview

In this exercise, you will be building a Wordle game using React. Players receive a collection of concealed words that they must identify by inputting letters. The game is successfully completed once all words have been correctly guessed.

Requirements for React Wordle Game

  • The game must have a minimum of 10 hidden words.
  • The game must track the number of correct and incorrect guesses.
  • The game must display a message when a player has won or lost.

Instructions for React Wordle Game

  1. Display a set of hidden words, each represented by underscores (e.g., “______”).
  2. Allow the player to enter a letter.
  3. If the letter is present in one or more of the hidden words, replace the corresponding underscores with the letter.
  4. If the letter is not present in any of the hidden words, mark it as an incorrect guess.
  5. Let the player keep guessing until they correctly guess all the words or exceed the allowed number of incorrect guesses.
  6. Display a message indicating whether the player has won or lost.

Bonus Requirements

  • Add a reset button that allows the player to start a new game.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Wordle game exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Wordle game exercise

import React, { useState } from 'react';

const words = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew', 'kiwi', 'lemon'];

const allowedIncorrectGuesses = 6;

const WordleGame = () => {
  const [hiddenWords, setHiddenWords] = useState(words);
  const [guesses, setGuesses] = useState([]);
  const [incorrectGuesses, setIncorrectGuesses] = useState(0);

  const handleGuess = (letter) => {
    const newGuesses = [...guesses, letter];
    setGuesses(newGuesses);

    let foundLetter = false;
    const newHiddenWords = hiddenWords.map((word) => {
      const letters = word.split('');
      const newLetters = letters.map((hiddenLetter) => {
        if (hiddenLetter === letter) {
          foundLetter = true;
          return letter;
        } else {
          return hiddenLetter;
        }
      });
      return newLetters.join('');
    });
    setHiddenWords(newHiddenWords);

    if (!foundLetter) {
      setIncorrectGuesses(incorrectGuesses + 1);
    }
  };

  const resetGame = () => {
    setHiddenWords(words);
    setGuesses([]);
    setIncorrectGuesses(0);
  };

  const gameWon = hiddenWords.every((word) => {
    return word.split('').every((letter) => {
      return guesses.includes(letter);
    });
  });

  const gameLost = incorrectGuesses >= allowedIncorrectGuesses;

  const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');

  return (
    <div>
      <h1>React Wordle</h1>
      <p>Guess the hidden words by clicking on the letters below!</p>
      {hiddenWords.map((word) => {
        return <div key={word}>{word.split('').map((letter) => {
          if (guesses.includes(letter)) {
            return letter;
          } else {
            return '_';
          }
        })}</div>;
      })}
      <p>Incorrect guesses: {incorrectGuesses}</p>
      {!gameWon && !gameLost && <div>
        {alphabet.map((letter) => {
          return <button key={letter} onClick={() => handleGuess(letter)} disabled={guesses.includes(letter)}>{letter}</button>
        })}
      </div>}
      {gameWon && <div>
        <p>Congratulations, you won!</p>
        <button onClick={resetGame}>Play Again</button>
      </div>}
      {gameLost && <div>
        <p>Sorry, you lost.</p>
        <button onClick={resetGame}>Play Again</button>
      </div>}
    </div>
  );
};

export default WordleGame;

In this exercise, we created a React Wordle game that allows players to guess hidden words by clicking on alphabet buttons. We keep track of the hidden words, the player’s guesses, and the number of incorrect guesses using React state.. We also added a reset button to allow players to start a new game.

This exercise was a good introduction to using React state and conditionally rendering components based on the game state. It also gave us practice with mapping over arrays to create buttons and rendering dynamic content based on user input.

Overall, this exercise provided a fun and interactive way to learn React concepts and practically apply them. With further customization and enhancement, this game can be made even more engaging and challenging.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you’ll be well on your way to becoming a skilled React developer!

Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!

Leave a Comment

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

Scroll to Top