Skip to content

Instantly share code, notes, and snippets.

@AlSquire
Created November 7, 2016 11:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlSquire/64793df200cf623a8b22f789896aaa54 to your computer and use it in GitHub Desktop.
Save AlSquire/64793df200cf623a8b22f789896aaa54 to your computer and use it in GitHub Desktop.
Tech talk classes ruby
class Card
include Comparable
NUMBERS = 1..13
COLORS = [:coeur, :carreau, :trefle, :pique]
attr_accessor :number, :color
def initialize(number, color)
@number = number
@color = color
end
def to_s
"#{number_name} de #{color}"
end
def <=>(card)
comp = number <=> card.number
(number == 1 || card.number == 1) ? -comp : comp
end
def number_name
case number
when 1 then'as'
when 11 then 'valet'
when 12 then 'reine'
when 13 then 'roi'
else number.to_s
end
end
def method_missing(name, *args, &block)
name.size == 5 ? "#{name}!" : super
end
end
class Cards
attr_accessor :cards
def shuffle!
@cards.shuffle!
end
def sum
@cards.map(&:number).inject(0) do |memo, number|
memo += number
end
end
end
class Deck < Cards
def initialize
@cards = []
Card::NUMBERS.each do |number|
Card::COLORS.each do |color|
@cards << Card.new(number, color)
end
end
end
def deal!(n)
Hand.new(@cards.shift(n))
end
end
class Hand < Cards
include Comparable
def initialize(cards)
@cards = cards
end
def <=>(hand)
sum <=> hand.sum
end
end
card1 = Card.new(6, :trefle)
puts card1.prouts
# card2 = Card.new(1, :coeur)
# puts card2
#
# puts card1 < card2
# deck = Deck.new
# puts deck.cards.size
# deck.shuffle!
# # puts deck.cards
#
# hands = []
# 10.times do
# hands << deck.deal!(5)
# end
#
# puts hands.max.cards
# puts hands.max.cards
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment