Reputation: 35
In the following code, it runs without error, but there is no output. However, when I remove the code from the draw() loop, it outputs successfully. If I put the code in a for loop, then the output only occurs at the end of the for loop, not during the for loop. I don't understand why there is no output in both of these cases.
void setup(){
size(800,800);
}
int rows = height;
int cols = width;
int [][] myArray = new int[rows][cols];
void draw(){
background(255);
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
myArray[i][j]=int(random(255));
}
}
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
fill(myArray[i][j]);
rect(i,j,i+10,j+10);
}
}
}
Upvotes: 1
Views: 164
Reputation: 53578
width
and height
don't have real values until after size()
is called. Just because you've put the variables after the function, does not mean they get assigned after setup()
runs: all global variables are assigned BEFORE any functions are run. So in this case you end up with a width and height of 0, which will draw absolutely nothing because there are no pixels to color =)
You want this instead:
// let's put our global vars up top, to prevent confusion.
// Any global variable that isn't just declared but also
// initialised, gets initialised before *anything* else happens.
int rows, cols;
int[][] myArray;
// Step 2 is that setup() runs
void setup(){
size(800,800);
// now we can initialise values:
rows = width;
cols = height;
myArray = new int[rows][cols];
}
// Setup auto-calls draw() once, and
// then draw() runs at a specific framerate
// unless you've issued noLoop() at some point.
void draw(){
background(255);
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
myArray[i][j]=int(random(255));
}
}
for (int i=0;i<cols;i=i+10){
for (int j=0;j<rows;j=j+10){
fill(myArray[i][j]);
rect(i,j,i+10,j+10);
}
}
}
That said, we don't even need rows
and cols
here, we can just use width
and height
directly, and we don't need two loops, we just need one since we're not using not-yet-set neighbouring pixels when we draw the rectangles. We just need to skip by 10 all the time, which you already do:
int[][] myArray;
// Step 2 is that setup() runs
void setup() {
size(800,800);
myArray = new int[width][height];
}
void draw() {
background(255);
int i, j, step = 10;
for (i=0; i<height; i=i+step) {
for (j=0; j<width; j=j+step) {
myArray[i][j]=int(random(255));
fill(myArray[i][j]);
rect(i,j,i+step,j+step);
}
}
}
Upvotes: 3