How to get mouse coordinates on a grid

Viewed 33

I have a function to get a position on a grid (the size of the grid is flexible) based on the mouse position

def get_coords_from_mouse_pos(self, mx, my):
    return mx // self.item_width, my // self.item_height

self.item_width and self.item_height are the width and height of one tile on the grid. mx and my are the mouse x and y positions. This probably exists somewhere else but I can't find it.

I probably just have the math wrong, but I would appreciate it if someone could help.

1 Answers

Here's a minimal example that shows your logic working, the left and top grid borders are considered as part of the cell below.

import pygame
# Configuration
width, height = 320, 240
cell_width, cell_height = 32, 32

pygame.init()

sys_font = pygame.font.SysFont(None, 60)
text = sys_font.render(" ", True, "turquoise")
clock = pygame.time.Clock()
screen = pygame.display.set_mode((width, height))
# create transparent background grid
grid = pygame.Surface((width, height), flags=pygame.SRCALPHA)
for y in range(0, height, cell_height):
    pygame.draw.aaline(grid, "green", (0, y), (width, y))  # horizontal lines
for x in range(0, width, cell_width):
    pygame.draw.aaline(grid, "green", (x, 0), (x, height))  # vertical lines

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    mx, my = pygame.mouse.get_pos()
    pygame.display.set_caption(f"Mouse: {mx}, {my}")
    if mx > 0 and my > 0:
        cellx = mx // cell_width
        celly = my // cell_height
        text = sys_font.render(f"Cell: {cellx}, {celly}", True, "turquoise")
    # Graphics
    screen.fill("grey25")
    screen.blit(grid, (0, 0))
    # Draw Text in the center
    screen.blit(text, text.get_rect(center=screen.get_rect().center))
    # Update Screen
    pygame.display.update()
    clock.tick(30)
pygame.quit()

This will look something like this:

grid coordinates

Related