How to calculate the number of box according to their position?


I'm developing a python memory based game and having a problem to find the number of box the user clicks, according of the position of the cursor.

I already have this:

number = ev.pos[y]//boxsize*numboxsx+ev.pos[x]//boxsize

(with this line I get what you can see on the left of the picture in red)

But I have to consider: mx and my, they are the margin, because the boxes are centered. (What I show in the right of the picture in green).

So, how can I modify the line to get the number of box with the margin?


Answers:


You need to subtract the margins from the cursor position. Think of it as translating from absolute coordinates (where the cursor is on the screen) to relative coordinates (where the cursor is relative to your boxes).

relx, rely = ev.pos[x] - mx, ev.pos[y] - my
number = rely//boxsize*numboxsx + relx//boxsize