I'm getting an error "stack level too deep" running the code below. If the random card picked is not there it picks another random card. I suppose I should chance the code somehow, but I'm not sure how. Any suggestions?
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
I think it's safe to say the recursion is causing the error. Seems to me you don't need recursion, you could just loop until you get drawn_card != 0, e.g.,
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