我使用pygame
绘制了这个网格:
import pygame
# Color vars here
# Grid vars
WIDTH = 4
HEIGHT = 4
MARGIN = 1
# Initialize pygame
pygame.init()
WINDOW_SIZE = [820, 620]
screen = pygame.display.set_mode(WINDOW_SIZE)
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# Set the screen background
screen.fill(BLACK)
# Draw the grid
for row in range(120):
for column in range(160):
# Set the color here
# Draw rectangle
pygame.draw.rect(screen, color, [(MARGIN + WIDTH) * column + MARGIN, (MARGIN + HEIGHT) * row + MARGIN, WIDTH, HEIGHT])
# Limit to 60 frames per second
clock.tick(60)
# Update the screen
pygame.display.flip()
# Prevent hang if idle
pygame.quit()
如何偏移网格,使其不会从左上角开始?我想把它向右和向下移动一下。任何帮助将不胜感激。
答案 0 :(得分:2)
正如评论中提到的furas,有两种方法可以解决:
如果要移动所有元素,例如x轴为16像素,y轴为32像素,则可以为每个元素添加偏移量。
offset_x, offset_y = 16, 32
for row in range(120):
for column in range(160):
pygame.draw.rect(screen, color, [(MARGIN + WIDTH) * column + MARGIN + offset_x,
(MARGIN + HEIGHT) * row + MARGIN + offset_y,
WIDTH, HEIGHT])
执行嵌套循环时要注意的一件事是可以在循环外移动的计算(Loop-invariant code motion)。例如,MARGIN + WIDHT
,MARGIN + offset_x
,MARGIN + HEIGHT
和MARGIN + offset_y
对于每次迭代都是相同的。如果我们计算循环之前的值,我们将每帧节省4 * 120 * 160 = 76,800次计算。
full_width, full_height = MARGIN + WIDHT, MARGIN + HEIGHT
offset_x, offset_y = 16 + MARGIN, 32 + MARGIN
for row in range(120):
for column in range(160):
pygame.draw.rect(screen, color, [full_width * column + offset_x,
full_height * row + offset_y, WIDTH, HEIGHT])
如果您想要的偏移量为6(包含边距的矩形的大小),假设6 * 5 = 30,则可以在索引5处启动循环并取消偏移值。 / p>
full_width, full_height = MARGIN + WIDHT, MARGIN + HEIGHT
for row in range(5, 125):
for column in range(5, 165):
pygame.draw.rect(screen, color, [full_width * column + MARGIN,
full_height * row + MARGIN, WIDTH, HEIGHT])
不是直接在屏幕上绘制(这是一个Surface对象),您可以创建一个与网格大小相同的新Surface对象,在其上绘制,然后以所需的偏移量对其进行blit。
rows, columns = 120, 160
grid_image = pygame.Surface((rows * (WIDTH + 2 * MARGIN), columns * (HEIGHT + 2 * MARGIN)))
在主循环内。
full_width, full_height = MARGIN + WIDHT, MARGIN + HEIGHT
for row in range(rows):
for column in range(columns):
pygame.draw.rect(grid_image, color, [full_width * column + MARGIN,
full_height * row + MARGIN, WIDTH, HEIGHT])
screen.blit(grid_image, (offset_x, offset_y))