我正在创建一个包含多个班级的纸牌游戏.目前,我使用全局变量来保存$shuffled_deck,$players_hand和$dealers_hand变量,但我担心使用全局变量(可能是,不必要)并且更喜欢使用实例变量.
我一直在看书,但没有什么是真的点击.任何人都可以帮我指出正确的方向吗?
使用实例变量我无法保存@players_hand和@dealers_hand以便能够在其他类中使用它们.例如,我有来自Player类的@players_hand.我让Dealer类画了一张牌,但是我不能将@players_hand拉到Dealer类中来将两者加在一起.
我目前的代码是:
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
解决方法
您想使用attr_reader,attr_writer或attr_accessor.以下是它们的工作原理:
> attr_reader:players_hand:允许你编写some_player.players_hand来获取该玩家的players_hand实例变量的值
> attr_writer:players_hand:允许你编写some_player.players_hand = 0来将变量设置为0
> attr_accessor:players_hand:允许您同时读写,就好像您同时使用了attr_reader和attr_writer一样.
顺便说一句,所有这些都是为您编写的方法.如果你想,你可以像这样手动完成:
class Player def initialize @players_hand = 0 end def players_hand @players_hand end def players_hand=(new_value) @players_hand = new_value end end