jeudi 8 juin 2023

Issues with randomly generating instance of object in 2d array [duplicate]

I have a 2d array and I want to randomly generate one of two objects in each spot arr[r][c]. However when I tried my code, instead of generating a random object at the spot, it generates the same object for all indexes on the same column.

This is my current code:

    def generateBoard(self, r, c):
        for row in range(len(self.board)):
            for col in range(len(self.board[row])):
                if ((r - 2 < row < r + 2) and (c - 2 < col < c + 2)):
                    self.board[row][col] = obj1()
                else:
                    rand = random.randint(0, 1)
                    if (rand == 1):
                        self.board[row][col] = obj2()
                    else:
                        self.board[row][col] = obj1()

So for example, if row = 1, col = 2, and rand = 1, my method would not only generate an instance of obj2 at board[1][2], but also do so for [2][2], [3][2], [4][2]....... and I'm not sure why. Does anyone know what I'm doing wrong or if there is a better way to do what I want to do?




Aucun commentaire:

Enregistrer un commentaire