Skip to content

Instantly share code, notes, and snippets.

@bendoane bendoane/cards.rb
Created Oct 16, 2015

Embed
What would you like to do?
Homework: day 8
class Cards
attr_accessor :suit, :face, :value
def initialize(face, suit)
self.face = face
self.suit = suit
if face == "Ace"
self.value = 14
elsif face == "King"
self.value = 13
elsif face == "Queen"
self.value = 12
elsif face == "Jack"
self.value = 11
else
self.value = face.to_i
end
end
def >(this_card)
self.value > this_card.value
end
def <(this_card)
self.value < this_card.value
end
end
require_relative "cards"
class Deck
attr_accessor :cards
def initialize
poss_cards = %w(2 3 4 5 6 7 8 9 10 Jack Queen King Ace)
poss_suits = %w(Clubs Spades Hearts Diamonds)
self.cards = []
poss_suits.each do |suit|
poss_cards.each do |face|
self.cards << Cards.new(face,suit)
end
end
end
def shuffle
self.cards = cards.shuffle
end
def draw
cards.shift
end
end
require_relative "cards"
require_relative "deck"
require_relative "players"
class War
attr_accessor :p1_hand, :p2_hand, :p1_winnings, :p2_winnings, :rounds, :wars
def initialize
puts "We're going to play the card game: War."
self.p1_winnings = []
self.p2_winnings = []
self.rounds = 0
self.wars = 0
self.p1_hand = Deck.new
self.p2_hand = Deck.new
p1_hand.shuffle
p2_hand.shuffle
end
def play
until p1_hand.cards.empty? || p2_hand.cards.empty?
fight
end
results
puts "The game is over"
puts "Dare to declare WAR again? (Yes/No)"
answer = STDIN.gets.chomp
answer.downcase
if answer == "yes"
initialize
play
else
puts "Thanks for playing"
end
end
def fight
self.rounds = self.rounds + 1
puts "ROUND #{self.rounds}! Fight!"
p1_card = p1_hand.draw
p2_card = p2_hand.draw
if p1_card > p2_card
p1_winnings << p1_card
p1_winnings << p2_card
puts "Player 1's #{p1_card.face} of #{p1_card.suit} beat Player 2's #{p2_card.face} of #{p2_card.suit}"
elsif p2_card > p1_card
p2_winnings << p1_card
p2_winnings << p2_card
puts "Player 2's #{p2_card.face} of #{p2_card.suit} beat Player 1's #{p1_card.face} of #{p1_card.suit}"
else
self.wars = self.wars + 1
puts "This means WAR!"
end
end
def results
if p1_winnings.count > p2_winnings.count
puts "Player 1 triumphs after #{rounds} rounds, surviving #{wars} wars!"
else p2_winnings.count > p1_winnings.count
puts "Player 2 triumphs after #{rounds} rounds, surviving #{wars} wars!"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.