Skip to content

Instantly share code, notes, and snippets.

@hchood
Created November 18, 2013 03:44
Show Gist options
  • Save hchood/7522121 to your computer and use it in GitHub Desktop.
Save hchood/7522121 to your computer and use it in GitHub Desktop.
Ruby Fundamentals - Non-core problem: hangman game
#!/usr/bin/env ruby
# DEFINITIONS
def replace_letters(word, letters)
string = "[^" + letters.join + "]"
regex = Regexp.new(string)
new_word = word.gsub(regex, '_')
end
# VARIABLES
word_bank = ["commit", "terminal", "repo", "developer", "ruby", "fake word", "fake word_2"]
hidden_word = word_bank.sample
while hidden_word.match(/[^a-z]/)
hidden_word = word_bank.sample
end
displayed_word = '_' * hidden_word.length
chances = 8
guesses = []
# PROGRAM
puts "Welcome to Hangman!"
puts
while chances >= 1
puts "Word: #{displayed_word}"
puts "Chances: #{chances}"
print "Guess a single letter (a-z) or the entire word: "
guess = gets.chomp
if guesses.include?(guess)
puts "You already guessed that letter! Guess again.\n\n"
else
# If guess is a letter:
if guess.length == 1
guesses << guess
if hidden_word.include?(guess)
displayed_word = replace_letters(hidden_word, guesses)
puts "Found #{hidden_word.count(guess)} occurence(s) of the character #{guess}.\n\n"
if displayed_word == hidden_word
puts "Congratulations, you've guessed the word!"
exit
end
else
puts "Sorry, no #{guess}'s found.\n\n"
chances -= 1
if chances == 0
puts "You're out of chances, better luck next time..."
exit
end
end
# If guess is a word:
elsif guess.length >= 1
if guess == hidden_word
puts "Congratulations, you've guessed the word!"
exit
else
puts "Sorry, that's not the right word. You lose!"
exit
end
else
puts "You must enter a valid character a-z."
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment