Skip to content

Instantly share code, notes, and snippets.

@austinthecoder
Created October 2, 2009 14:47
Show Gist options
  • Save austinthecoder/199799 to your computer and use it in GitHub Desktop.
Save austinthecoder/199799 to your computer and use it in GitHub Desktop.
module Austin
Guess = Struct.new(:letter, :frequency_ratio, :word_frequency_ratio) do
def <=>(guess)
weight <=> guess.weight
end
def weight
2 * word_frequency_ratio + frequency_ratio
end
def update_ratios(word_list)
self.frequency_ratio = word_list.join('').percentage_of(letter)
self.word_frequency_ratio = word_list.percentage_with(letter)
end
end
class HangmanGame
def initialize(word_list)
@word_list = word_list
@guesses = ('a'..'z').map { |letter| Guess.new letter }
end
def guess(word)
self.word = word
@guesses.sort!.pop.letter
end
def word=(new_word)
if @word != new_word
@word = new_word
update_word_list
update_guesses
end
end
def update_word_list
word_pattern = /^#{@word.gsub('_', "[a-z]")}$/
@word_list = @word_list.select { |word| word_pattern === word }
end
def update_guesses
@guesses.each { |g| g.update_ratios @word_list }
end
end
class Austin
attr_writer :word_list
def new_game(guesses_left)
@game = HangmanGame.new(@word_list)
end
def guess(word, guesses_left)
@game.guess(word)
end
def incorrect_guess(guess); end
def correct_guess(guess); end
def fail(reason); end
def game_result(result, word); end
end
end
class String
def percentage_of(letter)
count(letter).to_f / size
end
end
class Array
def percentage_with(letter)
select { |word| word.include?(letter) }.size.to_f / size
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment