22 - Word Scramble Game with Timer and Score

Description

Develop a web application or React app for a word scramble game with these features:

  • Presents a scrambled word.

  • Allows users to guess the word by typing letters.

  • Provides a timer that counts down as users play.

  • Displays the current score based on correct guesses and remaining time.

  • Optionally, add features like:

    • Difficulty levels with varying word lengths and scramble complexity.

    • Hint button to reveal a letter in the scrambled word.

    • Leaderboard or score history for tracking performance.

Algorithm

  1. Data Management:

    • Define initial state variables for:

      • scrambledWord: The randomly generated scrambled word.

      • answerWord: The original unscrambled word.

      • guessedLetters: Array of already guessed letters.

      • score: Current game score.

      • timer: Remaining time in seconds.

  2. Game Logic:

    • Generate a random word from a word list.

    • Scramble the chosen word to create the scrambledWord.

    • Start the timer and update it periodically.

    • Check user input against the answerWord to validate guesses.

    • Calculate score based on correct guesses and remaining time.

  3. User Interaction:

    • Accept user input for guessing letters.

    • Update the guessedLetters state based on user input.

    • Display feedback for correct and incorrect guesses.

  4. Timer and Score Display:

    • Render the countdown timer prominently.

    • Update and show the current score dynamically.

    • End the game and show final score when the timer reaches zero.

  5. Optional Features:

    • Implement difficulty levels by adjusting word length and scrambling algorithm.

    • Add a hint button that reveals a random letter in the scrambled word for a cost.

    • Store and display leaderboards or individual score history for repeated play.

Code

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

const words = ['apple', 'banana', 'computer', 'dinosaur', 'elephant'];

function WordScrambleGame() {
  const [scrambledWord, setScrambledWord] = useState('');
  const [answerWord, setAnswerWord] = useState('');
  const [guessedLetters, setGuessedLetters] = useState([]);
  const [score, setScore] = useState(0);
  const [timer, setTimer] = useState(60); // Adjust default timer value

  useEffect(() => {
    const newWord = words[Math.floor(Math.random() * words.length)];
    setScrambledWord(shuffle(newWord));
    setAnswerWord(newWord);
  }, []);

  useEffect(() => {
    const interval = setInterval(() => {
      if (timer > 0) {
        setTimer(timer - 1);
      } else {
        clearInterval(interval);
      }
    }, 1000); // Update timer every second
    return () => clearInterval(interval);
  }, [timer]);

  const handleGuess = (letter) => {
    if (!guessedLetters.includes(letter)) {
      setGuessedLetters([...guessedLetters, letter]);
      if (answerWord.includes(letter)) {
        const newScore = score + (timer * 2); // Increase score based on remaining time
        setScore(newScore);
      }
    }
  };

  const isGuessed = (letter) => guessedLetters.includes(letter);

  const isSolved = () => guessedLetters.includes(answerWord.split('').every(letter => isGuessed(letter)));

  return (
    <div className="word-scramble-game">
      <h1>Scrambled Word: {scrambledWord}</h1>
      <div className="guessed-letters">
        {guessedLetters.map((letter) => <span key={letter}>{letter}</span>)}
      </div>
      <input type="text" maxLength={1} onChange={(event) => handleGuess(event.target.value.toLowerCase())} />
      <div className="timer">Time remaining: {timer}</div>
      <div className="score">Score: {score}</div>
      {isSolved() ? <p>Congratulations! You guessed the word.</p> : null}
    </div>
  );
}

export default WordScrambleGame;

Explanation

  • State Variables:

    • scrambledWord: Stores the scrambled version of the current word.

    • answerWord: Stores the original, unscrambled word.

    • guessedLetters: An array holding letters already guessed by the user.

    • score: The current game score.

    • timer: The remaining time in seconds.

  • useEffect Hooks:

    • The first useEffect runs once on component mount and:

      • Selects a random word from the words array.

      • Scrambles the word using the shuffle function (not shown, but you can implement a shuffling algorithm).

      • Sets the initial scrambledWord and answerWord states.

    • The second useEffect manages the timer:

      • Sets up an interval to decrement the timer state every second.

      • Clears the interval when the timer reaches zero.

  • handleGuess Function:

    • Takes a letter as input.

    • Adds the letter to guessedLetters if it hasn't been guessed yet.

    • Checks if the letter is in the answerWord:

      • If so, increases the score based on remaining time.

  • isGuessed and isSolved Functions:

    • isGuessed checks if a letter has already been guessed.

    • isSolved determines if all letters in the answerWord have been guessed.

  • JSX:

    • Renders the scrambled word, guessed letters, input field, timer, score, and a congratulatory message if the word is solved.

Additional Notes

  • Remember to implement the shuffle function for scrambling words.

  • Consider adjusting the default timer value and score calculation logic based on your preferences.

Last updated