Skip to content

Instantly share code, notes, and snippets.

@palnes palnes/hangman.js
Created Mar 15, 2013

Embed
What would you like to do?
// The original approach, with the relevant functions inlined
// in a closure to encapsulate implementation details.
function startGame(ui, solution) {
function repeat(string, repeat) {
var result = "";
result.forEach(function(item) {
result += string;
});
// for (var i = 0; i < repeat; i++) {
// result += string;
// }
return result;
}
function maskWord(word, chars) {
// Split word
//
return word.split("").map(
function(c) {
if (chars.indexOf(c.toLowerCase()) < 0 &&
chars.indexOf(c.toUpperCase()) < 0) {
return "*";
} else {
return c;
}
}).join("");
}
function guessedSolution(original, guesses) {
return maskWord(original, guesses) === original;
}
var guesses = [];
var render = function () {
var maskedWord = maskWord(solution, guesses);
ui.update(maskedWord);
};
var guess = function (letter) {
guesses.push(letter);
render();
if (guessedSolution(solution, guesses)) {
ui.close("You win!");
}
};
ui.onGuess(guess);
render();
}
function getRandom(list) {
return list[Math.floor(Math.random() * list.length)];
}
var ui = createHangmanUI(document.getElementById("hangman"));
var words = ["JavaScript", "Programming"];
var game = startGame(ui, getRandom(words));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.