2010-10-07 20 views
2

我正在用Python編寫一個骰子游戲模擬器。我通過使用包含1-6的整數的列表表示一個滾動。所以我可能有這樣的卷:確定骰子卷是否包含某些組合?

[1,2,1,4,5,1] 

我需要確定一個卷中包含的得分組合,如3種,4種,2臺3,和直道。

有沒有一個簡單的Pythonic這樣做?我嘗試了幾種方法,但他們都變得雜亂無章。

回答

4

value: count重組爲一個字典,並測試各種模式的存在。

+0

聰明。從列表中取出「set」也可能有一些技巧。 – dkamins 2010-10-07 00:41:54

+2

在python 2.7(或3.1)裏有一個Counter模塊中的Counter類,它會爲你做這件事。 'collections.Counter([1,2,1,4,5,1])的行爲就像那個'value:count'字典。 – AndrewF 2010-10-07 02:37:52

1

有兩種方法可以做到這一點:

def getCounts(L): 
    d = {} 
    for i in range(1, 7): 
     d[i] = L.count(i) 
    return d # d is the dictionary which contains the occurrences of all possible dice values 
      # and has a 0 if it doesn't occur in th roll 

這一個由伊格納西奧巴斯克斯 - 艾布拉姆斯啓發和dkamins

def getCounts(L): 
    d = {} 
    for i in set(L): 
     d[i] = L.count(i) 
    return d # d is the dictionary which contains the occurrences of 
      # all and only the values in the roll 
2

我以前(但與撲克牌這樣寫的代碼)。一定量的代碼蔓延對於編碼遊戲的所有規則是不可避免的。例如,查找n-of-kind的代碼將與查找直線的代碼完全不同。

讓我們先考慮一種類型。正如其他人所建議的,創建一個包含每個元素計數的dict。然後:

counts = sorted(d.values()) 
if counts[-1] == 4: 
    return four_of_a_kind 
if counts[-1] and counts[-2] == 3: 
    return two_sets_of_three 
# etc. 

檢查直線需要不同的方法。在檢查n-of-kind時,您需要獲取計數並忽略這些值。現在,我們需要研究的價值和忽略計數:

ranks = set(rolls) 
if len(ranks) == 6: # all six values are present 
    return long_straight 
# etc. 

在一般情況下,你應該能夠識別具有相似的味道,抽象出來的代碼,這些類型的規則將有助於規則,然後寫只是一個每條規則幾行。有些規則可能是完全獨特的,無法與其他規則共享代碼。這只是cookie崩潰的方式。