运行下面的代码时出现错误“堆栈级别太深”如果随机选择的卡不在那里,它会选择另一张随机卡。我想我应该想办法修改一下代码,但我不知道怎么改有什么建议吗?

   def hit
    choice_of_card = rand($deck.length); #choose a random card out of the deck
    drawn_card = $deck[choice_of_card]; #draw that random card from the deck
    if drawn_card != 0 #if there is a card there
     $deck[choice_of_card] = 0; #remove that card from the deck by making the space blank
     if drawn_card == 11 #if you draw an ace
      self.ace_count += 1;
     end
     self.hand_value += drawn_card ;
    else hit; #if there is no card at that space then redraw (recursion)
    end
  end

最佳答案

我认为可以肯定的是递归导致了错误在我看来你不需要递归,你可以循环,直到你被抽卡!=0,例如。,

drawn_card = 0
while drawn_card == 0
  choice_of_card = rand($deck.length); #choose a random card out of the deck
  drawn_card = $deck[choice_of_card]; #draw that random card from the deck
end

关于ruby - Ruby中的堆栈级别太深,试图绘制随机卡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12728186/

10-11 03:01