feat: Add removeWhere to Component (#1878)

Since removeWhere will be removed from the ComponentSet in #1877 we should expose it on the component.
This commit is contained in:
Lukas Klingsbo
2022-08-30 21:02:08 +02:00
committed by GitHub
parent b1a6dd18f2
commit abd28f28a6
3 changed files with 36 additions and 2 deletions

View File

@ -580,6 +580,15 @@ class Component {
components.forEach(remove);
}
/// Removes all the children for which the [test] function returns true.
void removeWhere(bool Function(Component component) test) {
children.forEach((component) {
if (test(component)) {
remove(component);
}
});
}
/// Remove the component from its parent in the next tick.
void removeFromParent() {
_parent?.remove(this);

View File

@ -33,6 +33,12 @@ class _ParentOnPrepareComponent extends _OnPrepareComponent {
}
}
class _IdentifiableComponent extends Component {
final int id;
_IdentifiableComponent(this.id);
}
void main() {
final prepareGame = FlameTester(_PrepareGame.new);
@ -344,6 +350,26 @@ void main() {
game.update(0);
},
);
testWithFlameGame(
'removeWhere removes the correct components',
(game) async {
final components = List.generate(
10,
_IdentifiableComponent.new,
);
game.addAll(components);
await game.ready();
expect(game.children.length, 10);
game.removeWhere((c) => (c as _IdentifiableComponent).id.isEven);
game.update(0);
expect(game.children.length, 5);
expect(
game.children.every((c) => (c as _IdentifiableComponent).id.isOdd),
true,
);
},
);
});
prepareGame.test(

View File

@ -2,7 +2,6 @@ import 'package:flame/components.dart';
import 'package:flame/game.dart';
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_bloc_example/src/game/components/enemy.dart';
import 'package:flame_bloc_example/src/game/components/enemy_creator.dart';
import 'package:flame_bloc_example/src/game/components/player.dart';
@ -19,7 +18,7 @@ class GameStatsController extends Component with HasGameRef<SpaceShooterGame> {
newState.status == GameStatus.initial;
},
onNewState: (state) {
gameRef.children.removeWhere((element) => element is EnemyComponent);
gameRef.removeWhere((element) => element is EnemyComponent);
},
),
);