Last active
April 3, 2017 20:18
-
-
Save leefreemanxyz/9b62ae2b0cf469c7f0f3adcd469ecbf7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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