在Ruby中创建Blackjack模拟,改变不同实例之间的变量

时间:2018-04-30 23:19:41

标签: ruby blackjack

这是面试。我想要做的是,一旦发牌(从经销商的Deck实例中删除),该牌就可供玩家的手牌实例使用。

    class Card
      attr_accessor :suite, :name, :value #specifiy that class attributes are both, readable and writable
      #constructor
      def initialize(suite, name, value) 
        @suite, @name, @value = suite, name, value #this looks odd
      end
    end

    class Deck
      attr_accessor :playable_cards
      SUITES = [:hearts, :diamonds, :spades, :clubs] #constant 
      NAME_VALUES = { 
        :two   => 2,
        :three => 3,
        :four  => 4,
        :five  => 5,
        :six   => 6,
        :seven => 7,
        :eight => 8,
        :nine  => 9,
        :ten   => 10,
        :jack  => 10,
        :queen => 10,
        :king  => 10,
        :ace   => [11, 1]}

      def initialize #initialzing shuffles the deck
        shuffle 
      end

      def deal_card #removes card from deck
        random = rand(@playable_cards.size) #returns an random int greater >= 0 & < max
        @playable_cards.delete_at(random)
      end

      def shuffle
        @playable_cards = [] #array of 52 cards
        SUITES.each do |suite| #iterate over suites
          NAME_VALUES.each do |name, value| #iterate, over card for that suite
            @playable_cards << Card.new(suite, name, value) #add to end of array, new Card
          end
        end
      end
    end

    class Hand
      attr_accessor :cards

      def initialize
        @cards = []
      end
    end

    class Player
      def initialize
        @player_hand = Hand.new
      end

    end

    class Dealer 
      def initialize
        @dealer_hand = Hand.new
        @dealer_deck = Deck.new
      end

      def deal 
        card = @dealer_deck.deal_card
      end
    end


require 'test/unit'

class CardTest < Test::Unit::TestCase
  def setup
    @card = Card.new(:hearts, :ten, 10)
  end

  def test_card_suite_is_correct
    assert_equal @card.suite, :hearts
  end

  def test_card_name_is_correct
    assert_equal @card.name, :ten
  end
  def test_card_value_is_correct
    assert_equal @card.value, 10
  end
end

class DeckTest < Test::Unit::TestCase
  def setup
    @deck = Deck.new
  end

  def test_new_deck_has_52_playable_cards
    assert_equal @deck.playable_cards.size, 52
  end

  def test_dealt_card_should_not_be_included_in_playable_cards
    card = @deck.deal_card
    assert(!@deck.playable_cards.include?(card)) #upon dealing card, card should be removed from deck
  end

  def test_shuffled_deck_has_52_playable_cards
    @deck.shuffle
    assert_equal @deck.playable_cards.size, 52
  end
end

我所做的就是添加了PlayerDealer类。我的想法是玩家有一只手,所以在初始化时,一个Hand的实例存储在@player_hand中,而经销商也是如此。显然,经销商也有自己的套牌实例。现在,当我致电Dealer.new.deal卡片从卡座中移除后,如何将新删除的卡片添加到Player @player_hand

我考虑过使用全局变量,但那是不好的做法。我也不太确定这是否是正确的方法。

1 个答案:

答案 0 :(得分:0)

我猜你需要一个让玩家和经销商存在的地方。从这个环境中你可以控制在经销商和玩家之间传递牌。也可能有几个球员或其他什么。

所以我会创建一个Game类,在这里你可以初始化玩家和经销商,你可以创建方法来处理卡片。

 =A1&"|"&B1