【问题标题】:Python: How to make drawn elements snap to grid in pygamePython:如何使绘制的元素在 pygame 中对齐网格
【发布时间】:2020-09-16 18:49:27
【问题描述】:

我正在尝试一个 Pathfinding 项目,但在创建工作 GUI 时遇到了问题。我正在使用 pygame 并且已经创建了一个网格和一个功能,当您按下(或按住)鼠标按钮时会绘制立方体。但是,这些立方体只会移动到您单击的任何位置,并且不会捕捉到网格。我想过以某种方式使用模数,但我似乎无法让它工作。请在下面找到随附的代码。 Cube 类是我用于在屏幕上绘制的正方形。此外,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))

【问题讨论】:

    标签: python user-interface pygame snap-to-grid


    【解决方案1】:

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

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2012-01-02
      • 1970-01-01
      相关资源
      最近更新 更多