cellular-automata/lib/Grid.dart
2018-07-05 17:59:11 +02:00

63 lines
1.5 KiB
Dart

import 'package:rules_of_living/Cell.dart';
import 'package:rules_of_living/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;
}
List<List<Cell>> _buildGrid(int w, int h) {
List<List<Cell>> grid = new List(h);
Rule threeTrue = new Rule((int n) {
if(n==3) return true;
else return false;
});
Rule twoTrue = new Rule((int n) {
if(n==2) return true;
else 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(twoTrue);
grid[y][x] = new 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( getNeighbors(x, y, 1) );
}
}
}
int getNeighbors(int x, int y, int range) {
int count = 0;
for (int iy = y - range ~/ 2; iy < iy + range / 2; iy++) {
for (int ix = x - range ~/ 2; ix < ix + range / 2; ix++) {
if (iy > 0 && iy < map.length && ix > 0 && ix < map[iy].length &&
map[iy][ix].state == true) count++;
}
}
return count;
}
}