使用pygame渲染矩阵可视化

-1 投票
0 回答
15 浏览
提问于 2025-04-12 00:15

我在用Pygame绘制一个二维矩阵的可视化时遇到了问题(我知道这个库可能不是最适合这个工作的……不过无所谓)。问题出现在我试图把矩阵中的每个节点渲染成一个矩形时。每个节点都是一个Node类的实例,它有x1、y1、x2和y2这些值,这些值是根据它在数组中的位置得来的。x1和y1是矩形第一个点的坐标,而x2和y2是第二个点的坐标。当我用线条来表示节点时,一切看起来都很正常。但是当我用矩形时,这些矩形就挤在一起了。我注意到这些矩形是表示二维列表中第0行和第0列之后的节点。有没有人知道这是为什么?我提供了脚本A(线条)和脚本B(矩形),还有输出的图片供大家查看。[脚本A的输出][1],[脚本B的输出][2]

脚本A(线条)

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)

脚本B(矩形)



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)

线条能正确渲染在正确的位置让我感到困惑,为什么矩形却不行,毕竟它们使用的是相同的坐标。

0 个回答

暂无回答

撰写回答