Repository navigation
Expand file tree
/
Copy pathcards
More file actions
72 lines (59 loc) · 1.54 KB
/
Copy pathcards
File metadata and controls
72 lines (59 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class Card
SYMBOL_BY_TYPE = {club: '♣', diamond: '♦', heart: '♥', spade: '♠'} # Optional
attr_accessor :type, :value
def initialize(type, value)
@type, @value = type, value
end
# @return [String] Visual display
def to_s
"#{SYMBOL_BY_TYPE[type]}#{value}"
end
end
class Deck
TYPES = %i(club diamond heart spade)
VALUES = %i(A 2 3 4 5 6 7 8 9 10 J Q K)
attr_accessor :cards
def initialize
@cards = TYPES.each_with_object([]) do |type, cards|
VALUES.each {|value| cards.push(Card.new(type, value))}
end
end
# @return [Array] Cards
def reset
initialize
end
# @return [Array] shuffled cards
def shuffle
cards.shuffle!
end
# @return [Integer] number of cards in the pack
def count
cards.size
end
# @return [Card|Nil] takes first card
def take_top
cards.shift
end
# @param [Symbol] type
# @param [Symbol] value
# @return [Card|Nil] requested card
def find_card(type, value)
cards.find{|card| card.type == type && card.value == value }
end
# @param [Symbol] type
# @param [Symbol] value
# @return [Card] removed card
def remove_card(type, value)
card = find_card(type, value)
cards.delete(card) if card
end
# insert new card on top if card does not exists in the Deck
# @param [Symbol] type
# @param [Symbol] value
# @return [Array] cards with the new card on top
def add_on_top(type, value)
if TYPES.include?(type) && VALUES.include?(value)
cards.unshift(Card.new(type, value)) unless find_card(type, value)
end
end
end