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: var SomeVar = new WordGuess("word");
  Call methods on SomeVar
 *********************************************************************/

function WordGuess(word) {
	var secretWord = word;
	var tries = 0;
	var guessedLetters = "";
	var 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) {
	    var found = false;
	    guessedLetters = guessedLetters.concat(letter);
	    tries++;
		
	    for (var 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 (var i = 0; i < currentState.length; i++) {
			currentState[i] = "_";
	    }
	}
}

Submitted: December 24, 2012

Return to the snippets listing