-
Notifications
You must be signed in to change notification settings - Fork 3
/
new_cards.rb
executable file
·177 lines (142 loc) · 2.62 KB
/
new_cards.rb
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
require 'rubygems'
require 'active_support/inflector'
class RankOutOfBoundsError < StandardError; end
class SuitOutOfBoundsError < StandardError; end
class Suit
STRINGS = [ "Heart", "Diamond", "Club", "Spade" ]
def initialize(suit)
@suit = case suit
when 0, /h/i
0
when 1, /d/i
1
when 2, /c/i
2
when 3, /s/i
3
else
raise SuitOutOfBoundsError
end
end
def to_s
STRINGS[@suit]
end
def to_c
STRINGS[@suit][0,1].downcase
end
end
class Rank
STRINGS = ["Two", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" ]
CHARS = (2..10).to_a + [ "J", "Q", "K", "A" ]
NUMERALS = (2..14).to_a
VALUES = (2..10).to_a + [ 10, 10, 10, 10 ]
def initialize(rank)
raise RankOutOfBoundsError unless (2..14) === rank.to_i
@rank = rank.to_i - 2
end
def to_s
STRINGS[@rank]
end
def to_n
NUMERALS[@rank]
end
def to_c
CHARS[@rank]
end
def value
VALUES[@rank]
end
end
class Card
attr_accessor :rank, :suit
def initialize(rank, suit)
@rank = Rank.new(rank)
@suit = Suit.new(suit)
end
def to_s
"#{@rank} of #{@suit.to_s.pluralize}"
end
def to_db
"#{rank.to_n}#{suit.to_c}"
end
def value
@rank.value
end
def <(card)
@rank.to_n < card.rank.to_n
end
def >(card)
@rank.to_n > card.rank.to_n
end
end
class Deck
attr_reader :cards
def initialize
@cards ||= []
end
def add_deck
@cards ||= []
(0..3).each do |s|
(2..14).each do |r|
@cards << Card.new(r, s)
end
end
true
end
def draw
@cards.shift
end
def draw_all
to_discard = @cards
@cards = []
to_discard
end
def place(card)
if(card.respond_to?('rank') && card.respond_to?('suit'))
@cards ||= []
@cards << card
end
end
def shuffle
@cards = @cards.sort_by { rand }
end
def each
@cards.each { |card| yield card }
end
def [](index)
@cards[index]
end
def []=(index, card)
@cards[index] = card unless card.class != Card
end
def <<(cards)
@cards << cards
end
def size
@cards.size
end
def to_db
cards = []
@cards.each { |card| cards << card.to_db}
cards.join(",")
end
end
class Web_Deck < Deck
attr_accessor :redis_key
def initialize redis_key
@redis_key = redis_key
@cards ||= []
$r.lrange(redis_key, 0, -1).each do |c|
@cards << Card.new(c[0,c.size-1], c[-1,1])
end
end
def place card
super
$r.rpush @redis_key, card.to_db
end
def draw
$r.lpop @redis_key
super
end
end