I am creating a 2d array of square objects. Each square needs to be displayed in a window, so I need to iterate x and y by the width of a square and save those x and y values in the square object.
In the first nested loop it seems everything is working. Right after I create a square object and put it in the matrix, I print the row and col of the array, the x and y values where to draw the square. All results are as expected.
However when I try to access the square objects in the grid later. Every y value for every square is the same. Just the y, the x is fine.
I am printing the grid again in the same function, which should give me the same output. For some reason all of the square.y values are 12.
I want to know why all of the square.y values are becoming 12.
class Square():
def __init__(self, row, col, x, y, value):
#self.color = color
self.row = row
self.col = col
self.x = x
self.y = y
self.value = value
drawWall = False
drawPath = False
SQUARE_WIDTH = 6
SQUARE_HEIGHT = 6
GRID_SIZE_HEIGHT = 3
GRID_SIZE_WIDTH = 3
def createGrid():
print("this is the created grid \n =================================================================")
grid = [[None]* GRID_SIZE_HEIGHT] * GRID_SIZE_WIDTH
y = 0
for i in range(GRID_SIZE_WIDTH):
x = 0
for j in range(GRID_SIZE_HEIGHT):
grid[i][j] = Square(i, j, x, y, 2)
print(' [',i, "][", j,']:', "x", x, "y", y, end = '')
x += SQUARE_WIDTH
y += SQUARE_HEIGHT
print()
# printing the grid again for testing. Every y is 12
print("============================================================")
print("Why are all ys all 12????")
for i in range(GRID_SIZE_WIDTH):
for j in range(GRID_SIZE_HEIGHT):
xr = grid[i][j].x
yr = grid[i][j].y
print(' [',i, "][", j,']:', "x", xr, "y", yr, end = '')
print()
print("====================================================")
return grid
newGrid = createGrid()