class GuessGame def initialize @correct = rand(1000) + 1 # Correct guess. @max = 1000 # Maximum and minimum for @min = 1 # "homing in" on the answer. @last = nil # The last guess. end def guess (x) curr = (x - @correct).abs if @last lastd = (@last - @correct).abs if lastd < curr print "Colder\n" elsif lastd > curr print "Warmer\n" if x > @last && @last > @min @min = @last # Increase the minimum. elsif x < @last && @last < @max @max = @last # Decrease the maximum. end end if x > @max || x < @min print "Idiot!\n" # Problem exists between keyboard and chair. end end @last = x; # This guess becomes the last guess end attr_reader :max, :min end game = GuessGame.new continue = true # Continue until the user exits. while(continue) print "Guess: " # Prompt. cmd = gets if cmd =~ /exit|quit|bye/i # Exit commands; case insensitive. print "See ya!\n" exit # elsif cmd =~ /max|min/i # For testing. # print game.max, "\n", game.min, "\n" elsif cmd =~ /^[0-9]+/ game.guess cmd.to_i end end
Do you think it's readable?


Sign In
Create Account


Back to top









