Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dice values NOT repeat in if statement

I would like my dice values not to repeat because when it does, it registers a wrong input in my program (not a crash, simply a string message stating "Your input was wrong"). It is a board game so I do not want the same values to repeat, for example 6,0 to repeat twice or even thrice. Is there a way to save the dice values or anything I can do so that it chooses new random values every time?

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))

Desired output:

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

with no repeats, such as:

6,0
8,2
6,0 #this is a repeat, I do not want this to happen
3,9
like image 244
Ali R. Avatar asked Oct 30 '16 14:10

Ali R.


2 Answers

You can use a dictionary that maps dice to arguments of random.randint calls:

>>> 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

Futher, using collections.defaultdict, you don't need to handle else case specially.

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))
like image 170
falsetru Avatar answered Sep 27 '22 01:09

falsetru


Or you could just roll over and over again until a new combination emerges. This also implies that you have to do some bookkeeping of the combinations already drawn. And you must make sure that there is at least one more possible combination left, otherwise the loop will not terminate.

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
like image 30
Ukimiku Avatar answered Sep 23 '22 01:09

Ukimiku