Randomly distribute objects on grid

Don’t worry about asking, fire away!

For chessboards (example) they often combine letters and numbers to indicate a tile on the board. For this situation having two separate arrays would suffice– one for the rows, the other for the columns. By using 16 values (8 + 8) you can indicate each tile’s location.

If you want to code some funky coloured chessboard where each tile has a different colour, two separate arrays might not be optimal (you could creatively find different ways to solve the issue, but let’s forget about that for now). Because you need to save a unique colour value for each tile on the board, it might be better to go for a double array:

color[][] tileColours = new color[8][8];
int size;

void setup() {
  size(400, 400);
  noStroke();
  size = width / 8;
  prepArray();
}

void draw() {
  drawArray();
}

void prepArray() {
  for (int i = 0; i < 8; i++) {
    for (int j = 0; j < 8; j++) {
      float r = random(255);
      float g = random(255);
      float b = random(255);
      tileColours[i][j] = color(r, g, b);
    }
  }
}

void drawArray() {
  for (int i = 0; i < 8; i++) {
    for (int j = 0; j < 8; j++) {
      color c = tileColours[i][j];
      float x = i * size;
      float y = j * size;
      fill(c);
      rect(x, y, size, size);
    }
  }
}

Compared to the two singular arrays which have 16 values in total, the double array in this example contains 64 values.

Does that make the added value of double arrays more clear?

2 Likes