1

我正在尝试一个 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))
4

1 回答 1

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()
于 2020-09-16T19:26:23.970 回答