我为 Ruby Quiz #19 构建了一个 Yahtzee 游戏。我已经启动并运行了游戏,但是,有2个错误。
当玩家选择使用 >=3 的滚动作为“小顺子”(4 个骰子的序列)来“刮擦”(得分为零)时,该部分会发生错误。这是小直的代码:
def sm_straight
@roll = @roll.sort.uniq
if (0..1).any? {|x| (@roll[x+3] - @roll[x+2] == 1) && (@roll[x+2] - @roll[x+1] == 1) && (@roll[x+1] - @roll[x] == 1)}
@scorecard["sm. straight"] = 30
else
puts "Your roll is not a sm. straight! Please select another section or type scratch to score 0 for this section."
scratch = gets.chomp
if scratch == "scratch"
@scorecard["sm. straight"] = "scratch"
elsif @scorecard.has_key?(scratch)
@turn -= 1
section_to_score(scratch)
else
sm_straight
end
end
end
这是错误:
NoMethodError:sm_straight 中未定义的方法
-' for nil:NilClass from Yahtzee_test.rb:209:in
块'
第 209 行是“if 语句”行
当玩家错误地输入要保留的骰子时。我试图找出一种更好的方法来询问玩家如何输入骰子以保持或捕捉错误并让他们使用当前系统重新输入数字。这是代码”
def roll_again
puts "Which dice would you like to keep from this roll? (1, 2, 3, 4, 5)"
dice_to_keep = gets.chomp.split(',').map {|x| (x.to_i) - 1}.map {|x| @roll[x]}
new_roll = Array.new(5 - dice_to_keep.size) {rand(6) + 1}
@roll = new_roll + dice_to_keep
p @roll
@roll_count += 1
puts "That was roll number #{@roll_count}, you have #{3-@roll_count} remaining."
if @roll_count < 3
more_rolls?
else
section(@roll)
end
end
任何有关如何更好地编写此代码并使其无错误的建议将不胜感激!