[英]Is there a function for selecting a specific part of a 2d array in Java?
所以,我有一个学校项目,有 2 名玩家,使用武器、陷阱和食物类,并将它们随机放置在阵列的特定部分。 我为它们中的每一个构造了一个具有相应 class 类型的二维数组,每个数组分别称为WeaponAreaLimits
、 FoodAreaLimits
和TrapAreaLimits
。
public class Board{
int[][] weaponAreaLimits = { {-2,2}, {2, 2}, {-2, -2}, {2, -2} };
int[][] foodAreaLimits = { {-3, 3}, {3, 3}, {-3, -3}, {3, -3} };
int[][] trapAreaLimits = { {-4, 4}, {4, 4}, {-4, -4}, {4, -4} }; //These are the specific coordinates that limit the placement of said weapons etc.
....
问题是,武器可以在这些点制成的盒子内,但是,食物必须在武器周围的点上,而不是在 - 3,3 3,3 -3,-3
和3,-3
制成的盒子内。 我构建了一个名为createRandomFood()
的方法,它随机地为Food
对象提供属性。 我坚持的是 x 和 y ,以及如何只使用那些周围的点而不把它们放在不应该放在的地方。 看看我写的:
....
public void createRandomFood(){
for(int i = 1; i < food.length; i++){
food[i].setId(i + 1);
food[i].setX;
food[i].setY;
food[i].setPoints(rand.nextInt(10) + 1); //Ignore the other setters
}
}
我的问题是,有没有办法消除这些点?
在您的示例中,您必须在不属于内部区域( weaponAreaLimits
区域限制)的外部区域( foodAreaLimits
)中生成一个点。 正确的方法可能取决于区域形状,例如,如果内部区域是圆形而外部区域是三角形怎么办?
您可以使用此算法解决问题:
foodAreaLimits
内生成一个随机点weaponAreaLimits
之外就足够了。int
,所以它很简单:西、东、北、南。weaponAreaLimits
。 您正在处理int
所以例如 west 意味着移动 {-1, 0} 所以执行food[i].x--
。您可能必须考虑区域有多大以及项目分布是什么。 如果内部和外部区域的大小接近,则可能会很棘手。
好吧,假设我现在明白了,首先...
您的限制数据可以更简单,只要它们代表矩形限制。 您只需要 minX、maxX、minY、maxY。 我会创建一个 object 来存储这些:
public class Limits {
int minX;
int minY;
int maxX;
int maxY;
public Limits(int x1, y1, x2, y2) {
minX = x1;
minY = y1;
maxX = x2;
maxY = y2;
}
}
然后你的对象变成
Limits weaponAreaLimits = new Limits(-2, -2, 2, 2);
Limits foodAreaLimits = new Limits(-3, -3, 3, 3);
Limits trapAreaLimits = new Limits(-4, -4, 4, 4);
这是有效的,因为一个矩形可以由两个对角线定义。 在这种情况下,我们使用左下角和右上角。 您不需要每个顶点。
现在,您需要这样的方法:
public boolean setPoints(Item item, Limits includeRange, Limits excludeRange) {
// These two variables hold the width & height of the box where things can be
int width = includeRange.maxX - includeRange.minX + 1;
int height = includeRange.maxY - includeRange.minY + 1;
int x;
int y;
do {
x = includeRange.minX + (rand() % width);
y = includeRange.minY + (rand() % height);
// At this point, x and y are inside the includeRange.
// We need to make sure they aren't in the disallowed area
} while ( (excludeRange == null) ||
(x >= excludeRange.minX && x <= excludeRange.maxX &&
y >= excludeRange.minY && y <= excludeRange.maxY) );
// When the above loop exits, you have an x and y that works.
item.x = x;
item.y = y;
return true;
}
我没有通过 java 编译器运行它,因此可能存在语法错误。 但基本上,我们循环,在外盒内随机设置 x 和 y,直到我们得到一个不在内盒内的随机值。 但我们也允许使用 null 内盒,以便我们可以使用相同的方法处理武器。
现在,这里缺少什么——我不是在检查以确保这个位置没有被其他东西占据。 如果由于整个区域已满而无法工作,则此方法应返回 false。 我会把它留给你。 想象一下,您尝试在只能容纳 25 件的区域中添加 50 件武器。
这里有一堆重要的东西。 除了代码的基本结构之外,还有对矩形定义的理解。 该矩形内正在生成随机数。 还有排除代码。
希望这能给你足够的进步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.