How to initialise and use array in game assignment

Next, we need a couple of functions to deal with the two actions we can do to our array of invaders. First, we need a function to add a new invader. Then we need a function to remove the first invader that matches a given number.

void add_invader(int new_number){

}

void remove_invader(int which_number){

}

How should these functions work? Well, for adding a new invader, if we can add it at position 0, we’re done.

void add_invader(int new_number){
  if( invaders[0] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[0] = new_number;
  }
}

But what if the first space in the array is occupied? Well, we could try the next space…

void add_invader(int new_number){
  if( invaders[0] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[0] = new_number;
  } else {

  if( invaders[1] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[1] = new_number;
  }

  }
}

But what if both of those spaces are full?

void add_invader(int new_number){
  if( invaders[0] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[0] = new_number;
  } else {

  if( invaders[1] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[1] = new_number;
  } else {

  if( invaders[2] == -1 ){ // If there is no invader here,
    // We can add one!
    invaders[2] = new_number;
  }

  }
  }
}

Oh no. This is a lot of typing. My fingers hurt. Could we do this with a loop?

void add_invader(int new_number){
  for( int i = 0; i < invaders.length; i++){
    if( invaders[i] == -1 ){
      invaders[i] = new_number;
      return;
    }
  }
}

Removing an invader looks the same:

boolean remove_invader(int which_number){
  for( int i = 0; i < invaders.length; i++){
    if( invaders[i] == which_number ){
      invaders[i] = -1;
      shift_invader(i);
      return(true);
    }
  }
  return(false);
}

void shift_invader(int i){}

Except we are going to report true or false if we found an invader to remove. Also, what the heck is that shift_invader() function?

void shift_invader(int i){
 if( i+1 < invaders.length){
   invaders[i] = invaders[i+1];
   shift_invader(i+1);
  } else {
   invaders[i] = -1;
  }
}

Convince yourself that this moves the remaining invaders in the array towards the front.

1 Like