我正在创建一个包含多个课程的纸牌游戏。目前,我正在使用全局变量来保存$shuffled_deck
,$players_hand
和$dealers_hand
变量,但我担心使用全局变量(可能是不必要的)并且更喜欢使用实例变量。
我一直在看书,但没有什么是真的点击。任何人都可以帮我指出正确的方向吗?
使用实例变量我无法保存@players_hand
和@dealers_hand
以便能够在其他类中使用它们。例如,我@players_hand
类Player
。我让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
答案 0 :(得分:5)
使用你的例子,你可以这样做
class Blackjack
attr_reader :player, :dealer
def initialize
@player = Player.new
@dealer = Dealer.new
end
end
class Dealer
def dealers_hand #the long java way of a getter
@dealers_hand
end
#and now the short ruby way
attr_reader :dealers_hand #if you only need to read the attribute
attr_writer :dealers_hand #if you only need to write the attribute
attr_accessor: dealers_hand #if you need both
def initialize
@deck = Deck.new
@dealers_hand = 5
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
attr_reader :players_hand
def initialize
@players_hand = 0
end
end
class Deck
def suits
attr_reader :shuffled_deck
@shuffled_deck = @shuffled_deck
end
def hit_player
@hit = $shuffled_deck.pop
end
def hit_dealer
@hit = $shuffled_deck.pop
end
end
game = Blackjack.new
p game.dealer.dealers_hand
game.dealer.dealers_hand = 4
p game.dealer.dealers_hand
答案 1 :(得分:4)
您想使用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