Skip to content Skip to sidebar Skip to footer

Why When The X And Y Size Are Not The Same The Grid Is Not Showing Properly

I have this code that is used to display a grid but when size_x and size_y are not the same the grid is not shown properly. For exemple, if size_x = 16 and size_y =8, the grid that

Solution 1:

You got the math wrong at the nested for loops drawing the squares, this fix:

for row in range(size_x):
    for column in range(size_y):
        color = WHITE
        if grid[row][column] == 1:
            color = GREEN
        pygame.draw.rect(screen,
                         color,
       **notice the change** --------v
                         [(MARGIN + WIDTH) * row + MARGIN,
                          (MARGIN + HEIGHT) * column + MARGIN,
                          WIDTH,
                          HEIGHT])

You need draw the rectangle using the width as your first point (upper left corner).


Solution 2:

You accidentally swapped size_x and size_y. The x axis is the horizontal axis and the y axis is the vertical axis. The rows are the y dimension from top to bottom and the columns are the x dimension from left to right. Hence size_y is the number of rows and size_x is the number of columns:

# Create a 2 dimensional array. A two dimensional
# array is simply a list of lists.
grid = []
for row in range(size_y):                              # <--- size_y
    # Add an empty array that will hold each cell
    # in this row
    grid.append([])
    for column in range(size_x):                       # <--- size_x
        grid[row].append(0)  # Append a cell
while not done:
    # [...]

     # Draw the grid
    for row in range(size_y):                          # <--- size_y
        for column in range(size_x):                   # <--- size_x
            color = WHITE
            if grid[row][column] == 1:
                color = GREEN
            pygame.draw.rect(screen,
                             color,
                             [(MARGIN + WIDTH) * column + MARGIN,
                              (MARGIN + HEIGHT) * row + MARGIN,
                              WIDTH,
                              HEIGHT])

Post a Comment for "Why When The X And Y Size Are Not The Same The Grid Is Not Showing Properly"