2014-02-21 72 views
2

我想在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高的沖水),也不是非常紅寶石般的。

是否有更明顯的方式來確定撲克牌手?

+2

你可以看看這個寶石:https://開頭的github https://github.com/aherve/Euler/blob/master/pb54.rb

簡而言之,Hand是由Card陣列,即以Card.valueCard.type響應定義.COM/robolson /紅寶石撲克 – siekfried

回答

3

這可能遠非完美,但我寫了一些方法來檢測撲克牌手來解決project euler問題。也許它可以給你一些想法;完整的代碼是在這裏:

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