我想用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
这看起来不太全面(无法判断它是王牌高还是6-高的红润),也不太像红宝石。
有没有一种更明显的方法来确定扑克中的手?
最佳答案
这可能远远不够完美,但我写了一些方法来检测扑克手来解决project euler问题。也许它能给你一些想法;完整的代码在这里:https://github.com/aherve/Euler/blob/master/pb54.rb
简而言之,Hand
由一个响应于Card
和Card.value
的Card.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