Skip to content

Instantly share code, notes, and snippets.

@mzemel
Created July 14, 2014 03:52
Show Gist options
  • Save mzemel/5244af969d84f4328f9c to your computer and use it in GitHub Desktop.
Save mzemel/5244af969d84f4328f9c to your computer and use it in GitHub Desktop.
Hangman program
# Let's play hangman!
module HangmanErrors
class YaDunGoofedError < StandardError; end
class HolyShitYouWon < StandardError; end
end
class TheGame
include HangmanErrors
attr_accessor :round
def initialize
puts "Well, howdy there. Ready to play? How many tries do you get?"
tries = gets.chomp.to_i
begin
self.round = WordJumblyBumbler.new(tries)
loop { loop_it! }
rescue HolyShitYouWon
puts "YOU WIN... but the princess is in another castle."
rescue
puts "Game. Over."
end
end
def loop_it!
puts "Gimme a letter!"
letter = gets.chomp
round.try(letter)
end
end
class WordJumblyBumbler
include HangmanErrors
attr_accessor :word, :partial, :tries
def initialize(tries = 10)
set_word!
self.tries = tries
self.partial = Array.new(word.size)
puts "Right then. You've got a word. It's first letter is #{word[0]}" +
" and it's last letter is #{word[-1]}. Good luck!"
end
def set_word!
self.word = ['apple', 'pear', 'banana', 'bamboo', 'mandolin', 'gondola', 'crankshaft'].sample
end
def try(char)
return fail_msg unless char[/[A-z]/]
raise YaDunGoofedError if tries < 1
hits = word.scan(/#{char.downcase}/).size # banana & 'aa' => YOU GOT 3 HITS KIDDO
hits == 0 ? fail_msg : boosh!(char)
win?
end
def boosh!(x)
# aw yeah, you got a letter
word.split("").each_with_index do |char, i| #'asdf' => %w(a s d f)
self.partial[i] = x.downcase if char == x.downcase
end
print_partial
end
def print_partial
puts partial.map {|x| x ? x : "?"}.join("")
end
def stick_figure
"O"*tries + " >\"~~~~ chomp chomp chomp"
end
def fail_msg
puts "Ouch. Not a letter!"
self.tries -= 1
print_partial
puts stick_figure
end
def win?
puts self.inspect
raise HolyShitYouWon if partial.select(&:nil?).size == 0
end
end
a = TheGame.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment