A repeated color pattern

I have written this code.

void setup(){
  size(800,400);
  background(0);
}
void draw(){
  cave();
  stone();
}

void cave(){
  noStroke();
  fill(160);
  rect(0,100,width,200);
}

void stone(){
  for(int i=0;i<width;i+= 30){
    stroke(0);
    fill(255,0,0);
    rect(i,100,30,30);
    rect(i,300,30,30);
    
    
  }
  
}

how can i make this 1st stone red, then green and then blue repeatedly? please help me with this.

You have 2 ways of doing it.

The first one is to draw 3 bricks at a time in your for loop and this way you draw one red, one green and one blue.

The second way is to have a variable that keep track of the color you want and in your for loop you check the value of that variable and set the color accordingly. At the end of the for loop you would then need to change the value of the variable.

would u plz give me an example of the second way

There you go.
It is a bit different than your code because Iā€™m using the draw() function to simulate your for loop but the idea stays the same:

int col;

void setup() {
  col = 0;
  frameRate(2);
}

void draw() {
  if (col == 0) {
    background(255,0,0);
  } else if (col == 1) {
    background(0,255,0);
  } else if (col == 2) {
    background(0,0,255);
  }
  
  col++;
  if (col == 3) {
    col = 0;
  }
}

You want something like that ?

color c[] = new color[3];
int n=0;

void setup() {
  size(800, 400);
  background(0);
  c[0]=color(255, 0, 0); // first color
  c[1]=color(0, 255, 0); // second
  c[2]=color(0, 0, 255); // third
}

void draw() {
  cave();
  stone();
}

void cave() {
  noStroke();
  fill(160);
  rect(0,100,width,200);
}

void stone() {
  for(int i=0; i<width; i+=30){
    stroke(0);
    fill(c[n]);
    rect(i,100,30,30);
    rect(i,300,30,30);
    n++;
    if(n>2) n=0;
  }
}
1 Like

Thanks for ur great help