Lesson 1- Grouping and Repetition
Using arrays for organising visual grids:
int gridW = 10;
int gridH = 10;
int stepX = 60;
int stepY = 60;
int shapeWidth = 40;
int shapeHeight = 40;
Graphic[][] GraphicArray;
void setup()
{
size(800, 800);
noStroke();
fill(0);
background(255);
GraphicArray = new Graphic[gridW][gridH];
// translate graphic to the center of the screen
translate((width-(stepX*gridW))/2, (height-(stepY*gridH))/2);
for (int i=0; i < gridW; i++)
{
for (int j = 0; j < gridH; j++)
{
GraphicArray[i][j] = new Graphic(i * stepX, j * stepY, shapeWidth, shapeHeight);
GraphicArray[i][j].draw();
}
}
}
class Graphic
{
PVector _pos;
int _shapeWidth;
int _shapeHeight;
Graphic(int x, int y, int shapeW, int shapeH)
{
_pos = new PVector(x, y);
_shapeWidth = shapeW;
_shapeHeight = shapeH;
}
void draw()
{
pushStyle();
stroke(0);
fill(0);
rect(_pos.x, _pos.y, _shapeWidth, _shapeHeight);
popStyle();
}
}
Using lists:
iint gridW = 10;
int gridH = 10;
int stepX = 60;
int stepY = 60;
int shapeWidth = 40;
int shapeHeight = 40;
ArrayList<Graphic> graphicList = new ArrayList<Graphic>();
void setup()
{
size(800,800);
noStroke();
fill(0);
translate((width-(stepX*gridW))/2, (height-(stepY*gridH))/2);
for(int i=0;i < gridH;i++)
{
for(int j = 0;j < gridW;j++)
{
graphicList.add(new Graphic(i * stepX , j * stepY , shapeWidth, shapeHeight));
}
}
noLoop();
}
void draw()
{
background(255);
translate((width-(stepX*gridW))/2, (height-(stepY*gridH))/2);
for(int i=0;i < graphicList.size();i++)
graphicList.get(i).draw();
}
class Graphic
{
PVector _pos;
int _shapeWidth;
int _shapeHeight;
Graphic(int x,int y,int shapeW, int shapeH)
{
_pos = new PVector(x,y);
_shapeWidth = shapeW;
_shapeHeight = shapeH;
}
void draw()
{
pushStyle();
stroke(0);
fill(0);
rect(_pos.x,_pos.y, _shapeWidth, _shapeHeight);
popStyle();
}
}