Playing cards: Difference between revisions
Content added Content deleted
(ruby attempt) |
m (→{{header|Ruby}}: some improvements and sample output) |
||
Line 1,065: | Line 1,065: | ||
{{works with|Ruby|1.8.7+}} |
{{works with|Ruby|1.8.7+}} |
||
<lang ruby>class Card |
<lang ruby>class Card |
||
# class constants |
|||
Suits = ["Clubs","Hearts","Spades","Diamonds"] |
Suits = ["Clubs","Hearts","Spades","Diamonds"] |
||
Pips = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"] |
Pips = ["2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"] |
||
# class variable (private) |
|||
@@value = { |
|||
"2" => 2, "3" => 3, "4" => 4, "5" => 5, "6" => 6, |
|||
"7" => 7, "8" => 8, "9" => 9, "10" => 10, |
|||
"Jack" => 11, "Queen" => 12, "King" => 13, "Ace" => 14, |
|||
} |
|||
attr_reader :pip, :suit |
|||
def initialize(pip,suit) |
def initialize(pip,suit) |
||
@pip=pip |
@pip = pip |
||
@suit=suit |
@suit = suit |
||
end |
end |
||
def to_s |
def to_s |
||
"#{@pip} #{@suit}" |
"#{@pip} #{@suit}" |
||
end |
|||
# allow sorting an array of Cards: first by suit, then by value |
|||
def <=>(card) |
|||
(@suit <=> card.suit).nonzero? or @@value[@pip] <=> @@value[card.pip] |
|||
end |
end |
||
end |
end |
||
class Deck |
class Deck |
||
def initialize |
def initialize |
||
Line 1,087: | Line 1,102: | ||
end |
end |
||
end |
end |
||
def to_s |
def to_s |
||
"[#{@deck.join(", ")}]" |
"[#{@deck.join(", ")}]" |
||
end |
end |
||
def shuffle! |
def shuffle! |
||
@deck.shuffle! |
@deck.shuffle! |
||
⚫ | |||
end |
end |
||
def deal |
def deal(*args) |
||
@deck.shift(*args) |
|||
shuffle! # Do we really need this? (instance variables are already private) |
|||
⚫ | |||
end |
end |
||
end |
end |
||
deck = Deck.new.shuffle! |
|||
puts card = deck.deal |
|||
hand = deck.deal(5) |
|||
puts hand.join(", ") |
|||
puts hand.sort.join(", ")</lang> |
|||
<pre>10 Clubs |
|||
8 Diamonds, Queen Clubs, 10 Hearts, 6 Diamonds, 4 Clubs |
|||
4 Clubs, Queen Clubs, 6 Diamonds, 8 Diamonds, 10 Hearts</pre> |
|||
=={{header|Smalltalk}}== |
=={{header|Smalltalk}}== |