New version:
- When a field is not empty, it is not considered as being surrounded anymore (even when it has 8 occupied neighbors). (But this is not what you want, right?)
- A surrounded corner or surrounded boeder cell is now recognized as surrounded
//
Cell[][] grid;
int cols = 25;
int rows = 25;
void setup() {
size(500, 500);
grid = new Cell[cols][rows];
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
grid[i][j] = new Cell(i*20, j*20,
20, 20, i, j);
}
}
}
void draw() {
background(0);
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
grid[i][j].display();
}
}
}
//-----------------------------------------------------------------------------
void mousePressed() {
// toggle state of a cell
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if (grid[i][j].isPressed()) {
//toggle
grid[i][j].state =
! grid[i][j].state;
return; // leave
}
}
}
}
boolean isSurrounded( int a, int b) {
// returns true when all (8) neighbour cells are occupied
// This tests also if we are on a wall / corner. This counts as a occupied field.
// When the field is not empty, it is not considered as being surrounded...
if (grid[a][b].state) {
return false; // leave
}
// first count occupied fields (and borders)
int count=0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
// This tests if we are on a wall / corner. This counts as a occupied field.
if ( ( ! fieldIsOK(a+i, b+j) ) &&
(! ( i==0 && j==0) )) {
//
count++;
}
if (fieldIsOK(a+i, b+j) &&
! ( i==0 && j==0) ) {
if (grid[a+i][b+j].state) {
// the next field is occupied
count++;
}
}
}//for
}//for
// Eval count
if (count==8) {
return true;
} else {
return false;
}//else
}//
boolean fieldIsOK(int ai, int bj) {
// returns true when the field is a valid index pair x,y for the grid
if (ai >= 0 && ai < cols &&
bj >= 0 && bj < rows )
return true;
else
return false;
}//
// =========================================================================
class Cell {
int x, y;
boolean state=false;
int scl=20;
int i, j;
int sclx, scly;
Cell(int x_, int y_,
int a_, int b_,
int i_, int j_) {
x = x_;
y = y_;
sclx=a_;
scly=b_;
i=i_;
j=j_;
}
void display() {
if (state)
fill( 255, 2, 2 );
else fill( 255 );
stroke(0);
rect(x, y,
sclx, scly);
if (isSurrounded(i, j )) {
fill(255, 0, 0);
ellipse(x+10, y+10, sclx-8, sclx-8);
}
}
boolean isPressed() {
// returns whether the mouse is inside the cell
if (
mouseX>x&&
mouseY>y&&
mouseX<x+20&&
mouseY<y+20)
return true;
else return false;
}//method
//
}//class
//