我有一个 csv 文件,其中的数字(即 0、2、34、0、2...)全都在一行上。我正在使用扫描仪从文件中读取它们。该文件代表了一个非常大的游戏内 map 。我知道这张 map 的宽度和高度。在扫描此文件时,我只想捕获下图中的棕色矩形(游戏 map 的一部分)。我正在扫描文件并希望将 csv 文件中的值放入短[]中。
int mapWidth = 8;
int mapHeight = 6;
int rectangleWidth = 5;
int rectangleHeight = 3;
short[] tmpMap = new short[rectangleWidth * rectangleHeight];
Scanner scanner = new Scanner(new File(path));
scanner.useDelimiter(", ");
我也很幸运知道我需要的矩形的 4 个角。深棕色方 block (我需要捕获的矩形的四个角)可以表示为:
int topLeftIndex = 17;
int topRightIndex = 21;
int bottomLeftIndex = 33;
int bottomRightIndex = 37;
我知道在我的扫描方法中,我可以检查我是否在矩形和蓝色突出显示框的范围内,如下所示:
if (count >= topLeftIndex && count <= bottomRightIndex){
//within or outside (east and west) of rectangle
我无法思考识别和不存储蓝色突出显示方 block 的逻辑。
这个矩形的大小、整个 map 的大小和深棕色点只是数字示例,并且会发生变化,但我将永远知道它们。谁能帮帮我吗?
这是我到目前为止所拥有的:
private static short[] scanMapFile(String path, int topLeftIndex,
int topRightIndex, int bottomLeftIndex, int bottomRightIndex)
throws FileNotFoundException {
Scanner scanner = new Scanner(new File(path));
scanner.useDelimiter(", ");
short[] tmpMap = new short[mapWidth * mapHeight];
int count = 0;
int arrayIndex = 0;
while(scanner.hasNext()){
if (count >= topLeftIndex && count <= bottomRightIndex){
//within or outside (east and west) of rectangle
if (count == bottomRightIndex){ //last entry
tmpMap[arrayIndex] = Short.parseShort(scanner.next());
break;
} else { //not last entry
tmpMap[arrayIndex] = Short.parseShort(scanner.next());
arrayIndex++;
}
} else {
scanner.next(); //have to advance scanner
}
count++;
}
scanner.close();
return tmpMap;
}
注意:这不是学校作业:)任何帮助将不胜感激。
最佳答案
你可以这样:
public boolean isInside(int n) {
if(n >= topLeftIndex && n <= bottomRightIndex) {
if(n % mapWidth >= topLeftIndex % mapWidth
&& mapWidth % mapWidth <= bottomRightIndex % mapWidth) {
return true;
}
}
return false;
}
这首先检查您已经检查过的内容,然后检查“列”是否正确。 如果您知道左上角索引、右下角索引和 map 宽度,则此方法始终有效。
关于java - 使用外部点查找矩形内部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27932351/