views:

45

answers:

1

I'm working on a simple board game using Appcelerator Titanium for iPhone (javascript - not that it matters for this question really).

My problem isn't really language-specific, it's more of a general programming and math question.

I have a grid of "cells" that is 10 columns by 10 rows (100 cells). It's a board game, like checkers/draughts.

Starting at the top and moving downward, the rows are labeled 'A' through 'J'

Starting at the left and moving right, the columns are labeled '0' through '9'

Each cell is 32x32 (pixels).

I can drag a token onto/over the grid and when I release, it reports to me the x/y coordinates of where I released, eg: 124,302. I have these coords available to me in variables.

So my question is, how do I determine the center point of the cell that I released over, so I can center the token in that cell?

Any ideas on how to accomplish this?

+1  A: 

Use integer division to "round" off the raw coordinates.

x = (x / 32) * 32 + 16;
y = (y / 32) * 32 + 16;

Because the numbers are powers of two, you could also use bit operations.

x = (x & ~0x1F) | 0x10;
erickson
Yeah, *that's* what I was thinking. :)
Bill the Lizard
@erickson, Thanks, this is the direction I was headed in on paper. I just tried your first "round" off method, and didn't get expected results. For example, take the coordinates 10,10. That should clearly be in the first box, and the center of the first box is 16,16. But if we do your math on 10,10 we end up with 26,26. Unless I'm doing something wrong.
k00k
Kook, the equations are correct, but if and only if X and Y are integers and integer division rounds down (which it does in most languages).
Steve Emmerson
@k00k - Yes, most languages support "integer" division, where division of an integer will round toward zero. So, `10 / 32` yields 0, then `0 * 32` is also 0, and finally `0 + 16` results in 16.
erickson
Ahh, tis a javascript issue. In javascript, I need to use Math.floor(x /32) * 32 + 16;@erickson's bit operation worked in javascript as he outlined.
k00k