How to Fill Squares Strictly Inside a Grid in Pygame?

Viewed 18

I drew a grid in pygame, and when clicked, one of the elements should fill, but it fills anywhere, not just in the square.

# import pygame

class Grid:

    def __init__(self,x,y,color):
        self.x = x
        self.y = y
        self.color = color

    def draw_grid(self):
        self.start = 0
        self.end = 0
        pygame.init()
        win = pygame.display.set_mode((self.x,self.y))
        set_x = []
        set_y=[]

        for x in range(self.x):
            set_x.append(x)
        for y in range(self.y):
            set_y.append(y)
        start_position = []
        while True:
            #
            size_x = 25
            size_grid = size_x + 1
            for x in set_x[::size_grid]:
                for y in set_y[::size_grid]:
                    pygame.draw.rect(win, (self.color), (x, y, size_x, size_x),1)
                    
            for events in pygame.event.get():
                if events.type == pygame.QUIT:
                    sys.exit()
                elif events.type == pygame.MOUSEBUTTONDOWN:
                    self. pos = pygame.mouse.get_pos()
                    print(start_position)



                    pygame.draw.rect(win, (255, 0, 100), (self.pos[0], self.pos[1], size_x, size_x))





                    start_position.append(self.pos)

                #win.fill(self.color)
            pygame.display.flip()



def run():

    GREEN = (55,55,55)
    grid = Grid(1100,700,GREEN)
    grid.draw_grid()



run()

What I need is that when you click on a cell, the entire cell is filled, and not the space that goes beyond it. I tried to start point X to the left, exactly to the nearest point Y. and vice versa, but nothing happens, all coordinates go to the beginning, that is, to zero in X and Y

1 Answers

Use the // (floor division) operator to align the mouse position (a//b is the same as int(a/b)). First divide the mouse position by the size of a tile and calculate the row and column. Finally multiply the row and column by the size of a tile and calculate the upper left corner of the tile in the grid:

class Grid:
    # [...]

    def draw_grid(self):
        # [...]

        while True:
            # [...]

            for events in pygame.event.get():
                if events.type == pygame.QUIT:
                    sys.exit()
                elif events.type == pygame.MOUSEBUTTONDOWN:

                    x, y = events.pos
                    size = size_x + 1
                    self.pos = (x // size) * size, (y // size) * size

                    pygame.draw.rect(win, (255, 0, 100), (self.pos[0], self.pos[1], size_x, size_x))
                    start_position.append(self.pos)
Related