[英]Python dice game using list
我正在尝试开发一个从1开始的骰子值序列运行的python骰子游戏,从1开始的值是3分。 如果没有1,则该手为0,而一个骰子的手数可以超过一个。
例如[5,6,2,4,2,3,6,4]为0
[3,4,1,5,3,1,4,6]是6(两个1)
[2,1,1,1,2,3,3,2]为24(两个1,2,3 = 18,一个1,2 = 6)
[5,3,2,6,4,5,1,4]是18(一个1,2,3,4,5,6)
def get_hand_score(list_of_dice):
score1 = 0
list1_sorted = list_of_dice.sort()
if "1" in str(list_of_dice):
score1+=3
if "2" in str(list_of_dice):
score1+=3
if "3" in str(list_of_dice):
score1+=3
if "4" in str(list_of_dice):
score1+=3
if "5" in str(list_of_dice):
score1+=3
if "6" in str(list_of_dice):
score1+=3
return score1
def test_get_hand_score():
print("1. score: ", get_hand_score([5, 3, 2, 5, 5, 6, 4, 3]))
print("2. score: ", get_hand_score([3, 4, 1, 5, 3, 1, 4, 6]))
print("3. score: ", get_hand_score([5, 3, 2, 6, 4, 5, 1, 4]))
print("4. score: ", get_hand_score([2, 1, 1, 1, 2, 3, 3, 2]))
print("5. score: ", get_hand_score([3, 4, 1, 5, 2, 1, 4, 6]))
list1 = [5, 3, 2, 5, 5, 6, 4, 3]
print("6. dice: ", list1)
score1 = get_hand_score(list1)
list1.sort()
print(" dice_sorted: ", list1)
print(" score:", score1)
print()
list1 = [5, 3, 2, 6, 4, 5, 1, 4]
print("7. dice: ", list1)
list1_sorted = sorted(list1)
score1 = get_hand_score(list1)
print(" dice_sorted: ", list1_sorted)
print(" score:", score1)
print()
list1 = [2, 1, 1, 1, 2, 3, 3, 2]
print("8. dice: ", list1)
list1_sorted = sorted(list1)
score1 = get_hand_score(list1)
print(" dice_sorted: ", list1_sorted)
print(" score:", score1)
print()
这给了我:
1. score: 0
2. score: 3
3. score: 18
4. score: 9
5. score: 18
6. dice: [5, 3, 2, 5, 5, 6, 4, 3]
dice_sorted: [2, 3, 3, 4, 5, 5, 5, 6]
score: 0
7. dice: [5, 3, 2, 6, 4, 5, 1, 4]
dice_sorted: [1, 2, 3, 4, 4, 5, 5, 6]
score: 18
8. dice: [2, 1, 1, 1, 2, 3, 3, 2]
dice_sorted: [1, 1, 1, 2, 2, 2, 3, 3]
score: 9
预期结果:
1. score: 0
2. score: 6
3. score: 18
4. score: 24
5. score: 21
6. dice: [5, 3, 2, 5, 5, 6, 4, 3]
dice_sorted: [2, 3, 3, 4, 5, 5, 5, 6]
score: 0
7. dice: [5, 3, 2, 6, 4, 5, 1, 4]
dice_sorted: [1, 2, 3, 4, 4, 5, 5, 6]
score: 18
8. dice: [2, 1, 1, 1, 2, 3, 3, 2]
dice_sorted: [1, 1, 1, 2, 2, 2, 3, 3]
score: 24
此代码有效(产生您的预期输出):
from collections import Counter
def get_hand_score(dice):
counts = Counter(dice)
total = 0
while counts[1] > 0:
n = 1
while counts[n] > 0:
counts[n] -= 1
total += 1
n += 1
return total * 3
代码的问题在于,您只能算一个序列。 您先寻找1,然后寻找2,依此类推,但是您不会以任何方式将其标记为“二手”,然后重复。 因此,当您的代码看到123123时,它只计数一次123。
编辑
更简单的(也许是?)工作代码:
def get_hand_score(dice):
counts = Counter(dice)
n = counts[1]
score = 0
for i in range(1, 7):
n = min(n, counts[i])
score += n
return score * 3
这里的想法是,每找到1分,得分就会提高。 (至少,它只是一个序列的一部分。)
之后,每2到1的分数都会增加分数。 并且每3到2的总数,分数就会再次增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.