我如何在 pygame 中用可缩放的矩形覆盖 window

how do I cover a window with scalable rects in pygame

我将如何着手使 rects 在整个网格中均匀放置,同时仍然是可扩展的。我想用它们覆盖整个 window 并在缩小它们时增加数量,我的目的是让它看起来像缩小了。

import pygame
import sys

width, height = 750, 750
window = pygame.display.set_mode((width, height))

scale = 1
scroll_scale = .05
while True:
    graph_size = 50 * scale
    graph_count = width / graph_size
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                scale += scroll_scale
            elif event.button == 5 and scale > 0:
                scale -= scroll_scale
    window.fill((255,255,255))
    pygame.draw.rect(window, (0,255,0),(0, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size, 0, graph_size, graph_size))
    pygame.draw.rect(window, (0,255,0),(0 + graph_size * 2, 0, graph_size, graph_size))
    pygame.display.update()

我知道必须有一种方法可以做到这一点而无需单独绘制所有矩形,但我似乎找不到它

使用 2 个嵌套循环和 built-in range 函数:

import pygame
import sys

width, height = 750, 750
window = pygame.display.set_mode((width, height))

scale = 1
scroll_scale = .05
while True:
    graph_size = 50 * scale
    graph_count = width / graph_size
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                scale += scroll_scale
            elif event.button == 5 and scale > 0:
                scale -= scroll_scale

    window.fill((255,255,255))
    size = round(graph_size)
    for x in range(0, width + size, size):
        for y in range(0, height + size, size):
            c = (0,255,0) if (((x + y) // size) % 2) == 0 else  (127, 127, 127)
            pygame.draw.rect(window, c, (x, y, size, size))
    pygame.display.update()