一个类的实例可以访问其他实例的方法,但是对于一个具有不同方法的类的两个不同子类可以这样做吗?还是必须将访问的方法包含在超类中?
问问题
89 次
1 回答
0
听起来您需要通过将 Deck 实例传递给各个 Hand 实例来跟踪您的关联。这是基于您描述的场景的示例:
class Card
attr_accessor :suit, :value
def initialize(suit, value)
@suit = suit
@value = value
end
end
class Deck
SUITS = ["Spades", "Clubs", "Diamonds", "Hearts"]
VALUES = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"]
HAND_SIZE = 5
attr_accessor :cards
def initialize
shuffle
end
def shuffle
@cards = []
SUITS.each do |suit|
VALUES.each do |value|
@cards << Card.new(suit, value)
end
end
@cards.shuffle!
end
def deal_hand
shuffle if @cards.size < (HAND_SIZE + 1)
hand = @cards[0...HAND_SIZE]
@cards = @cards.drop(HAND_SIZE)
hand
end
end
class Player
attr_accessor :deck
attr_accessor :hand
def initialize(deck)
@deck = deck
end
def draw!
@hand = @deck.deal_hand
end
end
# initialize
the_deck = Deck.new
players = []
players << (player1 = Player.new(the_deck))
players << (player2 = Player.new(the_deck))
players << (player3 = Player.new(the_deck))
players << (player4 = Player.new(the_deck))
# draw
players.each do |player|
player.draw!
end
# play
# ...
希望这可以帮助。
于 2012-11-29T03:35:18.490 回答