首页 > 解决方案 > 如何让我的尝试次数正确?

问题描述

大家好,我之前问过如何在 ruby​​ 上修复一个猜数游戏,我已经完成了所有工作,但现在尝试或尝试的次数并没有很好地反映。我要解决这个问题吗?

这是代码:

def check(int, r_int)
    tries = 0
    if int < r_int
      tries +=1
      puts "Guess Higher"
    elsif int > r_int
      tries +=1
      puts "Guess Lower"
    elsif int == r_int
      win = true
      puts "You are correct"
      puts "You had attempted this "+ tries.to_s + " times to win"
      abort
    end
end

这是主要功能:

def main

win = false

puts "Lets play a game!"
puts "I am thinking of a number between 1 and 100"
rnd_int = rand(100)

while not win
    guess = gets.chomp.to_i
    value = check(guess, rnd_int)
end

end

总的来说一切正常,但游戏结束时的尝试仍然为 0,不确定错误在哪里。

标签: ruby

解决方案


也许代码可能如下所示(只是一个建议)

def check(attempts,guess,number)
    puts ">>> Attempts [#{attempts}]: guess higher" if guess < number
    puts ">>> Attempts [#{attempts}]: guess lower"  if guess > number
    if guess == number
        puts "Winner!!!"
        return true
    end
    return false
end


if __FILE__ == $0
    win = false
    attempts = 5
    
    puts "
        Lets play a game!
        I am thinking of a number between 1 and 100
    "
    
    number = rand(100)
    
    while not win
        print "Your guess: "
        guess = gets.chomp.to_i
        attempts -= 1
        unless attempts
            puts "You could not guess right"
            exit
        end
        win = check(attempts, guess, number)
    end
end

输出样本


                Lets play a game!
                I am thinking of a number between 1 and 100

Your guess: 50
>>> Attempts [4]: guess higher
Your guess: 80
>>> Attempts [3]: guess higher
Your guess: 90
>>> Attempts [2]: guess lower
Your guess: 86
Winner!!!

代码可以是以下形状

win = false
attempts = 5

puts "
    Lets play a game!
    I am thinking of a number between 1 and 100
"
number = rand(100)

while not win
    print "Your guess: "
    guess = gets.chomp.to_i
    attempts -= 1
    score = guess <=> number
    win = true if score == 0
    puts "Attempts [#{attempts}]: guess higher" if score < 0
    puts "Attempts [#{attempts}]: guess lower"  if score > 0
    unless attempts > 0
        puts "You could not guess it right"
        exit
    end
end

puts "You are winner!!!"

使用<=>运算符,代码将如下所示

attempts = 5

puts "
    Lets play a game!
    I am thinking of a number between 1 and 100

"
number = rand(100)

while true
    print "Your guess: "
    guess = gets.chomp.to_i
    attempts -= 1
    case guess <=> number
    when 0
        puts "\n>>> Nice guess, you are winner!!!"
        exit
    when -1
        puts "Attempts [#{attempts}]: guess higher" if attempts > 0
    when 1  
        puts "Attempts [#{attempts}]: guess lower"  if attempts > 0
    end
    unless attempts > 0
        puts "\n>>> Sorry, you could not guess it right"
        exit
    end
end

推荐阅读