# Algorithm to detect a CLICK within Square range

It might be a simple question but I am looking for optimal solution. I will have numbers printed on a screen and I will be aware of coordinates. Numbers/Symbols will have 4 points(Square) to define their boundaries. Coordinates of that particular symbol will be stored in a file. Lets' say there is a number 5 and it's 4 coordinates on screens are:(2,20,20,20,2,40,20,40)

Now lets assume that a string 555 represent a value in a file, say the value is Car1

When the user press num pad of 5 thrice then it should detect that he needs Car1.

I am interested to know whether there's some standard formula/Algo to find the range between these 4 coordinates or I have to work on my own. The Formula that was coming in my mind is:

Symbol = (X1+X2+X3+X4)(Y1+Y2+Y3+Y4) = (62)(120) = 182(Representing 5)

But I am skeptical whether it's right and whether the formula will always be given a unique value per symbol/character based on given coordinates?

• Can your squares be rotated (i.e. do they need to be aligned to the X/Y axis?) – Joachim Sauer Feb 21 '13 at 15:11
• Actually those will be symbols on a Keypad where every Key will be representing a number. The Admin will just record 4 points via Interface in a file. Later if some someone presses those sets of numbers then I have to check whether he REALLY pressed 555 – Volatil3 Feb 21 '13 at 15:13
• You're right, it won't. If Y1 were one less pixel and Y4 was one more pixel, it would calculate the same value. Is there a particular reason why you must represent a square with a number? Can you not save X1,Y1,X2,Y2 where coordinate 1 is bottom left-most and coordinate 2 is upper right-most? – Neil Feb 21 '13 at 16:25
• @Neil this is what I am doing now, It did work :) – Volatil3 Feb 21 '13 at 16:54

A common way to do this is just to compare the coordinates of the mouse click with the coordinates of the square.

Suppose the square has top-left coordinate of x1, y1 and bottom-right is x2,y2.

A mouse click at mx, my is in the square if (mx>x1 and mx<x2 and my>y1 and my<y2).

If all the square are the same size and in a grid, you can give each square a number:

n = y * number of squares in a row + x.

Then to get n from a mouse click:

n = (width of grid in pixels / square width in pixels * number of squares in a row) + (height of grid in pixels / square height in pixels)