Fix Simulation Neighbor Propagation

This commit is contained in:
Marty Oehme 2018-08-30 12:03:23 +02:00
parent b95d39d2b4
commit a324d52df5

View file

@ -23,11 +23,14 @@ class Simulation {
int get w => map.width; int get w => map.width;
int get h => map.height; int get h => map.height;
Simulation(int w, int h) : this.map = new Grid.fill(w, h, _getGOLCell()) { Simulation(int w, int h) : this.map = new Grid(w, h) {
for (int i = 0; i < map.length; i++) {
map[i] = _getGOLCell();
}
print("Grid creation finished"); print("Grid creation finished");
} }
static Cell _getGOLCell([bool defaultState = false]) { Cell _getGOLCell([bool defaultState = false]) {
Cell cell = Cell(defaultState); Cell cell = Cell(defaultState);
Rule threeTrue = new Rule((int n) { Rule threeTrue = new Rule((int n) {
if (n == 3) return true; if (n == 3) return true;
@ -37,8 +40,9 @@ class Simulation {
if (n == 2) return true; if (n == 2) return true;
return false; return false;
}); });
cell.surviveRules..add(twoTrue)..add(threeTrue); cell.surviveRules.add(twoTrue);
cell.birthRules.add(twoTrue); cell.surviveRules.add(threeTrue);
cell.birthRules.add(threeTrue);
return cell; return cell;
} }
@ -133,21 +137,20 @@ class Simulation {
if (el.state != el.nextState) stateChanges = true; if (el.state != el.nextState) stateChanges = true;
el.advanceState(); el.advanceState();
}); });
stateChanges ? _dirty = true : false;
return stateChanges; return stateChanges;
} }
int getSurroundingNeighbors(int x, int y, int range) { int getSurroundingNeighbors(int x, int y, int range) {
int count = 0; int count = 0;
for (int iy = y - range; iy <= y + range; iy++) { for (int ix = -range + x; ix <= range + x; ix++) {
for (int ix = x - range; ix <= x + range; ix++) { for (int iy = -range + y; iy <= range + y; iy++) {
if (ix > 0 && if (ix >= 0 &&
iy > 0 && iy >= 0 &&
iy < map.height &&
ix < map.width && ix < map.width &&
map.get(x, y).state == true && iy < map.height &&
!(x == ix && y == iy)) { map.get(ix, iy).state == true &&
count++; !(x == ix && y == iy)) count++;
}
} }
} }
return count; return count;
@ -161,8 +164,7 @@ class Simulation {
int brickW = (canvas.width ~/ map.width); int brickW = (canvas.width ~/ map.width);
int brickH = (canvas.height ~/ map.height); int brickH = (canvas.height ~/ map.height);
ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.clearRect(0, 0, canvas.width, canvas.height);
for (int i = 0; i < map.length; i++) {
for (int i; i < map.length; i++) {
math.Point p = map.toCoordinates(i); math.Point p = map.toCoordinates(i);
if (_renderEdges) { if (_renderEdges) {
ctx.setStrokeColorRgb(100, 100, 100); ctx.setStrokeColorRgb(100, 100, 100);
@ -175,7 +177,6 @@ class Simulation {
ctx.setFillColorRgb(0, 0, 0); ctx.setFillColorRgb(0, 0, 0);
ctx.fillRect(p.x * brickW, p.y * brickH, brickW, brickH); ctx.fillRect(p.x * brickW, p.y * brickH, brickW, brickH);
} }
_dirty = false; _dirty = false;
} }