cellular-automata/lib/App.dart
2018-07-06 15:00:01 +02:00

76 lines
1.9 KiB
Dart

import 'dart:html' as html;
import 'package:rules_of_living/Cell.dart';
import 'package:rules_of_living/Grid.dart';
class App {
// Elapsed Time Counter - useful for Safety Timeout
Stopwatch _elapsed = new Stopwatch();
// Game Tick Rate - *does* impact game speed
final int _MS_PER_STEP = 1000;
// Max Frame (i.e. Rendering) rate - does *not* impact game speed
final int _MS_PER_FRAME = 1000 ~/ 2;
// ms stuck in updateloop after which game will declare itself unresponsive
final int SAFETY_TIMEOUT = 2000;
num _updateLag = 0.0;
num _drawLag = 0.0;
final html.CanvasElement canvas;
final Grid grid = new Grid(20,20);
List<List<Cell>> map;
App(this.canvas) {
this.map = this.grid.map;
_elapsed.start();
}
void process(num now) {
_drawLag+= _elapsed.elapsedMilliseconds;
_updateLag += _elapsed.elapsedMilliseconds;
_elapsed.reset();
while (_updateLag >= _MS_PER_STEP) {
if (_elapsed.elapsedMilliseconds > SAFETY_TIMEOUT) {
// TODO stub - give warning etc when this occurs
print("ERROR STUCK IN UPDATE LOOP");
break;
}
update();
_updateLag -= _MS_PER_STEP;
}
if (_drawLag >= _MS_PER_FRAME) {
render(_updateLag / _MS_PER_STEP);
_drawLag = 0;
}
}
void update() {
print("updating");
grid.update();
}
void render([num interp]) {
print("rendering");
html.CanvasRenderingContext2D ctx = canvas.getContext('2d');
int brickW = (canvas.width ~/ map[0].length);
int brickH = (canvas.height ~/ map.length);
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
Cell c = map[y][x];
if (c.state == true)
ctx.setFillColorRgb(155, 155, 255);
else
ctx.setFillColorRgb(0, 0, 0);
ctx.fillRect(x * brickW, y * brickH, brickW, brickH);
}
}
}
}