WordGuess Game

Description: Simple object for creating a word guessing game (aka Hangman). This object can be used to set a secret word, keep track of tries, keep track of guessed letters and a method for retrieving the current state of the guessed word.
Tested Platform: All modern browsers
Language: Javascript
/**********************************************************************
  Usage: let Somelet = new WordGuess("word");
  Call methods on Somelet
 *********************************************************************/

function WordGuess(word) {
    let secretWord = word;
    let tries = 0;
    let guessedLetters = "";
    let currentState;
    resetCurrentState();
    
    // Method to set the object to a new word
    this.setWord = function(newWord) {
        secretWord = newWord;
        tries = 0;
        guessedLetters = "";
        resetCurrentState();
    };
    
    // Return number of guesses, guessed letters or current state of word
    this.getTries = function() {
        return tries;
    };
    
    this.getGuessedLetters = function() {
        return guessedLetters;
    };
    
    this.getCurrentState = function() {
        return currentState.join(" ");
    };
    
    // Method for guessing a letter
    this.guess = function(letter) {
        let found = false;
        guessedLetters = guessedLetters.concat(letter);
        tries++;
        
        for (let i = 0; i < secretWord.length; i++) {
            if (secretWord.charAt(i) == letter) {
                currentState[i] = letter;
                found = true;
            }
        }
        
        return found;
    };
    
    
    // Resets the state of this word game
    function resetCurrentState() {
        currentState = secretWord.split("");
        tries = 0;
        guessedLetters = "";
        
        for (let i = 0; i < currentState.length; i++) {
            currentState[i] = "_";
        }
    }
}

Posted: March 20, 2023

Return to the snippets listing