Skip to content

Instantly share code, notes, and snippets.

@eveadele
Created February 20, 2014 00:24
Show Gist options
  • Save eveadele/9104476 to your computer and use it in GitHub Desktop.
Save eveadele/9104476 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#Choose a word
word_bank = ["mountains", "madness", "colour", "unknown",
"dream", "witch", "house", "quest", "horror", "west", "reanimator",
"red", "hook", "case", "ward", "space", "shadow", "time", "over", "shunned",
"whisperer", "darkness"]
word = word_bank.sample
chances = 8
#Generate guessed word
guessed_word = ""
len = word.length
len.times do
guessed_word << "_"
end
#Start game
puts "Welcome to Hangman!"
puts
puts "Word: " + guessed_word
puts "Chances remaining: #{chances}"
while guessed_word != word && chances > 0
#Get user input
print "Guess a single letter (a-z) or the entire word: "
guess = gets.chomp
#Evaluate guess
correct = false
occurrences = 0
loc = 0
if guess.length > 1 #User guesses entire word
if guess == word
guessed_word = word
else
puts "That's not the word, sorry."
chances -= 1
end
else #User guesses individual letter
word.each_char do |letter|
if guess == letter
guessed_word[loc] = letter
occurrences += 1
correct = true
end
loc += 1
end
if correct == true #Inform user of outcome of their guess
puts "Found #{occurrences} occurrence(s) of the character #{guess}."
puts
puts "Word: " + guessed_word
else
chances -= 1
puts "Sorry, no #{guess}'s found."
puts
puts "Word: " + guessed_word
puts "Chances remaining: #{chances}"
end
end
end
if guessed_word == word
puts "Congratulations, you've guessed the word!"
else
puts "You're out of chances, better luck next time..."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment