用两个阵列确定扑克牌

时间:2014-02-21 08:01:34

标签: ruby arrays algorithm poker

我想在ruby中创建一个简单的多人扑克节目,但我觉得我正在重新发明轮子:

table = [card1, card2, card3, card4, card5]
mike = [card6, card7]
john = [card8, card9]

card6.face = "A"
card6.suit = "spades"

我很难写一个算法来决定每个玩家可能拥有的牌。

例如,为了确定玩家是否处理了同花顺,我写了这样的内容:

  together = table + hand

  # Populate hash with number of times each suit was found
  $suits.each do |suit|
    matched[suit] = together.select{|card| card.suit == suit}.size
  end
  matched.each do |k,v|
    if v == 5
      puts "#{k} were seen five times, looks like a flush."
    end
  end

这似乎并不十分全面(无论如何判断它是Ace-high还是6-high flush)还是非常类似红宝石。

有没有更明显的方法来确定扑克牌?

1 个答案:

答案 0 :(得分:3)

这可能远非完美,但我写了一些方法来检测扑克手来解决project euler问题。也许它可以给你一些想法;完整代码在这里:https://github.com/aherve/Euler/blob/master/pb54.rb

简而言之,HandCard数组定义,可响应Card.valueCard.type

  def royal_flush?
    return @cards if straight_flush? and @cards.map(&:value).max == Poker::values.max
  end

  def straight_flush?
    return @cards if straight? and @cards.map(&:type).uniq.size == 1
  end

  def four_of_a_kind?
    x_of_a_kind?(4)
  end

  def full_house?
    return @hand if three_of_a_kind? and Hand.new(@cards - three_of_a_kind?).one_pair?
    return nil
  end

  def flush?
    return @cards if @cards.map(&:type).uniq.size == 1
  end

  def straight?
    return @cards if (vs = @cards.map(&:value).sort) == (vs.min..vs.max).to_a
  end

  def three_of_a_kind?
    x_of_a_kind?(3)
  end

  def two_pairs?
    if (first_pair = one_pair?) and (second = Hand.new(@cards - one_pair?).one_pair?)
      return first_pair + second
    else
      return false
    end
  end

  def one_pair?
    x_of_a_kind?(2)
  end

  def high_card?
    @cards.sort_by{|c| c.value}.last
  end

  private
  def x_of_a_kind?(x)
    Poker::values.each do |v|
      if (ary = @cards.select{|c| c.value == v}).size == x
        return ary
      end
    end
    return false
  end
end