Daniel Mills
Daniel Mills

Reputation: 160

Converting back and forth between a position (slot) and coordinate

Basically, imagine a position based area with a width of 9 (starting with 0)

╔════╦════╦════╦════╦════╦════╦════╦════╦════╗
║  0 ║  1 ║  2 ║  3 ║  4 ║  5 ║  6 ║  7 ║  8 ║
║  9 ║ 10 ║ 11 ║ 12 ║ 13 ║ 14 ║ 15 ║ 16 ║ 17 ║
║ 18 ║ 19 ║ 20 ║ 21 ║ 22 ║ 23 ║ 24 ║ 25 ║ 26 ║
╚════╩════╩════╩════╩════╩════╩════╩════╩════╝

However, i am not converting to coordinates and back with position 0 as (0,0) This is essentially what i am trying to get

╔══════╦══════╦══════╦══════╦═════╦═════╦═════╦═════╦═════╗
║ -4,1 ║ -3,1 ║ -2,1 ║ -1,1 ║ 0,1 ║ 1,1 ║ 2,1 ║ 3,1 ║ 4,1 ║
║ -4,2 ║ -3,2 ║ -2,2 ║ -1,2 ║ 0,2 ║ 1,2 ║ 2,2 ║ 3,2 ║ 4,2 ║
║ -4,3 ║ -3,3 ║ -2,3 ║ -1,3 ║ 0,3 ║ 1,3 ║ 2,3 ║ 3,3 ║ 4,3 ║
╚══════╩══════╩══════╩══════╩═════╩═════╩═════╩═════╩═════╝

Essentially, the center of the X value is 0, going left or right, decreasing or increasing. However, i have not set the y as a center, since the Y value can expand to infinity.

I need to figure out how to do this with the following methods in Java

getPosition(int x, int y);    //RETURNS (int position)
getCoordinates(int position)    //RETURNS (int x, int y)

Any ideas?

Upvotes: 2

Views: 54

Answers (1)

Channa Jayamuni
Channa Jayamuni

Reputation: 1905

Use following methods. Note that i used java.awt.Point to represent x and y coordinates in getCoordinates(int position) method.

public int getPosition(int x, int y) {
    return ((y - 1) * 9) + (x + 4);
}

public Point getCoordinates(int position) {
    //calculate x and y
    int y = (int) ((position / 9) + 1);
    int x = (position - ((y - 1) * 9)) - 4;

    Point point = new Point(x, y);
    return point;
}

Upvotes: 1

Related Questions