Python:如何在 pygame 中使绘制的元素对齐网格

Python: How to make drawn elements snap to grid in pygame

我正在试验 Pathfinding 项目,但在创建工作 GUI 时卡住了。我正在使用 pygame 并且已经创建了一个网格和一个特征,当您按下(或持续按下)鼠标按钮时它会绘制立方体。然而,这些立方体只是随您点击而移动,不会捕捉到网格。我考虑过以某种方式使用模数,但我似乎无法让它工作。请在下面找到代码。立方体 class 是我用来在屏幕上绘制的正方形。此外,drawgrid() 函数是我设置网格的方式。我很想在这方面得到一些帮助,因为我已经被困在这个障碍上三天了。

class Cube:
    def update(self):
        self.cx, self.cy = pygame.mouse.get_pos()
        self.square = pygame.Rect(self.cx, self.cy, 20, 20)

    def draw(self):
        click = pygame.mouse.get_pressed()
        if click[0]:  # evaluate left button
            pygame.draw.rect(screen, (255, 255, 255), self.square)

其他drawgrid()功能:

def drawgrid(w, rows, surface):
    sizebtwn = w // rows  # Distance between Lines
    x = 0
    y = 0
    for i in range(rows):
        x = x + sizebtwn
        y = y + sizebtwn
        pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
        pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))

您必须将位置与网格大小对齐。使用底除运算符(//)将坐标除以单元格大小并计算网格中的积分索引:

x, y = pygame.mouse.get_pos()

ix = x // sizebtwn
iy = y // sizebtwn

将结果乘以单元格的大小来计算坐标:

self.cx, self.cy = ix * sizebtwn, iy * sizebtwn

最小示例:

import pygame
pygame.init()

screen = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()

def drawgrid(w, rows, surface):
    sizebtwn = w // rows 
    for i in range(0, w, sizebtwn):
        x, y = i, i
        pygame.draw.line(surface, (255, 255, 255), (x, 0), (x, w))
        pygame.draw.line(surface, (255, 255, 255), (0, y), (w, y))

class Cube:
    def update(self, sizebtwn):
        x, y = pygame.mouse.get_pos()
        ix = x // sizebtwn
        iy = y // sizebtwn
        self.cx, self.cy = ix * sizebtwn, iy * sizebtwn
        self.square = pygame.Rect(self.cx, self.cy, sizebtwn, sizebtwn)
    def draw(self, surface):
        click = pygame.mouse.get_pressed()
        if click[0]:
            pygame.draw.rect(surface, (255, 255, 255), self.square)

cube = Cube()

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    cube.update(screen.get_width() // 10)

    screen.fill(0)
    drawgrid(screen.get_width(), 10, screen)
    cube.draw(screen)
    pygame.display.flip()