在Ruby中实现和测试Card和Deck类

时间:2014-10-14 08:32:12

标签: ruby

我在运行代码时遇到了一些麻烦,并且已经使用了至少4个小时......我似乎无法弄明白。顺便说一下,我是编程新手。

这是卡片组的UML图 http://imgur.com/lBJw2z0

class Card
  #Cards rank from lowest to highest
    VALUE = %w(2 3 4 5 6 7 8 9 10 J Q K A)
  SUITS = %w(C D H S)
  #(Club Diamond Heart Spade)

 def initialize(the_rank, the_suit)
    [@rank = the_rank]
    [@suit = the_suit]
    [@symbols = [nil, nil, '2', '3', '4', '5', '6', '7', 
                '8', '9', '10', 'J', 'Q', 'K', 'A']
  end

  def rank
    [return @symbols[@rank]]
  end

  def suit
    return @suit
  end

  def to_s
    "#{rank()}#{suit()}"
  end
end

  #double loop for Deck#initialize
  @cards = [ ]
    for rank in 2..14
    for suit in ['C', 'D', 'H', 'S']
    # create a new card with the specified rank
    # and suit and append it to the array.   
    end
  end 
  suits.each do |suit|
      (ranks.size).times do |i|
        @cards.push(Card.new(ranks[i], suit,(i+1)))
      end
    end

  #Remove a card from the top
  def deal
    [@cards.pop()](1)
  end
  #Add card to the bottom of the deck
  def add_to_bottom(the_card)
    @cards.insert(0, the_card)
  end
   #Add card to the top of the deck
  def add_to_top(the_card)
    @cards << the_card
  end

 #Shuffle the Card objects in the deck
  def shuffle!
    @cards.shuffle!
  end

    def count()
    @cards.count()
  end

   def empty?
    @cards.length == 0
  end

  def to_s
    string = ""
    @cards.each do |card|
      string += card.to_s + " "
    end
  end

  def cards
    @cards
  end
end

2 个答案:

答案 0 :(得分:0)

我没有对此进行过彻底的测试,但它基本上实现了您链接到的UML图:

class Deck

  def initialize
    @ranks = %w(2 3 4 5 6 7 8 9 10 J Q K A)
    @suits = %w(Clubs Diamonds Hearts Spades)
    @cards = []

    @ranks.each do |rank|
      @suits.each do |suit|
        @cards << Card.new(rank, suit)
      end
    end
  end

  def deal
    @cards.shift
  end

  def add_to_bottom(card)
    @cards.unshift(card)
  end

  def add_to_top(card)
    @cards << card
  end

  def count
    @cards.count
  end

  def empty?
    @cards.empty?
  end

  def shuffle!
    @cards.shuffle
  end

  def to_s
    result = ''
    @cards.each do |card|
      result = result + card.to_s + "\n"
    end
    return result
  end

end


class Card
  attr_reader :rank, :suit, :color
  def initialize(rank, suit)
    @rank = rank
    @suit = suit
    if @rank == 'Clubs' || @rank == 'Spades'
      @color = 'black'
    else
      @color = 'red'
    end
  end

  def to_s
    "Card: #{@color} #{@rank} of #{@suit}"
  end

end

# Run it, and try some stuff...
my_deck = Deck.new

puts my_deck.to_s
my_deck.deal
my_deck.count
my_deck.shuffle!
puts my_deck.to_s
my_deck.deal
my_deck.count

答案 1 :(得分:0)

现在我想弄清楚测试方法如何。我有第一个工作

d = Deck.new
d.cards.each do |card|
  puts "#{card.rank} #{card.suit}"
end

需要测试的第二种方法: 使用带有assert_equal方法的单元测试框架测试Card和Deck类。为Card类中的所有方法编写单元测试,但您只需要在Deck类中测试这些方法:new,deal,add_to_bottom,add_to_top,count,empty?