基本上,想象一个宽度为 9(从 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 ║
╚════╩════╩════╩════╩════╩════╩════╩════╩════╝
但是,我没有将位置 0 转换为坐标并返回为 (0,0) 这基本上是我想要得到的
╔══════╦══════╦══════╦══════╦═════╦═════╦═════╦═════╦═════╗
║ -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 ║
╚══════╩══════╩══════╩══════╩═════╩═════╩═════╩═════╩═════╝
本质上,X值的中心是0,向左或向右,减少或增加。但是,我没有以y为中心,因为y值可以扩展到无穷大。
我需要弄清楚如何使用 Java 中的以下方法执行此操作
getPosition(int x, int y); //RETURNS (int position)
getCoordinates(int position) //RETURNS (int x, int y)
有什么想法吗?
最佳答案
使用以下方法。请注意,我在 getCoordinates(int position)
方法中使用了 java.awt.Point
来表示 x
和 y
坐标.
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;
}
关于java - 在位置(槽)和坐标之间来回转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805846/