Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

While value in array

edited December 2018

For a snake game, I have the food teleport to a random spot on the screen when you eat it, but it's possible for the food to end up on your tail, and not on an empty space. Basically, I sort of need some way to check if the food's x is in the arrayList for the snake's x, and the smae with y, and if so, to execute an action until that is not true.

Tagged:

• like this....?

ArrayList<Integer> snakeArrayX=new ArrayList();
ArrayList<Integer> snakeArrayY=new ArrayList();

// --------------------------------------------------------------

void setup() {
size(400, 400);
frameRate(60);
}

void draw() {

int x = int(random(width));   // probably gridSize here !!!
int y = int(random(height));

// as long as new apple position x,y is inside snake, the position is not acceptable and gets redefined
while (positionIsInsideSnake(x, y)) {
x = int(random(width));   // probably gridSize here !!!
y = int(random(height));
}//while
//
}//func

boolean positionIsInsideSnake(int x, int y) {

for (int i=0; i<snakeArrayX.size(); i++) {
if (x==snakeArrayX.get(i) && y==snakeArrayY.get(i)) {
return true; // it's inside; we immediately leave the function (because one occurance is enough)
}//if
}//for

// no occurance
return false;
}//func
//

• Yes, thank you. I completely forgot about the possibility of using return true / false.

• A do... while loop is better if you know that the loop is going to be done at least once, less repetition (your lines 13, 14 are identical to lines 18, 19)

void draw() {
int x, y;
do {
x = int(random(width));
y = int(random(height));
} while (positionIsInsideSnake(x, y));
}

(Untested)

• thanks!