Are you looking to create a JavaScript-based interactive word scramble game? This tutorial provides a clear and concise explanation of each line of code for your understanding. Learn how this game works and how to implement it.



What is the Jumbled Words Unscramble Game?

The Jumbled Words Unscramble game is a classic and charming word puzzle that challenges players to unscramble the letters of a scrambled word. In this game, players are presented with a word that has been randomly scrambled and have to decipher the original word within a limited time frame.

Jumbled Words Unscramble Game Interactive Demo

This informative and engaging game can be added to web pages using HTML, CSS, and JavaScript. It provides a fun method for evaluating and improving vocabulary, word identification, and cognitive abilities. Here's a quick demo of how each technology plays a role in the game:

To create a JavaScript-based interactive word scramble game, follow these steps:

Create an Event Listener for DOM Load

The document.addEventListener("DOMContentLoaded", () => { }); code ensures the JavaScript executes only after the entire HTML document loads.

Implement Fisher-Yates Shuffle Algorithm

The function fisherYatesShuffle(array) employs the renowned Fisher-Yates algorithm to shuffle an array randomly. This shuffled array will be used to scramble the words for the game.

function fisherYatesShuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

Initializing a Words Object

The words array contains objects for each word with an original and a hint property. Applying the Fisher-Yates shuffle algorithm to the original word generates an additional scrambled property.

const words = [
    { original: "HTML", hint: "Structure of web pages." },
    { original: "CSS", hint: "Styles web pages." },
    // ... (more words)
].map(wordObject => ({
    ...wordObject,
    scrambled: fisherYatesShuffle(wordObject.original.split("")).join("")
}));

Set Up Gameplay Variables

Variables such as currentWordIndex, timeLeft, score, and timer are initialized for game mechanics. These variables help track the current word, time remaining, player score, and game timer.

let [currentWordIndex, timeLeft, score, timer] = [0, 30, 0, null];

Cache DOM Elements

Variables store multiple elements from the DOM, such as wordElement, hintElement, and timeLeftElement, to avoid repetitive querying and improve access speed.

const [wordElement, hintElement, timeLeftElement, inputField, submitButton, skipButton, scoreElement, timerElement] =
["#word", "#hint span", "#timer strong", "#user-input", "#submit", "#skip", "#score", "#timer"]
.map(selector => document.querySelector(selector));

Reset Game Function

The resetGame() function resets the game to its initial state by clearing the timer and setting the index and score to zero.

const resetGame = () => {
    clearInterval(timer);
    currentWordIndex = score = 0;
    scoreElement.textContent = score;
    newRound();
};

New Round Setup

The newRound() function sets up a new round by choosing a word, updating the display, resetting the timer, and starting the countdown. It also checks whether the player has reached the end of the word list or not.

const newRound = () => {
    if (currentWordIndex >= words.length) {
        alert(`Game Over! Your score is ${score}. Restarting game.`);
        return resetGame();
    }
    const currentWord = words[currentWordIndex++];
    timeLeft = 30;
    [wordElement.textContent, hintElement.textContent, timeLeftElement.textContent, timerElement.style.color] =
        [currentWord.scrambled, currentWord.hint, `${timeLeft} sec`, "initial"];
    inputField.value = "";
    clearInterval(timer);
    timer = setInterval(updateTimeLeft, 1000);
};

Implement Timer Functionality

The updateTimeLeft() function decreases the time remaining by one second and updates the timer display. It also changes the timer text color to red when 10 seconds or less remain.

const updateTimeLeft = () => {
    if (timeLeft <= 0) {
        clearInterval(timer);
        alert("Time's up! Try the next word.");
        return newRound();
    }

    timeLeftElement.textContent = `${--timeLeft} sec`;
    if (timeLeft <= 10) timerElement.style.color = "red";
};

Add Event Handlers for Game Buttons

The Skip and Submit buttons have event handlers attached to them. Clicking the Skip button starts a new round. Clicking the Submit button checks the player's input against the original word to either proceed or display an alert for incorrect input.

skipButton.addEventListener("click", newRound);
submitButton.addEventListener("click", () => {
    if (inputField.value.toUpperCase() === words[currentWordIndex - 1].original) {
        scoreElement.textContent = ++score;
        newRound();
    } else {
        alert("Incorrect. Try again!");
    }
});

Initializing First Round

The newRound() function initializes the first round of the game.

newRound();

Conclusion

Creating a Word Scramble game in JavaScript is an enjoyable challenge that helps you sharpen your programming skills. You can make a fun and highly interactive game with a good understanding of the DOM, JavaScript fundamentals, and event handling. Take the code snippet above and experiment to create your unique version of the game!



Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram