I’m creating a card game with multiple classes. Currently, I’m using global variables to hold the $shuffled_deck, $players_hand, and $dealers_hand variables, but I worry when using global variables (perhaps, needlessly) and would prefer to use instance variables.
I’ve been reading around, but nothing is really clicking. Can anyone help point me in the right direction with this?
Using instance variables I haven’t been able to save the @players_hand and @dealers_hand to be able to use them in other classes. For instance, I have @players_hand from the Player class. I have the Dealer class draw a card, but I can’t pull that @players_hand into the Dealer class to add the two together.
My current code is:
class Blackjack
def initialize
@player = Player.new
@dealer = Dealer.new
end
end
class Dealer
def initialize
@deck = Deck.new
$dealers_hand = 0
end
def hit_dealer
@deck.hit_dealer
end
def hit_player
@deck.hit_player
end
def draw_card
@hit = $shuffled_deck
end
def shuffle
@deck.suits
end
end
class Player
def initialize
$players_hand = 0
end
end
class Deck
def suits
#code that shuffled the deck..
$shuffled_deck = @shuffled_deck
end
def hit_player
@hit = $shuffled_deck.pop
end
def hit_dealer
@hit = $shuffled_deck.pop
end
end
You want to use
attr_reader,attr_writer, orattr_accessor. Here’s how they work:attr_reader :players_hand: Allows you to writesome_player.players_handto get the value of that player’splayers_handinstance variableattr_writer :players_hand: Allows you to writesome_player.players_hand = 0to set the variable to 0attr_accessor :players_hand: Allows you to both read and write, as though you’d used bothattr_readerandattr_writer.Incidentally, all these do is write methods for you. If you wanted, you could do it manually like this: