Skip to content

Instantly share code, notes, and snippets.

@rajeevkannav
Last active November 30, 2017 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeevkannav/2669b2f22641193e0537bb5b606ccf9f to your computer and use it in GitHub Desktop.
Save rajeevkannav/2669b2f22641193e0537bb5b606ccf9f to your computer and use it in GitHub Desktop.
Write a command line program in ruby that accurately and efficiently guesses the word in 4 letter word Cows and Bulls game.
class RepeatedCharactorFound < StandardError
def message
"Repeated charactors are not allowed. Please Try again."
end
end
class MinimumLengthRequired < StandardError
def message
"Charactor length must be equal to four. Please Try again."
end
end
class NextAttemptRequired < StandardError
def message
"almost there!!. Try with next attempt."
end
end
class BullsAndCows
def initialize
puts "Player One : Please enter your guess -:"
@guess = get_and_validate_stroke
@attempts = 0
puts "Player Two : Try to hit guess with your attempt -:"
bulls_and_cows
puts "Congratulations. You've done it, in #{@attempts} tries. It was #{@guess}."
end
def bulls_and_cows
@attempts += 1
answer = @guess.dup
_attempt = get_and_validate_stroke
return true if _attempt == @guess
##################### CRUX OF THE PROGRAM ####################
bulls = 0
_attempt.scan(/[a-z]/).each_with_index do |char, index|
break if index == answer.size
if char == answer[index, 1]
_attempt[index, 1] = answer[index, 1] = "."
bulls += 1
end
end
cows = 0
_attempt.scan(/[a-z]/).each do |char|
if index = answer.index(char)
answer[index, 1] = "."
cows += 1
end
end
###############################################################
puts "Moow Moow Moow are #{cows}, Grunt Grunt Grunt #{bulls}, Please try again :-"
raise NextAttemptRequired
rescue NextAttemptRequired => e
puts e.message
retry
end
def get_and_validate_stroke
_stroke = gets.chomp
raise MinimumLengthRequired if _stroke.length != 4
raise RepeatedCharactorFound if _stroke.chars.to_a.uniq.count != _stroke.length
_stroke
rescue RepeatedCharactorFound => e
puts e.message
retry
rescue MinimumLengthRequired => e
puts e.message
retry
end
end
BullsAndCows.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment