Created
October 23, 2012 08:10
-
-
Save addisaden/3937574 to your computer and use it in GitHub Desktop.
A Rubyclass to get some cards
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
class Cards | |
def initialize(*signs) | |
@colors = [:♥, :♠, :♦, :♣] | |
@valid_signs = [2, 3, 4, 5, 6, 7, 8, 9, 10, :J, :Q, :K, :A] | |
if signs.empty? then | |
signs = @valid_signs | |
end | |
signs.each { |s| | |
raise "Given Sign \"#{ s }\" is not valid" unless @valid_signs.include?(s) | |
} | |
@signs = signs.sort { |a,b| @valid_signs.index(a) <=> @valid_signs.index(b) } | |
@card = Struct.new(:color, :sign) do | |
class << self | |
attr_accessor :colors, :signs | |
end | |
def show | |
"\{#{ sign }#{ color } \}" | |
end | |
def compare(other) | |
num = Proc.new { |a| self.class.signs.index(a.sign) } | |
col = Proc.new { |a| self.class.colors.reverse.index(a.color) } | |
num_compare = num.call(self) <=> num.call(other) | |
if num_compare == 0 then | |
return col.call(self) <=> col.call(other) | |
else | |
return num_compare | |
end | |
end | |
def <=>(other) | |
getVal = Proc.new { |card| (self.class.colors.index(card.color)*self.class.signs.length) + self.class.signs.index(card.sign) } | |
getVal.call(self) <=> getVal.call(other) | |
end | |
end | |
@card.colors = @colors | |
@card.signs = @signs | |
@cards = (@colors.product @signs).collect { |c| @card.new(*c) } | |
end | |
attr_reader :colors, :signs, :valid_signs, :cards | |
def count | |
@cards.count | |
end | |
def get(n=1) | |
@cards.pop(n) | |
end | |
def put(card, pos=0) | |
if valid_card? card then | |
# unshift | |
@cards.insert(pos, card) | |
return true | |
else | |
return false | |
end | |
end | |
def <<(cards) | |
cards.each { |c| raise "#{ c } is not a valid card" unless valid_card?(c) } | |
@cards.unshift(*cards) | |
end | |
def mix | |
@cards.shuffle! | |
end | |
def sort | |
@cards.sort! | |
end | |
private | |
def valid_card?(card) | |
return false unless card.is_a? @card | |
return false unless @colors.include? card.color | |
return false unless @signs.include? card.sign | |
return true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment