Python:如何使绘制的元素在pygame中捕捉到网格

问题描述

我正在尝试一个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,(x,0),w))
        pygame.draw.line(surface,(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),w))
        pygame.draw.line(surface,(0,y),(w,y))

class Cube:
    def update(self,y = pygame.mouse.get_pos()
        ix = x // sizebtwn
        iy = y // sizebtwn
        self.cx,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,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()