Class: Gamemaker::CardGame::Deck

Inherits:
Object
  • Object
show all
Defined in:
lib/gamemaker/card_game/deck.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cards = self.class.card_class.all) ⇒ Deck

Returns a new instance of Deck.



19
20
21
# File 'lib/gamemaker/card_game/deck.rb', line 19

def initialize(cards = self.class.card_class.all)
  @cards = cards.dup
end

Class Method Details

.card_classObject

Raises:

  • (NotImplementedError)


4
5
6
# File 'lib/gamemaker/card_game/deck.rb', line 4

def self.card_class
  raise NotImplementedError, "Deck is an abstract class, use Deck.of(CardType) to create a usable subclass"
end

.from_json(json) ⇒ Object



15
16
17
# File 'lib/gamemaker/card_game/deck.rb', line 15

def self.from_json(json)
  new(json["cards"].map { |card| card_class.from_json(card) })
end

.of(card_class) ⇒ Object



8
9
10
11
12
13
# File 'lib/gamemaker/card_game/deck.rb', line 8

def self.of(card_class)
  Class.new(self) do
    define_singleton_method(:name) { super() || "#{card_class.name}Deck" }
    define_singleton_method(:card_class) { card_class }
  end
end

Instance Method Details

#==(other) ⇒ Object



57
58
59
# File 'lib/gamemaker/card_game/deck.rb', line 57

def ==(other)
  @cards == other.to_a
end

#as_jsonObject



61
62
63
# File 'lib/gamemaker/card_game/deck.rb', line 61

def as_json(*)
  { cards: to_a }
end

#draw(n = nil) ⇒ Object Also known as: take



35
36
37
# File 'lib/gamemaker/card_game/deck.rb', line 35

def draw(n = nil)
  n ? @cards.shift(n) : @cards.shift
end

#draw!(n = nil) ⇒ Object Also known as: take!



41
42
43
44
45
46
47
48
49
# File 'lib/gamemaker/card_game/deck.rb', line 41

def draw!(n = nil)
  if n && n > @cards.length
    raise IndexError, "Cannot draw #{n} cards from the deck: only #{@cards.length} cards left"
  elsif !n && empty?
    raise IndexError, "Cannot draw from the deck: no cards left"
  else
    draw(n)
  end
end

#empty?Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/gamemaker/card_game/deck.rb', line 27

def empty?
  @cards.empty?
end

#lengthObject



23
24
25
# File 'lib/gamemaker/card_game/deck.rb', line 23

def length
  @cards.length
end

#shuffle!Object



31
32
33
# File 'lib/gamemaker/card_game/deck.rb', line 31

def shuffle!
  @cards.shuffle!
end

#to_aObject



53
54
55
# File 'lib/gamemaker/card_game/deck.rb', line 53

def to_a
  @cards.dup
end