Interaction Design WikiProgramming

Arrays and lists for visual grids

Using arrays for organising visual grids:

 

int gridW = 10;
int gridH = 10;
int stepX = 60; // horizontal distance between shapes
int stepY = 60; // vertical distance between shapes
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();
  }
}

 

The same example using lists:

int gridW = 10;
int gridH = 10;
int stepX = 60; // horizontal distance between shapes
int stepY = 60; // vertical distance between shapes
int shapeWidth = 40;
int shapeHeight = 40;
ArrayList<Graphic> graphicList = new ArrayList<Graphic>();

void setup()
{
  size(800, 800);
  noStroke();
  fill(0);
  for (int i=0; i < gridH; i++)
  {
    for (int j = 0; j < gridW; j++)
    {
      graphicList.add(new Graphic(i * stepX, j * stepY, shapeWidth, shapeHeight));
    }
  }
}

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();
  }
}