#!/usr/bin/ruby #First introduce the idea of the game puts "It's time to play pick a number!" puts "First pick a number in your head, don't tell me that number!" puts "Now pick a number HIGHER than that number, we will use it as an upper bound." puts "So what was the number?" upper_bound = gets.to_i #This equation is the maxiumum number of turns it will take to guess the users number. turns = (Math.log10(upper_bound) / Math.log10(2)).to_i + 1 puts "Now I will guess your number in #{turns} (lg upper bound) turns!" high = upper_bound low = 1 #Always guess an average of the bounds for maximum efficiency. number = (high + low) / 2 guesses = 0 #Initially, the number is not found. found = false #While the number hasn't been found and the NumberPicker hasnt been given #more than 7 guesses keep trying to guess the number. while(!found and guesses <= 7) guesses = guesses + 1 puts "#{guesses}: Is #{number} too high (1), too low (2), or correct (0)?" response = gets.to_i if response == 1 #When the number is too high, the bounds are the low bound and the number. high = number number = (low + number) / 2 elsif response == 2 #When the number is too low, the bounds are the high bound and the number. low = number number = (high + number) / 2 else found = true end end #At this point the game is over, output the number of guesses needed. #The else statement will only execute when the user gives the computer #false feedback as to whether the number was too high or low. if found puts "Looks like I was correct within #{guesses} guesses!" else puts "Oh My! I've failed! Or is it that you've cheated?" end #So the console screen doesnt automatically exit. puts "Press ENTER to exit" gets