Skip to content

Instantly share code, notes, and snippets.

@ttreitlinger
Created March 8, 2011 15:13
Show Gist options
  • Save ttreitlinger/860391 to your computer and use it in GitHub Desktop.
Save ttreitlinger/860391 to your computer and use it in GitHub Desktop.
pile.rb
# A Pile represents the pile of cards on the table during a card game
require 'card_list.rb'
require 'observer.rb'
class Pile
include Observable
attr_reader :last_card
# Create an empty hand.
def initialize
@card_list = CardList.new
end
# Add card to pile.
def add card
@card_list.add card
@last_card = card
changed
notify_observers(self)
end
# Empty the pile.
def empty!
@card_list.empty!
end
# Sort the pile.
def sort!
@card_list.sort
end
# Return pile as string
def to_string
@card_list.to_string
end
# iterate over all cards in pile
def each
@card_list.each{|card| yield card}
end
# Return number of cards in pile
def no_of_cards
@card_list.no_of_cards
end
# Return the best card in the pile
def calculate_winner
sorted_cards = @card_list.sort # sort cards in 'poker' order
sorted_cards[-1] # return best card
end
# Return true iff top two cards of same suit
def snap?
if @cards.length < 2
false
# check for snap!
elsif @cards[-1].suit == @cards[-2].suit
true
else
false
end
end
end
require "test/unit"
require 'pile.rb'
require 'card.rb'
require 'winning_cards_observer.rb'
class TC_Pile < Test::Unit::TestCase
def setup
@pile = Pile.new
end
def test_initialisation
assert_equal(0, @pile.no_of_cards)
end
def test_winner
# create pile with entire pack of cards
SUITS.each do |suit|
KINDS.each do |kind|
card = Card.new suit, kind
@pile.add card
end
end
# check that ace of spades is the winner
ace_of_spades = Card.new :SPADES, :ACE
assert_equal(ace_of_spades, @pile.calculate_winner)
end
def test_add_one_card
@pile.empty!
two_of_spades = Card.new :SPADES, :TWO
@pile.add two_of_spades
assert_equal(two_of_spades, @pile.last_card)
end
def test_observable
# create a new observer class
wc_observer = WinningCardsObserver.new
# add it to the pile's list of observers
@pile.add_observer(wc_observer)
#create a card and add it to the pile to trigger the notifyer
two_of_spades = Card.new :SPADES, :TWO
@pile.add two_of_spades
# assert that the observer now knows the last card played
assert_equal(two_of_spades, wc_observer.last_card)
end
end
class WinningCardsObserver
attr_reader :last_card
def update pile
@last_card = pile.last_card
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment