dimanche 1 août 2021

random.randint() works when printing but not when assigning to a value [closed]

I am trying to make a minesweeper game as a practice project but I have ran into an error when generating the random coordinates for the bombs. Basically, when I run the random.randint() function, it gives me an error when I try to assign it, but not when I print it out.

import random
def assignBombs(grid, k):
    m = len(grid) - 1
    n = len(grid[1]) - 1
    while k > 0:
        i = random.randint(0, m)
        j = random.randint(0, n)
        if grid[i][j].bomb == False:
            grid[i][j].bomb == True
            n -= 1
    return grid
grid = initialize(5, 5)
grid = assignBombs(grid, 4)

The initialize function will make a 5x5 grid of Cells, a class which has the boolean self.bomb. Please let me know if I need to provide this.

Anyway, this will give me the following error when running:

ValueError: empty range for randrange() (0, 0, 0)

However, if I replace the while loop in the function with a simple print statement:

def assignBombs(grid, k):
    m = len(grid) - 1
    n = len(grid[1]) - 1
    print(m, n, random.randint(0, n), random.randint(0, m))

This will print out just fine:

4 4 3 4

Where m and n are the max row and column indices. Any help is appreciated!




Aucun commentaire:

Enregistrer un commentaire