22 - Word Scramble Game with Timer and Score

Description

Create a React application that presents a word scramble game with a timer and score. The game should present a scrambled word, allow users to guess the word by typing letters, provide a timer that counts down as users play, and display the current score based on correct guesses and remaining time.

Algorithm

  1. Create a state variable to store the scrambled word, user guesses, timer, and score.

  2. Define a function to handle user input (letter guesses).

  3. Define a function to check if the user's guess is correct.

  4. Define a function to update the timer and score.

  5. Render the scrambled word, user input field, timer, and score.

Classes

  • WordScramble: A component that represents the word scramble game.

  • LetterInput: A component that represents the user input field.

Code

WordScramble.js

import React, { useState } from 'react';
import LetterInput from './LetterInput';

function WordScramble() {
  const [scrambledWord, setScrambledWord] = useState('tgienr');
  const [userGuesses, setUserGuesses] = useState('');
  const [timer, setTimer] = useState(60);
  const [score, setScore] = useState(0);

  const handleGuess = (letter) => {
    const updatedUserGuesses = userGuesses + letter;
    setUserGuesses(updatedUserGuesses);
    checkGuess(updatedUserGuesses);
  };

  const checkGuess = (guess) => {
    if (guess === unscramble(scrambledWord)) {
      setScore(score + 1);
      setTimer(timer + 10);
    } else {
      setTimer(timer - 10);
    }
  };

  const updateTimer = () => {
    setTimer(timer - 1);
  };

  return (
    <div>
      <h2>Word Scramble</h2>
      <p>Scrambled Word: {scrambledWord}</p>
      <LetterInput onGuess={handleGuess} />
      <p>Timer: {timer}</p>
      <p>Score: {score}</p>
    </div>
  );
}

export default WordScramble;

LetterInput.js

import React from 'react';

function LetterInput({ onGuess }) {
  const [letter, setLetter] = useState('');

  const handleInput = (event) => {
    const letter = event.target.value;
    setLetter(letter);
    onGuess(letter);
  };

  return (
    <input
      type="text"
      value={letter}
      onChange={handleInput}
    />
  );
}

export default LetterInput;

Explanation

The WordScramble component renders the scrambled word, user input field, timer, and score. The LetterInput component represents the user input field. The handleGuess function handles user input (letter guesses). The checkGuess function checks if the user's guess is correct. The updateTimer function updates the timer and score.

Possible Future Enhancements

  • Add more features to the game (e.g., multiple levels, bonus rounds).

  • Improve the user interface and user experience.

  • Add support for multiple players.

  • Display the correct answer after the game is over.

  • Allow users to save and load their progress.

Last updated