我的RNG猜谜游戏似乎不断产生一个新号码,而不是保存游戏当前会话的数量供玩家猜测。
def initialize
@@answer = rand(1..100).to_s
end
def answer
@@answer
end
def guessing
puts "What's your guess?"
@@guess = gets.chomp.downcase
while @@guess != answer
wrong_answer
end
right_answer
end
答案 0 :(得分:0)
我没有看到您的代码有任何问题,但它可能是初始化类的方式(如果您在每次想要猜测时都明确地调用猜测)。
您需要将初始化的类存储在变量中:
guess = Guess.new
guess.guessing
guess.guessing
除非必要,否则您不想使用类实例变量,例如,使用@guess
,@answer
代替@@guess
和@@answer
。
另一种方式
def guessing
puts "What's your guess?"
@guess = gets.chomp.downcase
while @guess != answer
puts "wrong_answer"
@guess = gets.chomp.downcase
end
puts "right_answer"
end
答案 1 :(得分:0)
我认为如果将随机数存储在attr_reader中,则可以引用它并将其与猜测进行比较。如果您将猜测存储在attr_accessor中,您可以将猜测与存储的随机数进行比较,并让用户通过更新猜测继续游戏,直到它与随机数匹配。我可以包含一个示例,您可以将其复制并粘贴到IRB中。要开始游戏,只需致电PlayGame.new
,即可开始运行。输入cheat
作为随机数,输入hint
作为提示。
class RandomNumber
attr_reader :number
def initialize
@number = rand(1..100).to_s
end
def hint
random_number = number.to_i
puts case
when random_number >= 75
"Your number is in the range of 75 to 100"
when random_number >= 50
"Your number is in the range of 50 to 74."
when random_number >= 25
"Your number is in the range of 25 to 49"
else random_number > 0
"Your number is 24 or less."
end
end
end
class PlayGame
attr_accessor :input
attr_reader :number
def initialize
@generate_number = RandomNumber.new
@number = @generate_number.number
puts "What's your guess?"
@input = gets.chomp.downcase
validate
end
def validate
case
when input == number
puts "You win!"
when input == "cheat"
puts "The number is #{number}"
get_guess
when input == "hint"
@generate_number.hint
get_guess
else
get_guess
end
end
def get_guess
puts "Try again, what's your guess?"
@input = gets.chomp.downcase
validate
end
end