簡體   English   中英

Python:如何讓骰子不擲出相同的值

[英]Python: how to let dice not roll same value

在我的 Python 程序中,我想擲骰子 8 次,但不重復相同的值。 我正在嘗試不同的事情,但找不到解決方案。 我的代碼全如下:

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   

我相信這個 function 可以完成這項工作

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

你可以這樣稱呼它:

dice = roll_dice(0, 7)

dice_value = next(dice)

獲取所有值:

list(roll_dice(0, 7))

你可以使用這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM