Problem to draw multiple rectangles with loop.

edited January 2018 in Questions about Code

Hello, i have some trouble making my code work, let me explain :

First we have to draw rectangles everytime there is a 1 on this array :

  int[][] alienSprite = {
    {1, 0, 1, 1, 1, 0, 1}, 
    {0, 1, 0, 1, 0, 1, 0},
    {1, 1, 1, 1, 1, 1, 1},
    {0, 1, 0, 1, 0, 1, 0},
    {1, 0, 0, 0, 0, 0, 1}
  };

The next thing is to store the position where the invaders will spawn :

  int[] posAlienX = new int[8];

  void setup() { 
    size (800, 600); 
    for (int i = 0; i <posAlienX.length; i++){ 
      posAlienX[i] = x; 
      x = x +100;
    }
  }

Till now it was very basic stuff, i created 2 arrays, one for the rectangles "pattern", one for the invaders positions...

void alien(){

  int spriteY = 20;
  int n = 0;

  for (int s = 0; s < posAlienX.length; s++){
    int spriteX = posAlienX[s];

    while (n < 7) {

      for (int i = 0; i < alienSprite.length; i++ ){

        if (alienSprite[i][n] == 1){
          fill(125);
          rect(spriteX,spriteY,5,5);
          spriteY = spriteY + 5;
        }
        else if (alienSprite[i][n] == 0){
          spriteY = spriteY + 5; 
        }
      }

      spriteX = spriteX +5;

      spriteY = 20;

      n++;
    }
  } 
}

when i enter the loop i want SpriteX to be the position of the cell, but it doesn't work.

Unfortunately it draw only one invader (i need 8). I don't understand because i have a loop to change my SpriteX position with the AlienX array. Again i'm new to Java and programming, so thanks for your help and your patience.

it give me this :

Sans titre

Answers

  • start by formatting the code. edit your post, highlight the code bits, press ctrl-o.

    then change the subject so it says something more useful than 'my code doesn't work' - we get 100 of those a week, yours will get lost if you don't add something descriptive to it. 'aliensprite'?

  • will do !

  • Answer ✓

    what is n after the first s loop has finished?

    what is n when the second s loop starts?

  • edited January 2018

    Oh i see, i need to reset n to 0 at the end of the first loop because when the second loop start n == 7...

    Thank you for your help ! i'm struggling on it since this morning

  • yes. in fact you can just move line 4 after line 6...

    or use a for loop for n instead of a while loop

    BUT this is a weird way to do what you are doing, which is just drawing 8 aliens on screen, one pixel at a time. what's up with using an image?

  • Yeah it's not practical at all but it's for an exercice, to familiarise with Two-Dimensional Arrays... now i have to do the same thing with the Arraylist. =)

Sign In or Register to comment.