Skip to content

Instantly share code, notes, and snippets.

@tehviking
Created August 7, 2010 06:03
Show Gist options
  • Save tehviking/512499 to your computer and use it in GitHub Desktop.
Save tehviking/512499 to your computer and use it in GitHub Desktop.
class Hangman
DICTIONARY = %w(pangolin ecstatic oligarchy corridor)
MAX = 6
def initialize(input=STDIN, output=STDOUT)
@input = input
@output = output
@guesses = 0
end
def start
@output.puts "Welcome to Hangman!"
generate_word
@current = @word.gsub(/./, "_")
@output.puts @current
guess
end
def guess
while @guesses < MAX
# print the word with letters found. Separate characters with a space.
@output.puts @current.gsub(/([A-Z_])/, "\\1 ")
@output.print "Enter a letter. You have #{MAX - @guesses} guesses. "
input = @input.gets.chomp.upcase
unless is_letter?(input)
if input == "QUIT"
exit
else
@output.puts "Please enter a valid character (1 letter)..."
next
end
end
# if the letter is in the word
if letter_is_in_word?(input)
update_word(input)
# if all letters are replaced, we've found the word, hurray!
if @current == @word
@output.puts "Well done! The word was #{@word}"
exit
end
else
# if the letter is not in the word, increase guesses number.
@guesses += 1
end
end
end
def update_word(input)
for i in 0...@word.size
# if current character is the input, replace the '_'
if @word[i].chr == input
@current[i] = input
end
end
end
def is_letter?(input)
# check that the input is one letter
!(input.size > 1 or not (input =~ /[[:alpha:]]/))
end
def letter_is_in_word?(input)
@word.index(input) != nil
end
def generate_word
@word = DICTIONARY[rand(DICTIONARY.size)-1].upcase
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment