cellular-automata/lib/Grid.dart
2018-07-06 15:00:45 +02:00

68 lines
1.6 KiB
Dart

import 'Cell.dart';
import 'Rule.dart';
class Grid {
final int w;
final int h;
final List<List<Cell>> map;
Grid(int w, int h)
: this.w = w,
this.h = h,
this.map = new List() {
map.addAll(_buildGrid(w, h));
map[5][5].state = true;
map[5][6].state = true;
map[5][7].state = true;
print("Grid creation finished");
}
List<List<Cell>> _buildGrid(int w, int h) {
print("grid being created");
List<List<Cell>> grid = new List(h);
Rule threeTrue = new Rule((int n) {
if(n==3) return true;
return false;
});
Rule twoTrue = new Rule((int n) {
if(n==2) return true;
return false;
});
for (int y = 0; y < h; y++) {
grid[y] = new List(w);
for (int x = 0; x < w; x++) {
// GIVES RULES FOR CONWAY GAME OF LIFE BY DEFAULT S23/B3
Cell cell = new Cell();
cell.surviveRules.add(twoTrue);
cell.surviveRules.add(threeTrue);
cell.birthRules.add(threeTrue);
grid[y][x] = cell;
}
}
return grid;
}
void update() {
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
// DEFAULTS TO CONWAY GAME OF LIFE RANGE OF ONE
map[y][x].update( getSurroundingNeighbors(x, y, 1) );
}
}
}
int getSurroundingNeighbors(int x, int y, int range) {
int count = 0;
for (int iy = y - range; iy <= y + range; iy++) {
for (int ix = x - range; ix <= x + range; ix++) {
if (ix > 0 && iy > 0 && iy < map.length && ix < map[iy].length && map[iy][ix].state == true && !(x == ix && y == iy)) {
count++;
}
}
}
return count;
}
}