Fix Rendering when no Changes occured

Rendering checks a dirty flag which gets set whenever a cell updates by changing their state.
This commit is contained in:
Marty Oehme 2018-07-07 19:08:26 +02:00
parent 5a10c0e1f7
commit 70e33fe135
2 changed files with 13 additions and 0 deletions

View File

@ -6,11 +6,16 @@ class Cell {
List<Rule> surviveRules = new List<Rule>();
List<Rule> birthRules = new List<Rule>();
/// For determining if render updates are necessary in [Grid].render() function
bool dirty = false;
Cell([bool state = false]) : this.state = state;
void advanceState() {
this.state = this.nextState;
this.nextState = false;
this.dirty = true;
}
void update(int neighbors) {

View File

@ -8,6 +8,8 @@ class Grid {
final int h;
final List<List<Cell>> map;
bool _dirty = true;
Grid(int w, int h)
: this.w = w,
this.h = h,
@ -82,6 +84,7 @@ class Grid {
for (int x = 0; x < w; x++) {
// DEFAULTS TO CONWAY GAME OF LIFE RANGE OF ONE
map[y][x].update(getSurroundingNeighbors(x, y, 1));
if (!_dirty && map[y][x].dirty) _dirty = true;
}
}
for (int y = 0; y < h; y++) {
@ -110,6 +113,9 @@ class Grid {
}
void render(html.CanvasElement canvas, [num interp]) {
// only renders if any cells changed between renders
if (!_dirty) return;
html.CanvasRenderingContext2D ctx = canvas.getContext('2d');
int brickW = (canvas.width ~/ map[0].length);
int brickH = (canvas.height ~/ map.length);
@ -124,5 +130,7 @@ class Grid {
ctx.fillRect(x * brickW, y * brickH, brickW, brickH);
}
}
_dirty = false;
}
}