mardi 15 février 2022

Python random.randint(a,b) not producing random values for a 2d grid

I'm new to coding and making my own MineSweeper game. I'm using PyGame.

When I use the code below I would use the list Tiles to draw a 2d grid with red pixels for the Items and gray pixels for the others. I would get a image similar to this: Image of the result. As you can see the pixels are not arranged in a random manner. Re-seeding the random number generator doesn't help, I just get a different not-random pattern.

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

Why is random.randint() not giving random values and if they are why are they like this in the image? I have searched other posts saying things like the birthday paradox but surely this can't happen every single time I run it?




Aucun commentaire:

Enregistrer un commentaire