检查数组是否有值

时间:2014-09-15 09:22:25

标签: java

首先,看看这个Snake-Game。

我的问题是,方法locateApple()在随机位置生成苹果。

有时它直接在蛇身上产生。我该如何防止这种情况?

一种方法可以是检查Snake体的阵列。但我不知道该怎么做。

谢谢。

2 个答案:

答案 0 :(得分:0)

如果没有合适的位置,您可以丢弃苹果并尝试新的位置......

Point position = null;
do{
    Point candidate = createRandomLocation();
    double distance = measureDistance(head, candidate);    
    if (distance > 20) { //maybe you check other things as well...
        position = new Poisition(candidate)
    }
}while(position ==null);

答案 1 :(得分:0)

假设您有一个Coordinate类,其中包含xy的2个值。这个类的方法如下:

  • int getX();获取x坐标
  • 的值
  • int getY();获取y坐标
  • 的值

现在您还需要一个包含多个坐标的CoordinateContainer类。

Coordinate容器类可以包含(以及其他..)方法,如:

  • void add(Coordinate x);添加坐标。
  • Coordinate getCoordinate(Coordinate x);获取坐标
  • `boolean contains(坐标x);检查容器是否包含特定坐标。

等等。

现在您可以将蛇表示为CoordinateContainer

contains方法的实现可能如下所示:

public boolean contains(Coordinate x){
    for(int i = 0; i < numOfCoordinates; i++) //numOfCoordinates is an int holding how many Coordinates you have passed in the array.
        if(array[i].getX() == x.getX() && array[i].getY() == x.getY()) return true;
    return false; // Compare value of X,Y of each Coordinate with the respective X,Y of the parameter Coordinate.
}

既然您有办法检查Coordinate中是否包含CoordinateContainer,那么您就可以了。放置苹果的方法可能如下所示:

private void placeNewApple(){
    Coordinate newApple = apples.getRandom(); //<-- getRandom() returns a random Coordinate within the board        
    while(snake.contains(newApple)){
        newApple = apples.getNew();
    }
    placeApple(newApple);// method to place an apple at newApple.getX() , newApple.getY();
}

希望这是有道理的

注意:如果您没有/想要这样做,即使用单独的类,并且您只在主程序中有Array请添加一些代码对你的问题,我会更新我的答案。

相关问题