mardi 4 février 2020

How can I get a random number in Ruby (v2.6.3)

I'm doing an assignment in which I have to make a simple card game. The tutor has provided me with a method to generate a random card - which I'm not allowed to change:

def random_card
  cards = ["two", "three", "four", "five", "six", "seven",
           "eight", "nine", "ten",
           "jack", "queen", "king", "ace"]

  cards[rand(13)]
end

And I have tried to make a method that adds cards to the players hand, calling the random_card method each time:

def move(random_card)
  player_hand = []
  while true do
    puts "Make a move. Enter 'hit' or 'stick' "
    choice = gets.chomp
    if choice == "stick"
      break
    elsif choice == "hit"
      # this is currently giving me the same card for each "hit"
      # but a different one each time I run the code.
      player_hand.push(random_card)
    end
  end
  # TODO change this to return
  puts player_hand
end

Each time I `hit' the same card gets added to the hand, My question is how to prevent this and for the method to return a "new" random card each time we run through the loop.

Thanks.




Aucun commentaire:

Enregistrer un commentaire