#include "library.h" const int size = 60; // the grid has 60 x 60 squares bool alive[size][size]; const int border = 50; // 50 pixel empty border around the edge const int cell_size = 10; // each square is 10 pixels wide const int grid_size = 2*border + size*cell_size; void draw() { int line = 0; fill_rectangle(0, 0, grid_size, grid_size, color::white); while (line <= size) { move_to(border + line * cell_size, border); draw_to(border + line * cell_size, border + size * cell_size); move_to(border, border + line * cell_size); draw_to(border + size * cell_size, border + line * cell_size); line = line + 1; } int i = 0; while (i < size) { int j = 0; while (j < size) { if (alive[i][j]) { const int x = border + j * cell_size; const int y = border + i * cell_size; fill_rectangle(x, y, cell_size, cell_size, color::red); } j = j + 1; } i = i + 1; } } void init() { int i = 0; while (i < size) { int j = 0; while (j < size) { alive[i][j] = false; j = j + 1; } i = i + 1; } while (true) { draw(); wait_for_mouse_click(); const int x = get_click_x(); const int y = get_click_y(); if (x < border) // click in the left border to finish break; const int cellx = (x - border) / cell_size; const int celly = (y - border) / cell_size; alive[celly][cellx] = ! alive[celly][cellx]; } } bool safelook(int a, int b) { if (a<0 || b<0 || a>=size || b>=size) return false; return alive[a][b]; } int count_neighbours(int i, int j) { int count = 0; int a = -1; while (a <= 1) { int b = -1; while (b <= 1) { if (a!=0 || b!=0) { if (safelook(i+a, j+b)) count = count + 1; } b = b + 1; } a = a + 1; } return count; } void step() // This isn't correct yet. The fate of every cell depends { int i = 0; // on the initial conditions. Neighbours dying or being born while (i < size) // must have no effect until the next cycle. { int j = 0; while (j < size) { const int neigh = count_neighbours(i, j); // the rules: for each cell count how many of its // eight neighbours are alive: // less than 2, it dies of loneliness // more than 3, it dies from overcrowding // exactly 2, no change // exactly 3, it comes to life if (neigh < 2 || neigh > 3) alive[i][j] = false; else if (neigh == 3) alive[i][j] = true; j = j + 1; } i = i + 1; } } void main() { make_window(grid_size, grid_size); init(); step(); draw(); }