クラスのインスタンスは他のインスタンスのメソッドにアクセスできますが、異なるメソッドを持つクラスの 2 つの異なるサブクラスに対してこれを行うことは可能ですか? または、アクセスするメソッドをスーパー クラスに含める必要がありますか?
質問する
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 に答える