0

In my Python program I want to roll a dice 8 times, but without it repeating the same value. I am trying different things but can't find a solution. My code is all follows:

if time%2 == 0 and counter_agents<max_agents: 
   succeeded=False  
   teller=0
   while (not(succeeded)and teller<10): 
           dice = random.randint (0,7)
           combis = []
           if dice == 0:                  
               pos_x=20
               pos_y=75 
           elif dice == 1:                  
               pos_x=21
               pos_y=75                   
           elif dice == 2:
               pos_x=60
               pos_y=75                   
           elif dice == 3:
               pos_x=61
               pos_y=75 
           elif dice == 4:
               pos_x=100
               pos_y=75                     
           elif dice == 5:
               pos_x=101
               pos_y=75 
           elif dice == 6:
               pos_x=140
               pos_y=75 
           elif dice == 7:
               pos_x=141
               pos_y=75   
           if counter_agents+1<=max_agents:  #field[pos_y,x_pos]==0 and 
               succeeded=True  
           teller=teller+1   
d.b
  • 32,245
  • 6
  • 36
  • 77
  • 4
    Stackoverflow has a `dice` tag? – Michael Szczesny Mar 03 '22 at 17:28
  • 4
    Since your dice has 8 numbers and you throw it 8 times, you can shuffle the values - https://stackoverflow.com/questions/976882/shuffling-a-list-of-objects – TDG Mar 03 '22 at 17:29
  • 1
    @MichaelSzczesny 13 watchers – timgeb Mar 03 '22 at 17:33
  • I can't see how `counter_agents` or `max_agents` are used in your code, so the condition `if counter_agents+1<=max_agents:` may never be achieved in order to do `succeeded=True`? Please elaborate about this variables – nferreira78 Mar 03 '22 at 17:41

2 Answers2

1

I believe this function does the job

import random

def roll_dice(min, max) -> int:
    numbers = set()
    for _ in range(max - min + 1):
        while (dice_value := random.randint(min, max)) in numbers:
            pass
        numbers.add(dice_value)
        yield dice_value

You can call it like this:

dice = roll_dice(0, 7)

dice_value = next(dice)

To get all values:

list(roll_dice(0, 7))
0

You can use this:

#Importing the library 
import numpy as np

#create a function "def"
def roll():
  numbers = list(np.random.choice(range(8), 8, replace=False))
  return numbers

#calls the function
roll()