I have encountered an issue when rendering a visualization of a 2d matrix using Pygame (I am aware this not the best library for the job ... but anyway). The issue arises when I attempt to render each node in the matrix as a rectangle. Each node is an instance of the Node class and has x1, y1, x2, and y2 values derived from it's position in the array. x1 and y1 are the coordinates for the first point of the rectangle and x2 and y2 are the coordinates are the second point. When I use lines to represent the nodes, everything seems to render as I expected. However when I use rectangles, the rectangles clump together. I noticed these are the rectangles representing the nodes after the 0th row and col positions in the 2d list. Does anyone know why this is? I have provided script A (lines) and script B (rectangles) with images of the output for review. [Output for script A][1], [Output for script B][2]
Script A (lines)
import pygame
import time
pygame.init()
class Node:
count = 0
def __init__(self, row, col):
Node.count += 1
self.id = Node.count
self.row = row
self.col = col
self.x1 = col * 10
self.y1 = row * 10
self.x2 = col * 10 + 5
self.y2 = row * 10 + 5
def display(matrix):
for i in matrix:
print(i)
matrix = [[Node(i, j) for j in range(10)] for i in range(10)]
win = pygame.display.set_mode((500, 500))
win.fill((0, 0, 0,))
for i in range(len(matrix)):
for node in matrix[i]:
pygame.draw.line(win, (0, 0, 255), (node.x1, node.y1), (node.x2, node.y2), width=1 )
pygame.display.update()
time.sleep(0.1)
Script B (rectangles)
import pygame
import time
pygame.init()
class Node:
count = 0
def __init__(self, row, col):
Node.count += 1
self.id = Node.count
self.row = row
self.col = col
self.x1 = col * 10
self.y1 = row * 10
self.x2 = col * 10 + 5
self.y2 = row * 10 + 5
def display(matrix):
for i in matrix:
print(i)
matrix = [[Node(i, j) for j in range(10)] for i in range(10)]
win = pygame.display.set_mode((500, 500))
win.fill((0, 0, 0,))
for i in range(len(matrix)):
for node in matrix[i]:
pygame.draw.rect(win, (0, 0, 255), (node.x1, node.y1, node.x2, node.y2))
pygame.display.update()
time.sleep(0.1)
The fact that the lines render in the correct positions leaves me puzzled as to why the rectangles are not as they are both using the same coordinates.