Python random.randint(a,b) 不为二维网格生成随机值
Python random.randint(a,b) not producing random values for a 2d grid
我不熟悉编码和制作我自己的扫雷游戏。我正在使用 PyGame.
当我使用下面的代码时,我会使用列表 Tiles 绘制一个二维网格,其中项目的红色像素和其他项目的灰色像素。我会得到与此类似的图像:Image of the result。如您所见,像素不是随机排列的。重新播种随机数生成器没有帮助,我只是得到了一个不同的非随机模式。
import pygame
import random
Height = 30
Length = 40
pygame.init()
win = pygame.display.set_mode((Length * 20 + 40,Height * 20 + 60))
Items = 50
Tiles = []
for i in range(Height * Length):
Tiles.append(99)
for i in range(Items):
index = random.randint(1,Height * Length-1)
if Tiles[index] == 99:
Tiles[index] = -1
else:
while not Tiles[index] == 99:
index = random.randint(1,Height * Length-1)
Tiles[index] = -1
def Render():
global Tiles
win.fill((100,100,100))
for x in range(Length):
for y in range(Height):
if Tiles[x*4 + y] == 99:
if (x*3 + y) % 2 == 0:
pygame.draw.rect(win, (150,150,150), (x*20+20,y*20+40,20,20))
else:
pygame.draw.rect(win, (130,130,130), (x*20+20,y*20+40,20,20))
elif Tiles[x*4 + y] == -1:
if (x*3 + y) % 2 == 0:
pygame.draw.rect(win, (255,0,0), (x*20+20,y*20+40,20,20))
else:
pygame.draw.rect(win, (225,0,0), (x*20+20,y*20+40,20,20))
run = True
while run is True:
pygame.time.delay(15)
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if keys[pygame.K_ESCAPE]:
run = False
Render()
pygame.display.update()
pygame.quit()
为什么 random.randint() 不给出随机值,如果是,为什么它们在图像中是这样的?我已经搜索过其他帖子说生日悖论之类的东西,但我肯定不会每次都这样 运行 它?
将 Tiles[x*4 + y]
更改为 Tiles[x*Height + y]
。
我不熟悉编码和制作我自己的扫雷游戏。我正在使用 PyGame.
当我使用下面的代码时,我会使用列表 Tiles 绘制一个二维网格,其中项目的红色像素和其他项目的灰色像素。我会得到与此类似的图像:Image of the result。如您所见,像素不是随机排列的。重新播种随机数生成器没有帮助,我只是得到了一个不同的非随机模式。
import pygame
import random
Height = 30
Length = 40
pygame.init()
win = pygame.display.set_mode((Length * 20 + 40,Height * 20 + 60))
Items = 50
Tiles = []
for i in range(Height * Length):
Tiles.append(99)
for i in range(Items):
index = random.randint(1,Height * Length-1)
if Tiles[index] == 99:
Tiles[index] = -1
else:
while not Tiles[index] == 99:
index = random.randint(1,Height * Length-1)
Tiles[index] = -1
def Render():
global Tiles
win.fill((100,100,100))
for x in range(Length):
for y in range(Height):
if Tiles[x*4 + y] == 99:
if (x*3 + y) % 2 == 0:
pygame.draw.rect(win, (150,150,150), (x*20+20,y*20+40,20,20))
else:
pygame.draw.rect(win, (130,130,130), (x*20+20,y*20+40,20,20))
elif Tiles[x*4 + y] == -1:
if (x*3 + y) % 2 == 0:
pygame.draw.rect(win, (255,0,0), (x*20+20,y*20+40,20,20))
else:
pygame.draw.rect(win, (225,0,0), (x*20+20,y*20+40,20,20))
run = True
while run is True:
pygame.time.delay(15)
keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if keys[pygame.K_ESCAPE]:
run = False
Render()
pygame.display.update()
pygame.quit()
为什么 random.randint() 不给出随机值,如果是,为什么它们在图像中是这样的?我已经搜索过其他帖子说生日悖论之类的东西,但我肯定不会每次都这样 运行 它?
将 Tiles[x*4 + y]
更改为 Tiles[x*Height + y]
。