Example. Grid using math.
import pygame from types import SimpleNamespace class Grid: @staticmethod def point(item): return SimpleNamespace(x=item[0], y=item[1]) def __init__(self, rect, size, gap=(0, 0)): self.rect = rect self.size = Grid.point(size) self.gap = Grid.point(gap) self.cut = Grid.point((self.size.x + self.gap.x, self.size.y + self.gap.y)) # Returns None for invalid position def get_position(self, x, y): if (self.rect.left < x < self.rect.right and self.rect.top < y < self.rect.bottom): return ((x - self.rect.x) // self.cut.x, (y - self.rect.y) // self.cut.y) # Returns None for invalid position def get_rect(self, x, y): if (self.rect.left < x < self.rect.right and self.rect.top < y < self.rect.bottom): return pygame.Rect( (x - self.rect.x) // self.cut.x * self.cut.x + self.rect.x, (y - self.rect.y) // self.cut.y * self.cut.y + self.rect.y, self.size.x, self.size.y) def main(): rect = pygame.Rect(0, 0, 800, 600) grid = Grid(rect, (40, 40)) print(grid.get_position(12, 22)) print(grid.get_rect(12, 22)) print(grid.get_position(83, 58)) print(grid.get_rect(83, 58)) print(grid.get_position(100, 700)) print(grid.get_rect(100, 700)) main()
99 percent of computer problems exists between chair and keyboard.