Skip to content

Instantly share code, notes, and snippets.

@apirak
Created March 23, 2012 14:51
Show Gist options
  • Save apirak/2171395 to your computer and use it in GitHub Desktop.
Save apirak/2171395 to your computer and use it in GitHub Desktop.
Hangman game with class, yield and self
require_relative 'hangman_class_3'
hangman = Hangman.new
hangman.start do |h|
puts h.answer
print "#{h.limit} Enter your best guest: "
h.guess(gets)
end
hangman.say_good_bye
String.class_eval do
def match_replace(word, char)
index = 0
word.each_char do |w|
if w == char
self[index] = char
end
index += 1
end
end
end
class Hangman
attr_reader :finish, :answer, :limit
def initialize
@words = %w{spiderman superman powerpuf hangman}
@finish = false
@limit = 8
@win = false
end
def random_word
return @words[rand(@words.length-1)]
end
def start(&block)
@word = random_word
@answer = "_" * @word.length
until @finish
yield self
end
end
def guess(answer)
@limit -= 1
answer = answer[0..-2]
if answer == 'exit' || limit == 0
@finish = true
return
end
if answer.length == 1
@answer.match_replace(@word, answer)
end
if @answer == @word || answer == @word
@finish = true
@win = true
end
end
def say_good_bye
if @win
puts "You are the winner"
else
puts "Bye loser, the answer is #{@word}"
end
end
end
require_relative 'hangman_class_3'
require 'test/unit'
class TestHangman < Test::Unit::TestCase
def setup
Hangman.class_eval do
attr_accessor :words, :finish, :limit, :win, :answer
def random_word
return "powerpuf"
end
end
@hangman = Hangman.new
end
def test_startup_value
assert(@hangman.words.length > 0, "should have more than one in dictionary")
assert_equal(@hangman.finish, false)
assert_equal(@hangman.limit, 8)
assert_equal(@hangman.win, false)
end
def test_exit
@hangman.guess("exit")
assert(@hangman.finish, "should exit when user type exit")
end
def test_find_one_missing_char
@hangman.start do |h|
h.guess("x\n")
assert_equal("________", h.answer)
break
end
end
def test_find_one_right_char
@hangman.start do |h|
h.guess("o\n")
assert_equal("_o______", h.answer)
break
end
end
def test_find_double_right_char
@hangman.start do |h|
h.guess("p\n")
assert_equal("p____p__", h.answer)
break
end
end
def test_quick_answer
@hangman.start do |h|
h.guess("powerpuf\n")
assert_equal(true, h.finish)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment