Created
October 25, 2012 23:55
-
-
Save bolthar/3956223 to your computer and use it in GitHub Desktop.
War!
This file contains 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
A = 14 | |
SPADES = :s | |
DIAMONDS = :d | |
HEARTS = :h | |
CLUBS = :c | |
SUITS = [SPADES, DIAMONDS, HEARTS, CLUBS] | |
class Card | |
attr_reader :rank | |
def initialize(rank, suit) | |
@rank = rank | |
@suit = suit #unused | |
end | |
end | |
class Deck | |
def initialize(cards) | |
@cards = cards | |
end | |
def draw | |
return @cards.pop | |
end | |
def collect(stack) | |
while(!stack.empty?) do | |
@cards.insert(0, stack.shift) | |
end | |
end | |
def empty? | |
return [email protected]? | |
end | |
end | |
class Game | |
def create_decks | |
all_cards = ((2..A).to_a).product(SUITS).map { |x| Card.new(*x) }.shuffle | |
return [all_cards[0..(all_cards.count/2 - 1)], all_cards[(all_cards.count/2)..all_cards.count]].map { |x| Deck.new(x) } | |
end | |
def determine_outcome(card1, card2) | |
return @deck2 unless card1 #if player 1 can't draw player 2 wins | |
return @deck1 unless card2 #and vice versa | |
return war if(card1.rank == card2.rank) | |
return card1.rank > card2.rank ? @deck1 : @deck2 | |
end | |
def combat | |
@stack << @deck1.draw | |
@stack << @deck2.draw | |
winner = determine_outcome(@stack[-2], @stack[-1]) | |
winner.collect(@stack) | |
return winner | |
end | |
def war | |
@stack << @deck1.draw #facedown | |
@stack << @deck1.draw | |
@stack << @deck2.draw #facedown | |
@stack << @deck2.draw | |
return determine_outcome(@stack[-3], @stack[-1]) | |
end | |
def initialize | |
@deck1, @deck2 = create_decks | |
@stack = [] | |
end | |
def play | |
turns = 0 | |
while [@deck1, @deck2].all? { |x| !x.empty? } | |
winner = combat | |
turns += 1 | |
end | |
print "TURNS : #{turns}\n" | |
print "WINNER : player#{winner == @deck1 ? 1 : 2}\n" | |
end | |
end | |
Game.new.play |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment