class RubyTerminalGames::Hangman::Word

Attributes

guess_letters[R]
input_index[R]
letters[R]

Public Class Methods

new() click to toggle source
# File lib/ruby_terminal_games/hangman/word.rb, line 5
def initialize
  @letters = random_word.chars
  @guess_letters = @letters.map { nil }
end

Public Instance Methods

guess!(key) click to toggle source
# File lib/ruby_terminal_games/hangman/word.rb, line 10
def guess!(key)
  return true if won?

  found = false
  letters.each_with_index do |letter, index|
    next unless letter == key
    found = true
    @guess_letters[index] = letter
  end
  found
end
won?() click to toggle source
# File lib/ruby_terminal_games/hangman/word.rb, line 22
def won?
  letters.size == guess_letters.compact.size
end

Private Instance Methods

random_word() click to toggle source
# File lib/ruby_terminal_games/hangman/word.rb, line 28
def random_word
  path = File.expand_path(
    File.join(File.dirname(__FILE__), "words.txt"))

  File.readlines(path)
    .map { |line|
    line.strip.downcase
  }.reject { |w| w.empty? }.sample
end