0

我为 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

任何有关如何更好地编写此代码并使其无错误的建议将不胜感激!

4

1 回答 1

0

要检查 5 个骰子中至少有 4 个的顺子,您可以替换:

@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)}

有了这个:

if has_straight(roll, 4)

并定义has_straight

def has_straight( roll, need )
  num = 1
  roll = roll.sort.uniq

  roll.each_with_index do |e, i|
    if i < roll.length-1 then
      if (roll[i+1] - roll[i]) > 1 then
        break if num >= need
        num = 1
      end

      num += 1
    end
  end

  num >= need
end

可能有一个更聪明的 Ruby 主义可以做到这一点,但它可以解决您的数组越界问题。

于 2013-07-02T17:17:34.490 回答