【发布时间】:2022-02-01 03:43:09
【问题描述】:
所以我在尝试创建一个琐事游戏时遇到了问题。我有几个问题。这是我当前的代码。
def random_question
#Going to work a way to use a hash instead of two seperate arrays
question_array = Array["Which state is known as the Evergreen State?", "What state is AZ?", "What state is CA?",
'What state is known as the Last Frontier?']
#random_question = question_array.shuffle.first
$ind = question_array.find_index($rand)
return $rand = question_array.sample
end
#If lives does not equal zero, let the game play out
while lives != 0
answer_array = Array["Washington", "Arizona", "California", "Alaska"]
puts random_question()
puts "!!!---" + $rand + "---!!!"
puts "What is your answer?"
#Takes answer(answer_response) and compares it to the correct answer
answer_response = gets.chomp
print answer_array[$ind.to_i - 1]
if answer_response == answer_array[$ind.to_i - 1]
puts "You're right!"
points += 10
puts "You have " + points.to_s + " points!"
else
puts "That is wrong. You lose a life!"
lives -= 1
puts "You have " + lives.to_s + " lives left!"
end
每当我在我的 CMD 或命令行中运行这个 Ruby 代码时,它会输出一个完全随机的答案,而不是我希望它显示的答案。
有人有解决办法吗?或者更好的是,谁能告诉我如何使用问题与答案相关联的哈希/字典?请帮忙。 :)
【问题讨论】:
-
提示:你在分配之前使用
$rand吗? -
我想我是,我注意到了。但我认为既然它是一个全局变量,它会起作用。抱歉,我对 Ruby 有点陌生。但我会调整它,看看是否有任何变化。 :)
-
我继续做了@rogerdpack,它最终给我一个错误说明。 “states.rb:239:in
gameplay': undefined methodfind_index' for nil:NilClass (NoMethodError) from states.rb:269:in `'” -
这里没有展示
gameplay方法。 -
如果在问题的开头说明了问答游戏的规则,读者会更容易理解你的代码。