Skip to content

Instantly share code, notes, and snippets.

@leefreemanxyz

leefreemanxyz/hangman.js

Last active Apr 3, 2017
Embed
What would you like to do?
//download file and run with node hangman.js
function wrongGuessCount(word, guesses) {
return guesses.filter(letter => word.indexOf(letter) == -1).length;
}
function showGuess(word, guesses) {
let show = [];
let letters = word.split("");
letters.filter(letter => guesses.indexOf(letter) > -1 ? show.push(letter) : show.push("_"));
show = show.join(" ");
return show;
}
function isWinner(word, guesses) {
let currentBoard = showGuess(word, guesses);
if (currentBoard.indexOf("_") > -1) {
return false;
} else {
return true;
}
}
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const fs = require("fs");
function next(word, guesses) {
if (isWinner(word, guesses)) {
console.log(`You have won. The word was ${word}`);
process.exit();
}
console.log(showGuess(word, guesses));
if (wrongGuessCount(word, guesses) >= 6) {
console.log(`You lose. The word was ${word}`);
process.exit();
}
console.log(`You have made ${wrongGuessCount(word,guesses)} incorrect guesses. You have ${6 - wrongGuessCount(word,guesses)} incorrect guesses remaining.`);
rl.question("next letter? ", answer => {
guesses.push(answer.toLowerCase().trim()[0]);
console.log("player wrote:", answer[0]);
next(word, guesses);
});
}
let mysteryWord = "pelican";
const dictionary = fs.readFile('/usr/share/dict/words', 'utf8', function(err, data) {
if (err) throw err;
let wordArray = data.split('\n');
mysteryWord = wordArray[Math.floor(Math.random() * wordArray.length)];
next(mysteryWord, []);
});
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.