Random keeps looping inside for

Hi!

I’m making an Atari Breakout like game for a school project, and I’m having a lil problem
I want the bricks’ colors be setted randomly

p[] pelota = new p[1];
b[] bloques = new b[100];

void setup(){
  size(900,600);
  println(height);
  rectMode(CENTER);
  
  pelota[0] = new p();
  
  for(int i=0; i<bloques.length; i++){
    bloques[i] = new b();
  }
}

void draw(){
  
  background(27,20,0);
  
  for(int i=0, j=1; j<15; i++){
    bloques[i].crear(i,j,int(random(1,4)),100);
    if(i>6){i=-1;j++;}
  }
  
  /*pelota[0].crear(15);
  pelota[0].mover();
  pelota[0].rebotar();
  */
  
  
}

Here you have the classes:

class b{
  
  int nivel;
  boolean visible = true;
  
  void crear(int c, int f, int n, float l){
    
    float a = l/10;
    float x = 5+5*c+(l*c)+(l/2);
    float y = 5*f+(a*f)+(a/8);
    nivel = n;
    
    switch (nivel){
      case 0:
      visible = false;
      break;
      
      case 1:
      fill(0,255,0);
      break;
      
      case 2:
      fill(255,255,0);
      break;
      
      case 3:
      fill(255,127,0);
      break;
      
      case 4:
      fill(255,0,0);
      break;
      
    }
    
    if(visible){
      rect(x,y,l,a);
    }
    
  }
  
  void destruir(){
    
  }
  
}
class p{
  
  float x = height*0.75;
  float y = width/2;
  
  float xv = 0;
  float yv = 2.5;
  
  float r;
  
  void crear(float d){
    ellipse(x,y,d,d);
    r = d/2;
  }
  
  void mover(){
    x += xv;
    y += yv;
  }
  
  void rebotar(){
    if(x <= 0+r || x>= width-r){
      xv = -xv;
    }
    
    if(y <= 0+r || y >= height-r){
      yv = -yv;
    }
  }
  
}

The problem is that, when I play it, The bricks start to keep changing the colors randomly. I Think the problem is the for loop, but I’m not really sure.

I hope you can help me

1 Like

You could add an instance variable in your b class holding each blocks color, declared in it’s public b()

You could create an array of colors and assign each brick a position in that array.
Then you would declare all the colors in main with the for loop you already have

1 Like