红宝石 - 二十一点游戏 - 数组不能强制转换为整数



我正在尝试使用Ruby构建一个"21点"游戏。用户每次输入"命中"时都会得到一张随机卡。如果他们输入"stick",还有一些其他条件,但现在不相关。当他们输入"命中"时,游戏应该返回他们牌组的运行总数。

然而,我陷入了"求和"用户总数的困境。每当我使用.sum时,它都会说"数组不能被强制为整数">。我相信这是因为你不能对零值求和。我尝试了以下方法试图绕过这个问题,但没有成功;

  • .compact
  • .inject(:+(
  • .减少(:+(
  • .map{|n|n[nil]=0}

任何指针都将不胜感激。还有,道歉。我知道这个代码并没有它所能达到的效率——我对此还很陌生。

代码

def score
kvpz = {
"two" => 2, "three" => 3, "four" => 4, 
"five" => 5, "six" => 6, "seven" => 7, 
"eight" => 8, "nine" => 9, "ten" => 10, 
"jack" => 10, "queen" => 10, "king" => 10,
"ace" => 11
}  
end
def random_card
cards = [
"two", "three", "four", "five", "six", "seven",
"eight", "nine", "ten", "jack", "queen", "king", "ace"
]
cards[rand(13)]
end
def move 
total = []
while true do
puts "hit or stick"
input = gets.chomp
if input == "hit"
deck = [""]
deck.push(random_card)
total << deck.map { |n| score[n] }
puts total
elsif input == "stick" && total <= 21 
puts "You scored: #{total}"
abort
elsif input == "stick" && total > 21 
puts "You busted with: #{total}" 
abort
end
end
end
def run_game
score
random_card
move
end
run_game

这是因为这里将数组推入total,而不是数字。

total << deck.map { |n| score[n] }

以包含数组数组的total结束。而sum方法不能求和数组。尝试只将数字放入total数组。

total << deck.map { |n| score[n] }更改为total += deck.map { |n| score[n].to_i }

to_i在此阻止nil值(nil.to_i # => 0(

+=只是向total阵列添加(而非嵌套(元素

total <= 21——此处使用total.sum <= 21

但如果您不需要total作为数组,您可以将其初始化为0(而不是[](,然后

total += deck.sum { |n| score[n].to_i }

最新更新