Last active
April 28, 2017 16:17
Star
You must be signed in to star a gist
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
#!/usr/bin/env ruby | |
def hangman | |
tries_left = 12 | |
# only select words less than ten letters long | |
lines = File.readlines('/usr/share/dict/words').select { |e| e.length < 10 } | |
# grab a random word | |
word = lines[rand(lines.length)].chomp.chars | |
guessed = [] | |
while tries_left > 0 | |
print "Guess a letter : " | |
# only take the first character. | |
# we could check to see if it's a letter, but why? | |
guessed.push STDIN.gets.chomp.chars[0] | |
# prints the letter or an underscore | |
# the ternary could have been part of #reduce but the line is long enough as is | |
puts word. | |
map { |e| guessed.include?(e) ? e : '_'}. | |
reduce('') { |acc, e| acc += " #{e} "} | |
return puts "Congratulations! You win!" if word & guessed == word | |
tries_left -= 1 | |
puts "You have #{tries_left} guesses left" | |
end | |
puts "Sorry, you lose. The word was #{word.join}" | |
end | |
loop do | |
hangman | |
print "Rematch? [y/N]" | |
break unless gets.chomp.casecmp?('y') | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment