How to initialise and use array in game assignment

Okay, follow along with me.

First, we are not going to mess about and use append or shorten at all. We are going to have one array, of a specific, fixed size.

This array will be an array of numbers, where each number will represent an invader.

Thus, the first number in the array represents the first invader.
The second number represents the second invader. And so on.

So, the first question is, how big does this array need to be? Well, because each invader is 70 pixels apart, and the game ends well before the entire screen is filled with invaders, it’s a safe bet that we will never have more than width/70 invaders on the screen at any time. To be extra safe, since this number isn’t very large, we can simply double it.

Now we take a minute to write the code for this.

int[] invaders;

void setup(){
  size(800,300);
  invaders = new int[width/35]; // width * 2 / 70 => width / 35
}

void draw(){}

Next, we need to put some numbers in that array! We know the invaders are going to be represented by numbers. The lowest number that represents an invader is 0. The highest number is 9. If we pick a number outside of the 0-9 range, we can use that number to mean “no invader”. A good choice for this number is -1.

We can use a for loop to fill the array up now.

int[] invaders;

void setup(){
  size(800,300);
  invaders = new int[width/35]; // width * 2 / 70 => width / 35
  for( int i = 0; i < invaders.length; i++){
    invaders[i] = -1; // fill up with no invaders.
  }
}

void draw(){}

Next, we need to draw the invaders. We need a second loop that draws them. For now, let’s put the first invader as x = 0.

int[] invaders;

void setup() {
  size(800, 300);
  invaders = new int[800/35];
  for ( int i = 0; i < invaders.length; i++) {
    invaders[i] = 6;
  }
}

void draw() {
  background(0);
  for ( int i = 0; i < invaders.length; i++) {
    if ( invaders[i] != -1 ) { // If this number does not represent "no invader",
      // Draw it.
      rectMode(CENTER);
      fill(255);
      rect(0 + 70 * i, height/2, 40, 40);
      fill(0);
      text( invaders[i], 0 + 70 * i, height / 2);
    } // End of if not a non-invader
  } // End of for loop.
} // End of draw()

If you run this, you should see invaders, right? Try it!

… Nope. Nothing. So what’s wrong? Nothing is wrong! All the invaders in our array have values of -1, so nothing is drawn for them.

Try changing the value they get set to in the loop!

1 Like