是否有用于选择Java中2d数组特定部分的函数?

问题描述 投票:-1回答:2

因此,我有一个学校项目,该项目有2个玩家,并使用武器,陷阱和食物类,并将它们随机放置在阵列的特定部分。我为每个数组构造了一个具有相应类类型的2d数组,每个数组分别称为WeaponAreaLimitsFoodAreaLimitsTrapAreaLimits

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,-33,-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
    }
}

我的问题是,有没有消除这些问题的方法或方法?

java arrays random 2d
2个回答
0
投票

在您的示例中,您必须在外部区域(foodAreaLimits)中生成一个不属于内部区域(weaponAreaLimits)的点。正确的方法可能取决于区域形状,例如如果内部区域是一个圆形而外部区域是一个三角形怎么办?

您可以使用此算法解决问题:

  1. foodAreaLimits内生成一个随机点
  2. 如果在weaponAreaLimits之外就足够了。
  3. 否则将随机选择方向。您只在处理int,所以很简单:西,东,北,南。
  4. 更改新点的方向坐标,直到移到weaponAreaLimits之外。您正在处理int,例如向西表示移动{-1,0},因此执行food[i].x--

您可能必须考虑面积有多大,项目分布是什么。如果内部区域和外部区域的大小相近,可能会很棘手。


0
投票

好吧,假设我现在明白了,首先...

您的极限数据可以更简单,只要它们代表矩形极限即可。您只需要minX,maxX,minY,maxY。我将创建一个对象来存储这些对象:

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,直到获得不在内部框内的随机值。但是我们也允许使用一个空的内部盒子,以便我们可以使用相同的方法来处理武器。

现在,此功能缺少什么-我没有检查以确保该位置没有被其他物体占用。如果由于整个区域已满而无法工作,则此方法应返回false。我留给你想象一下,您试图在只能容纳25个武器的区域添加50个武器。

这里有一堆重要的事情。除了代码的基本结构之外,您还可以了解矩形的定义。在该矩形内生成随机数。还有排除代码。

希望这给您足够的前进空间。

© www.soinside.com 2019 - 2024. All rights reserved.