ruby - 如何让我的尝试次数正确?
问题描述
大家好,我之前问过如何在 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,不确定错误在哪里。
解决方案
也许代码可能如下所示(只是一个建议)
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
推荐阅读
- cmake - 在 CMake 中使用来自 C/C++ 宏的值
- laravel - 获取用户的所有帖子
- windows - PyTorch 无法在我的 Windows PC 上通过 conda 安装
- python - 导入注册表作为节目列表中的选择,完成后关闭表格;当我再次返回打开表单时,在同一会话中没有响应
- python - 如何在计数不返回 0 的情况下进行计数控制循环?
- twilio - twilio 与 ZOHO CRM 集成的问题
- php - 控制台中显示的数据表操作列的引导模式内容
- c# - `foreach(var w in S.Split())` 是否存在任何可能的性能问题?
- ajax - 如何使用华为e5573cs api发送ussd
- php - 我如何匹配和替换具有相似标记名的不同节点(或之间)的每个字符?