-1

I'm making a simple game where a bunch of objects in an array appear at the same time. Pressing the mouse will remove the array of objects in a class (sample code below). When it hits 0 want it to head into another game State. I'm still so new at this...

void mousePressed() {

if (gameState == RUN_GAME) {
objects.remove(0);
}
}

When it hits 0 and theres no more objects in the sketch and you mouse press, processing automatically freezes. I've tried something like this (below) but it obviously doesn't work. How could I tell the if statement to change the gameState once the array list of objects hit 0? I hope I'm making sense.

void runGame(){

if (objects.length == 0) {
gameState == WINNER);
}
}
hamed
  • 7,939
  • 15
  • 60
  • 114
dazz
  • 1

2 Answers2

1

It looks like you're confusing arrays with ArrayLists.

Arrays are fixed-length "blocks" of variables that you can access via indexes. Here's an example that creates an array of 10 integers:

int[] array = new int[10];
for(int i = 0; i < array.length; i++){
   array[i] = i;
}

Notice the use of array.length, which gives you the number of indexes the array can contain- not the number of indexes that have been set to a value.

You cannot increase the size of an array, and arrays do not have a remove() function. But Processing does contain append() and shorten() methods that take an array and return another array that contains the same items, only with an index removed or added.

ArrayLists, on the other hand, are dynamically-sized Objects that contain an arbitrary number of indexes. You can add or remove other objects to an ArrayList. Here is an example of that:

ArrayList<Integer> arrayList = new ArrayList<Integer>();
for(int i = 0; i < 10; i++){
   arrayList.add(i);
}

ArrayLists do not have a length variable- instead, they have a size() method. This method does return the number of Objects that have been added to it.

So the answer to your question is that you need to decide whether you're using an array or an ArrayList, then stick with the methods that are appropriate for that type.

More info can be found in the Processing API: https://www.processing.org/reference/

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
  • Thanks for the information! I'm sorry I didn't provide that information earlier. I'm using an ArrayList. Now I'm trying to call for the size() within the if statement but I don't think that's working either..I'll keep working on it. if (objects.size() < 0) { gameState = WINNER; } – dazz Apr 23 '15 at 16:52
  • @dazz The size will never be **less than** zero. It might be **equal to** zero, though. You might also use the ArrayList.isEmpty() function. – Kevin Workman Apr 23 '15 at 16:55
  • Everything works now! You've been a great help. Thank you so much! – dazz Apr 23 '15 at 17:18
0

Assuming that you are using Java, you can do it by using the following code:

if (objects.isEmpty()) 
{ 
      gameState = WINNER; 
}
ahmet
  • 61
  • 1
  • 8