Skip to content

Commit

Permalink
ref: use ticker.delayed instead of reimplementing it
Browse files Browse the repository at this point in the history
  • Loading branch information
adil192 committed Sep 10, 2024
1 parent bca9feb commit 8adac1f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
15 changes: 7 additions & 8 deletions lib/flame/ricochlime_game.dart
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,7 @@ class RicochlimeGame extends Forge2DGame

/// Moves the existing monsters down and spawns new ones at the top
Future<void> spawnNewMonsters() async {
const monsterMoveSeconds = 1;
const monsterMoveDuration = Duration(seconds: monsterMoveSeconds);
const monsterMoveDuration = Duration(seconds: 1);

state.value = GameState.monstersMoving;

Expand All @@ -465,12 +464,12 @@ class RicochlimeGame extends Forge2DGame
}

// wait for the monsters to move
var elapsedSeconds = 0.0;
await for (final tick in ticker.onTick) {
if (inputCancelled) return;
elapsedSeconds += tick;
if (elapsedSeconds >= monsterMoveSeconds) break;
}
await ticker.delayed(
monsterMoveDuration,
onTick: () =>
inputCancelled ? TickerDelayedInstruction.stopEarly : null,
);
if (inputCancelled) return;

// check if the player has lost
if (isGameOver()) {
Expand Down
28 changes: 25 additions & 3 deletions lib/flame/ticker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,38 @@ class Ticker {
/// The actual time may be slightly longer than the given
/// [duration] since it is rounded to the next tick.
///
/// Returns the elapsed time in seconds.
Future<double> delayed(Duration duration) async {
/// If [onTick] is provided, it will be called for each tick,
/// including the final tick when the duration is reached/passed.
/// Return [TickerDelayedInstruction.stopEarly] in [onTick] to stop the
/// ticker early.
///
/// Returns the actual elapsed time in seconds.
Future<double> delayed(
Duration duration, {
TickerDelayedInstruction? Function()? onTick,
}) async {
final durationInSeconds = duration.inMilliseconds / 1000;
var elapsed = 0.0;
await for (final dt in onTick) {
await for (final dt in this.onTick) {
elapsed += dt;

switch (onTick?.call()) {
case TickerDelayedInstruction.stopEarly:
return elapsed;
default:
break;
}

if (elapsed >= durationInSeconds) return elapsed;
}
throw StateError(
'Ticker.delayed: Game was disposed before the duration passed',
);
}
}

enum TickerDelayedInstruction {
/// Return this value in [Ticker.delayed]'s `onTick`
/// to stop the ticker early.
stopEarly,
}

0 comments on commit 8adac1f

Please sign in to comment.