java 如何将这段代码简化为一个自动完成此操作的函数?[关闭]

iovurdzv  于 11个月前  发布在  Java
关注(0)|答案(1)|浏览(111)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

昨天就关门了。
Improve this question
我有这几行代码:

int[][] coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        if (yg.radius == 1) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}};
        } else if (yg.radius == 2) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}};
        } else if (yg.radius == 3) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}};
        } else if (yg.radius == 4) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}, {2, 2}, {-2, 2}, {-2, -2}, {2, -2}};
        } else if (yg.radius == 5) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}, {2, 2}, {-2, 2}, {-2, -2}, {2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}};
        } else if (yg.radius == 6) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}, {2, 2}, {-2, 2}, {-2, -2}, {2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}, {3, 3}, {-3, 3}, {-3, -3}, {3, -3}};
        } else if (yg.radius == 7) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}, {2, 2}, {-2, 2}, {-2, -2}, {2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}, {3, 3}, {-3, 3}, {-3, -3}, {3, -3}, {4, 0}, {0, 4}, {-4, 0}, {0, -4}};
        } else if (yg.radius == 8) {
            coordinates = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}, {2, 0}, {0, 2}, {-2, 0}, {0, -2}, {2, 2}, {-2, 2}, {-2, -2}, {2, -2}, {3, 0}, {0, 3}, {-3, 0}, {0, -3}, {3, 3}, {-3, 3}, {-3, -3}, {3, -3}, {4, 0}, {0, 4}, {-4, 0}, {0, -4}, {4, 4}, {-4, 4}, {-4, -4}, {4, -4}};
        }
        for (int[] coordinate : coordinates) {
            Hit(coordinate[0], coordinate[1], yg.damage);
        }

字符串
(Yes,我都是手工写的()现在,问题是。我怎么能自动地写这个?我的意思是我不想用手把这些都写到yg.radius 20上。
我需要一个函数,它将半径作为参数,并返回坐标数组。也许我做错了,我只需要一个数组,它可以给我一个圆形效果的像素。提前感谢!

3phpmpom

3phpmpom1#

下面可以帮助你,你可以试试看吗?

int[][] getCoordinatesInCircle(int radius) {
int[][] coordinates = new int[4 * radius * radius + 1][];  // Allocate space for all coordinates
int index = 0;

for (int x = -radius; x <= radius; x++) {
    for (int y = -radius; y <= radius; y++) {
        if (x * x + y * y <= radius * radius) {  // Check if within circle
            coordinates[index++] = new int[]{x, y};
        }
    }
}
return coordinates; }

字符串

相关问题