####################################################################### # Programming challenge 2: Guess my number # # To solve this challenge you need to know how to use a 'while' loop # # You need to know how to get user input from the command line # # Also how to normalize the input (removing trailing whitespaces) # # You should know about if-clauses and numeric comparisons, like '>' # # How to write methods # # And you should know what sequences are, e.g. 1..100 # ####################################################################### class Chooser def initialize(lower_bound, upper_bound) @number = rand(lower_bound..upper_bound) @steps = 0 end def guess(number) @steps = @steps + 1 if (@number == number) puts "Congratulations, the number is #{@number} and you needed #{@steps} steps!" return "correct" elsif @number > number return "greater" else return "smaller" end end end def ask_human(chooser, lower_bound, upper_bound) response = "" while response != "correct" # TODO: ask the user for input! # TODO: you can convert a string "42" to the number 42 by calling "42".to_i end end def computer_search(chooser, lower_bound, upper_bound) # TODO: implement a smarter solution than just guessing randomly response = "" while response != "correct" # 'rand' generates a random number in a sequence # you don't need to know how it works # because you can replace it with sth. better a_number = rand(lower_bound..upper_bound) response = chooser.guess(a_number) end end lower_bound = 1 upper_bound = 100 chooser = Chooser.new(lower_bound, upper_bound) # TODO: implement and call 'ask_human' #ask_human(chooser, lower_bound, upper_bound) computer_search(chooser, lower_bound, upper_bound)