cellular-automata/lib/App.dart

68 lines
No EOL
1.6 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
int _MS_PER_STEP = 1000 ~/ 3;
// Max Frame (i.e. Rendering) rate - does *not* impact game speed
final int _MS_PER_FRAME = 1000 ~/ 30;
// 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;
Grid grid = new Grid(100,100);
bool running = false;
App(this.canvas) {
_elapsed.start();
var runBtn = html.querySelector("#run");
runBtn.onClick.forEach((html.MouseEvent mouse) {
running = !running;
if(running) runBtn.innerHtml = "Stop";
if(!running) runBtn.innerHtml = "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");
if (running) grid.update();
}
void render([num interp]) {
// print("rendering");
grid.render(canvas, interp);
}
}