Created
October 11, 2021 09:24
-
-
Save kainio/6ca4d1031ff6f48cc2d2dae6aa55ed27 to your computer and use it in GitHub Desktop.
Hang person game solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class HangpersonGame | |
# add the necessary class methods, attributes, etc. here | |
# to make the tests in spec/hangperson_game_spec.rb pass. | |
# Get a word from remote "random word" service | |
# def initialize() | |
# end | |
attr_accessor :word, :guesses, :wrong_guesses | |
def initialize(word) | |
@word = word | |
@word_guesses = Array.new(word.length, '-') | |
@guesses = '' | |
@wrong_guesses = '' | |
end | |
def guess(letter) | |
if letter.nil? || letter.empty? || letter =~ /^[^a-zA-Z]{1}$/ | |
raise ArgumentError | |
end | |
if @word.downcase.include? letter.downcase | |
return false if @guesses.include? letter.downcase | |
@guesses << letter | |
@word.chars.each_with_index do |l, i| | |
if l == letter.downcase | |
@word_guesses[i] = letter.downcase | |
end | |
end | |
else | |
return false if @wrong_guesses.include? letter.downcase | |
@wrong_guesses << letter | |
end | |
end | |
def word_with_guesses | |
@word_guesses.join('') | |
end | |
def check_win_or_lose | |
if @word == word_with_guesses | |
return :win | |
elsif @guesses.length + @wrong_guesses.length >= 7 | |
return :lose | |
else | |
return :play | |
end | |
end | |
# You can test it by running $ bundle exec irb -I. -r app.rb | |
# And then in the irb: irb(main):001:0> HangpersonGame.get_random_word | |
# => "cooking" <-- some random word | |
def self.get_random_word | |
require 'uri' | |
require 'net/http' | |
uri = URI('http://watchout4snakes.com/wo4snakes/Random/RandomWord') | |
Net::HTTP.new('watchout4snakes.com').start { |http| | |
return http.post(uri, "").body | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment