Many simple games take place on grids – Tetris or Minesweeper are examples. So how can we do that? We’ll want to use a grid to keep track of what’s going on.

Something we can use, is what’s called a** 2-dimensional array**. We can declare one of those like this:

int[][] grid = new int[width][height]

See the similarity?

We’re going to use that here to make a gradient of red and blue. We’ll divide our applet into a grid, and increase the amount of red in one direction, and the amount of blue in the other.

We’ll need some variables:

int sqsize = 10; int wh = 500; int n; int[][] rgrid; int[][] bgrid;

In our setup() method, we’ll fill the arrays with values, like this:

void setup() { size(500, 500); noLoop(); n = wh/10; rgrid = new int[n][n]; bgrid = new int[n][n]; // give initial values to first row of red and first column of blue for (int i = 0; i < n; i++) { bgrid[0][i] = 1; rgrid[i][0] = 1; } // now calculate the rest of them for (int i = 1; i < n; i++) { for (int j = 0; j < n; j++) { int r = rgrid[j][i-1] + 5; if (r > 255) { r = 1; } rgrid[j][i] = r; int b = bgrid[i-1][j] + 5; if (b > 255) { b = 1; } bgrid[i][j] = b; } } }

Then, in our draw method we can set the color using the value from that point in the grid.

void draw() { // use r and b values to pick color for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { stroke(255); fill(rgrid[i][j], 0, bgrid[i][j]); rect(i*sqsize, j*sqsize, sqsize-2, sqsize-2); } } }

How’s that look? I added some green to mine – can you work out how I did it? What happens when we change how much we increase the color (in setup()). What other cool things can we do using this?

Pingback: Processing » Archive » Pacman