使骰子值不在if语句中重复

时间:2016-10-30 14:17:28

标签: python python-3.x

我希望我的骰子值重复,因为当它发生时,它会在我的程序中注册一个错误的输入(不是崩溃,只是一个字符串消息,指出“你的输入错误”)。这是一个棋盘游戏,所以我不希望重复相同的值,例如6,0重复两次甚至三次。有没有办法保存骰子值或我能做的任何事情,以便每次都选择新的随机值?

dice = random.randint(0,3)
ans = network.receive()
    if dice == 0:
        guess = str(random.randint(0,4))+','+str(random.randint(0,4))
    elif dice == 1:
        guess = str(random.randint(0,4))+','+str(random.randint(4,9))
    elif dice == 2:
        guess = str(random.randint(4,9))+','+str(random.randint(0,4))
    else:
        guess = str(random.randint(4,9))+','+str(random.randint(4,9))

期望的输出:

6,0
4,5
8,1
1,7

重复,例如:

6,0
8,2
6,0 #this is a repeat, I do not want this to happen
3,9

3 个答案:

答案 0 :(得分:4)

您可以使用将dice映射到random.randint来电的参数的字典:

>>> mapping = {
...     0: [0, 4, 0, 4],  # if dice == 1
...     1: [0, 4, 4, 9],  # elif dice == 2
...     2: [4, 9, 0, 4],  # elif dice == 3
... }
>>> mapping[0]
[0, 4, 0, 4]
>>> a, b, c, d = mapping[0]
>>> a
0
>>> b
4
>>> c
0
>>> d
4

此外,使用collections.defaultdict,您无需专门处理else个案。

from collections import defaultdict

dice = random.randint(0, 3)
ans = network.receive()

dice_random_mapping = defaultdict(lambda: [4, 9, 4, 9], {  # else
    0: [0, 4, 0, 4],  # if dice == 1
    1: [0, 4, 4, 9],  # elif dice == 2
    2: [4, 9, 0, 4],  # elif dice == 3
})

if ans == None:
    start1, stop1, start2, stop2 = dice_random_mapping[dice]
    guess = str(random.randint(start1, stop1))+','+str(random.randint(start2, stop2))

答案 1 :(得分:3)

或者你可以反复翻滚,直到出现新的组合。这也意味着您必须对已经绘制的组合进行一些记录。并且您必须确保至少还有一个可能的组合,否则循环将不会终止。

combis = []

dice = random.randint(0,3)
ans = network.receive()

while True:
    if dice == 0:
        guess = str(random.randint(0,4))+','+str(random.randint(0,4))
    elif dice == 1:
        guess = str(random.randint(0,4))+','+str(random.randint(4,9))
    elif dice == 2:
        guess = str(random.randint(4,9))+','+str(random.randint(0,4))
    else:
        guess = str(random.randint(4,9))+','+str(random.randint(4,9))

    if not guess in combis:
        combis.append(guess)
        break

答案 2 :(得分:2)

此功能可以为您完成所有骰子。它稍作优化。

import random

def roll_dice(low=1, high=6, count=1, allow_repeats=True):
    if not allow_repeats and count > (high - low):
        raise ValueError('Impossible not to have repeats with so many dice.')
    if not allow_repeats:
        possible_rolls = range(low, high) + [high]
        return random.sample(possible_rolls, count)
    return [random.randint(low, high) for _ in range(count)]

样品:

>>> roll_dice()
[1]
>>> roll_dice(count=2)
[5, 3]
>>> roll_dice(3, 10, count=2)
[8, 3]
>>> roll_dice(count=5, allow_repeats=False)
[6, 3, 2, 1, 4]
>>> roll_dice(count=5, allow_repeats=True)
[6, 6, 1, 5, 3]