Ruby猜数字游戏

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

# encoding: UTF-8
class NumberKeeper
	attr_accessor :number, :userGuessing, :smallerNum, :biggerNum, :guessTimes

	def initialize(limit)
		@smallerNum = limit.begin
		@biggerNum = limit.end
		prng = Random.new(Time.now.sec)
		@number = prng.rand(limit)
		@userGuessing = true
		puts "猜数字游戏现在开始!"
		@guessTimes = 0
	end

	def letUserGuess
		puts "请输入一个整数:(#{@smallerNum}至#{@biggerNum})"
		int = gets.chomp.to_i
		@guessTimes += 1
		if !(@smallerNum..@biggerNum).include?(int)
			puts "第#{@guessTimes}次猜测不在 #{@smallerNum}至#{@biggerNum} 范围内。"
		elsif int == @number
			puts "第#{@guessTimes}次猜测猜对了!"
			@userGuessing = false
		elsif int < @number
			puts "第#{@guessTimes}次猜测偏小了。"
			@smallerNum = int
		else
			puts "第#{@guessTimes}次猜测偏大了。"
			@biggerNum = int
		end
	end
end

instance = NumberKeeper.new(0..1000)
while instance.userGuessing
	instance.letUserGuess
end
sleep 3