Line data Source code
1 : import 'dart:math'; 2 : import 'dart:ui'; 3 : 4 : import 'components/component.dart'; 5 : 6 : /// Simple utility class that helps handling time counting and implementing 7 : /// interval like events. 8 : class Timer { 9 : final double limit; 10 : VoidCallback? callback; 11 : bool repeat; 12 : double _current = 0; 13 : bool _running = false; 14 : 15 1 : Timer(this.limit, {this.callback, this.repeat = false}); 16 : 17 : /// The current amount of ms that has passed on this iteration 18 2 : double get current => _current; 19 : 20 : /// If the timer is finished, timers that repeat never finish 21 5 : bool get finished => _current >= limit && !repeat; 22 : 23 : /// Whether the timer is running or not 24 2 : bool isRunning() => _running; 25 : 26 : /// A value between 0.0 and 1.0 indicating the timer progress 27 5 : double get progress => min(_current / limit, 1.0); 28 : 29 1 : void update(double dt) { 30 1 : if (_running) { 31 2 : _current += dt; 32 3 : if (_current >= limit) { 33 1 : if (!repeat) { 34 1 : _running = false; 35 2 : callback?.call(); 36 : return; 37 : } 38 : // This is used to cover the rare case of _current being more than 39 : // two times the value of limit, so that the callback is called the 40 : // correct number of times 41 3 : while (_current >= limit) { 42 3 : _current -= limit; 43 2 : callback?.call(); 44 : } 45 : } 46 : } 47 : } 48 : 49 1 : void start() { 50 1 : _current = 0; 51 1 : _running = true; 52 : } 53 : 54 1 : void stop() { 55 1 : _current = 0; 56 1 : _running = false; 57 : } 58 : 59 1 : void pause() { 60 1 : _running = false; 61 : } 62 : 63 1 : void resume() { 64 1 : _running = true; 65 : } 66 : } 67 : 68 : /// Simple component which wraps a [Timer] instance allowing it to be easily 69 : /// used inside a BaseGame game. 70 : class TimerComponent extends Component { 71 : Timer timer; 72 : 73 0 : TimerComponent(this.timer); 74 : 75 0 : @override 76 : void update(double dt) { 77 0 : super.update(dt); 78 0 : timer.update(dt); 79 : } 80 : 81 0 : @override 82 : void render(Canvas canvas) {} 83 : 84 0 : @override 85 0 : bool get shouldRemove => timer.finished; 86 : }