diff --git a/.github/workflows/pinball_flame.yaml b/.github/workflows/pinball_flame.yaml new file mode 100644 index 00000000..2263bb5a --- /dev/null +++ b/.github/workflows/pinball_flame.yaml @@ -0,0 +1,20 @@ +name: pinball_flame + +on: + push: + paths: + - "packages/pinball_flame/**" + - ".github/workflows/pinball_flame.yaml" + + pull_request: + paths: + - "packages/pinball_flame/**" + - ".github/workflows/pinball_flame.yaml" + +jobs: + build: + uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 + with: + working_directory: packages/pinball_flame + coverage_excludes: "lib/gen/*.dart" + test_optimization: false diff --git a/lib/flame/flame.dart b/lib/flame/flame.dart deleted file mode 100644 index 9264c0f4..00000000 --- a/lib/flame/flame.dart +++ /dev/null @@ -1 +0,0 @@ -export 'component_controller.dart'; diff --git a/lib/game/bloc/game_bloc.dart b/lib/game/bloc/game_bloc.dart index ba604f17..4ba63092 100644 --- a/lib/game/bloc/game_bloc.dart +++ b/lib/game/bloc/game_bloc.dart @@ -12,7 +12,6 @@ class GameBloc extends Bloc { on(_onBallLost); on(_onScored); on(_onBonusActivated); - on(_onDashNestActivated); on(_onSparkyTurboChargeActivated); } @@ -34,31 +33,6 @@ class GameBloc extends Bloc { ); } - void _onDashNestActivated(DashNestActivated event, Emitter emit) { - final newNests = { - ...state.activatedDashNests, - event.nestId, - }; - - final achievedBonus = newNests.length == 3; - if (achievedBonus) { - emit( - state.copyWith( - balls: state.balls + 1, - activatedDashNests: {}, - bonusHistory: [ - ...state.bonusHistory, - GameBonus.dashNest, - ], - ), - ); - } else { - emit( - state.copyWith(activatedDashNests: newNests), - ); - } - } - Future _onSparkyTurboChargeActivated( SparkyTurboChargeActivated event, Emitter emit, diff --git a/lib/game/bloc/game_event.dart b/lib/game/bloc/game_event.dart index 392cc50f..bbb89028 100644 --- a/lib/game/bloc/game_event.dart +++ b/lib/game/bloc/game_event.dart @@ -42,15 +42,6 @@ class BonusActivated extends GameEvent { List get props => [bonus]; } -class DashNestActivated extends GameEvent { - const DashNestActivated(this.nestId); - - final String nestId; - - @override - List get props => [nestId]; -} - class SparkyTurboChargeActivated extends GameEvent { const SparkyTurboChargeActivated(); diff --git a/lib/game/bloc/game_state.dart b/lib/game/bloc/game_state.dart index aa1144c0..c57eedb4 100644 --- a/lib/game/bloc/game_state.dart +++ b/lib/game/bloc/game_state.dart @@ -23,14 +23,12 @@ class GameState extends Equatable { required this.score, required this.balls, required this.bonusHistory, - required this.activatedDashNests, }) : assert(score >= 0, "Score can't be negative"), assert(balls >= 0, "Number of balls can't be negative"); const GameState.initial() : score = 0, balls = 3, - activatedDashNests = const {}, bonusHistory = const []; /// The current score of the game. @@ -41,9 +39,6 @@ class GameState extends Equatable { /// When the number of balls is 0, the game is over. final int balls; - /// Active dash nests. - final Set activatedDashNests; - /// Holds the history of all the [GameBonus]es earned by the player during a /// PinballGame. final List bonusHistory; @@ -54,7 +49,6 @@ class GameState extends Equatable { GameState copyWith({ int? score, int? balls, - Set? activatedDashNests, List? bonusHistory, }) { assert( @@ -65,7 +59,6 @@ class GameState extends Equatable { return GameState( score: score ?? this.score, balls: balls ?? this.balls, - activatedDashNests: activatedDashNests ?? this.activatedDashNests, bonusHistory: bonusHistory ?? this.bonusHistory, ); } @@ -74,7 +67,6 @@ class GameState extends Equatable { List get props => [ score, balls, - activatedDashNests, bonusHistory, ]; } diff --git a/lib/game/components/alien_zone.dart b/lib/game/components/alien_zone.dart index 1f9befba..30d7bbd5 100644 --- a/lib/game/components/alien_zone.dart +++ b/lib/game/components/alien_zone.dart @@ -3,9 +3,9 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template alien_zone} /// Area positioned below [Spaceship] where the [Ball] diff --git a/lib/game/components/camera_controller.dart b/lib/game/components/camera_controller.dart index aa963e9a..a411942e 100644 --- a/lib/game/components/camera_controller.dart +++ b/lib/game/components/camera_controller.dart @@ -1,7 +1,7 @@ import 'package:flame/components.dart'; import 'package:flame/game.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// Adds helpers methods to Flame's [Camera] extension CameraX on Camera { diff --git a/lib/game/components/controlled_ball.dart b/lib/game/components/controlled_ball.dart index eeef58fa..4ce2f2ee 100644 --- a/lib/game/components/controlled_ball.dart +++ b/lib/game/components/controlled_ball.dart @@ -1,9 +1,9 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flutter/material.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart'; /// {@template controlled_ball} diff --git a/lib/game/components/controlled_flipper.dart b/lib/game/components/controlled_flipper.dart index f1991fe1..3c82e719 100644 --- a/lib/game/components/controlled_flipper.dart +++ b/lib/game/components/controlled_flipper.dart @@ -1,9 +1,9 @@ import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/services.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template controlled_flipper} /// A [Flipper] with a [FlipperController] attached. diff --git a/lib/game/components/controlled_plunger.dart b/lib/game/components/controlled_plunger.dart index cec71876..d6c622f7 100644 --- a/lib/game/components/controlled_plunger.dart +++ b/lib/game/components/controlled_plunger.dart @@ -1,9 +1,9 @@ import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/services.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template controlled_plunger} /// A [Plunger] with a [PlungerController] attached. diff --git a/lib/game/components/controlled_sparky_computer.dart b/lib/game/components/controlled_sparky_computer.dart index 10168e50..6a8e9e59 100644 --- a/lib/game/components/controlled_sparky_computer.dart +++ b/lib/game/components/controlled_sparky_computer.dart @@ -3,9 +3,9 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template controlled_sparky_computer} /// [SparkyComputer] with a [SparkyComputerController] attached. diff --git a/lib/game/components/flutter_forest.dart b/lib/game/components/flutter_forest.dart index 88099ee4..3c5f5a1f 100644 --- a/lib/game/components/flutter_forest.dart +++ b/lib/game/components/flutter_forest.dart @@ -1,12 +1,10 @@ // ignore_for_file: avoid_renaming_method_parameters import 'package:flame/components.dart'; -import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:flutter/material.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template flutter_forest} /// Area positioned at the top right of the [Board] where the [Ball] @@ -15,9 +13,8 @@ import 'package:pinball_components/pinball_components.dart'; /// When all [DashNestBumper]s are hit at least once, the [GameBonus.dashNest] /// is awarded, and the [BigDashNestBumper] releases a new [Ball]. /// {@endtemplate} -// TODO(alestiago): Make a [Blueprint] once [Blueprint] inherits from -// [Component]. -class FlutterForest extends Component with Controls<_FlutterForestController> { +class FlutterForest extends Component + with Controls<_FlutterForestController>, HasGameRef { /// {@macro flutter_forest} FlutterForest() { controller = _FlutterForestController(this); @@ -26,17 +23,16 @@ class FlutterForest extends Component with Controls<_FlutterForestController> { @override Future onLoad() async { await super.onLoad(); + gameRef.addContactCallback(_DashNestBumperBallContactCallback()); + final signPost = FlutterSignPost()..initialPosition = Vector2(8.35, -58.3); - final bigNest = _ControlledBigDashNestBumper( - id: 'big_nest_bumper', - )..initialPosition = Vector2(18.55, -59.35); - final smallLeftNest = _ControlledSmallDashNestBumper.a( - id: 'small_nest_bumper_a', - )..initialPosition = Vector2(8.95, -51.95); - final smallRightNest = _ControlledSmallDashNestBumper.b( - id: 'small_nest_bumper_b', - )..initialPosition = Vector2(23.3, -46.75); + final bigNest = _BigDashNestBumper() + ..initialPosition = Vector2(18.55, -59.35); + final smallLeftNest = _SmallDashNestBumper.a() + ..initialPosition = Vector2(8.95, -51.95); + final smallRightNest = _SmallDashNestBumper.b() + ..initialPosition = Vector2(23.3, -46.75); final dashAnimatronic = DashAnimatronic()..position = Vector2(20, -66); await addAll([ @@ -50,31 +46,31 @@ class FlutterForest extends Component with Controls<_FlutterForestController> { } class _FlutterForestController extends ComponentController - with BlocComponent, HasGameRef { + with HasGameRef { _FlutterForestController(FlutterForest flutterForest) : super(flutterForest); - @override - Future onLoad() async { - await super.onLoad(); - gameRef.addContactCallback(_ControlledDashNestBumperBallContactCallback()); - } + final _activatedBumpers = {}; - @override - bool listenWhen(GameState? previousState, GameState newState) { - return (previousState?.bonusHistory.length ?? 0) < - newState.bonusHistory.length && - newState.bonusHistory.last == GameBonus.dashNest; - } + void activateBumper(DashNestBumper dashNestBumper) { + if (!_activatedBumpers.add(dashNestBumper)) return; - @override - void onNewState(GameState state) { - super.onNewState(state); + dashNestBumper.activate(); - component.firstChild()?.playing = true; - _addBonusBall(); + final activatedBonus = _activatedBumpers.length == 3; + if (activatedBonus) { + _addBonusBall(); + + gameRef.read().add(const BonusActivated(GameBonus.dashNest)); + _activatedBumpers + ..forEach((bumper) => bumper.deactivate()) + ..clear(); + + component.firstChild()?.playing = true; + } } Future _addBonusBall() async { + // TODO(alestiago): Remove hardcoded duration. await Future.delayed(const Duration(milliseconds: 700)); await gameRef.add( ControlledBall.bonus(theme: gameRef.theme) @@ -83,83 +79,29 @@ class _FlutterForestController extends ComponentController } } -class _ControlledBigDashNestBumper extends BigDashNestBumper - with Controls, ScorePoints { - _ControlledBigDashNestBumper({required String id}) : super() { - controller = DashNestBumperController(this, id: id); - } - +// TODO(alestiago): Revisit ScorePoints logic once the FlameForge2D +// ContactCallback process is enhanced. +class _BigDashNestBumper extends BigDashNestBumper with ScorePoints { @override int get points => 20; } -class _ControlledSmallDashNestBumper extends SmallDashNestBumper - with Controls, ScorePoints { - _ControlledSmallDashNestBumper.a({required String id}) : super.a() { - controller = DashNestBumperController(this, id: id); - } +class _SmallDashNestBumper extends SmallDashNestBumper with ScorePoints { + _SmallDashNestBumper.a() : super.a(); - _ControlledSmallDashNestBumper.b({required String id}) : super.b() { - controller = DashNestBumperController(this, id: id); - } + _SmallDashNestBumper.b() : super.b(); @override - int get points => 10; + int get points => 20; } -/// {@template dash_nest_bumper_controller} -/// Controls a [DashNestBumper]. -/// {@endtemplate} -@visibleForTesting -class DashNestBumperController extends ComponentController - with BlocComponent, HasGameRef { - /// {@macro dash_nest_bumper_controller} - DashNestBumperController( - DashNestBumper dashNestBumper, { - required this.id, - }) : super(dashNestBumper); - - /// Unique identifier for the controlled [DashNestBumper]. - /// - /// Used to identify [DashNestBumper]s in [GameState.activatedDashNests]. - final String id; - - @override - bool listenWhen(GameState? previousState, GameState newState) { - final wasActive = previousState?.activatedDashNests.contains(id) ?? false; - final isActive = newState.activatedDashNests.contains(id); - - return wasActive != isActive; - } - +class _DashNestBumperBallContactCallback + extends ContactCallback { @override - void onNewState(GameState state) { - super.onNewState(state); - - if (state.activatedDashNests.contains(id)) { - component.activate(); - } else { - component.deactivate(); + void begin(DashNestBumper dashNestBumper, _, __) { + final parent = dashNestBumper.parent; + if (parent is FlutterForest) { + parent.controller.activateBumper(dashNestBumper); } } - - /// Registers when a [DashNestBumper] is hit by a [Ball]. - /// - /// Triggered by [_ControlledDashNestBumperBallContactCallback]. - void hit() { - gameRef.read().add(DashNestActivated(id)); - } -} - -/// Listens when a [Ball] bounces bounces against a [DashNestBumper]. -class _ControlledDashNestBumperBallContactCallback - extends ContactCallback, Ball> { - @override - void begin( - Controls controlledDashNestBumper, - Ball _, - Contact __, - ) { - controlledDashNestBumper.controller.hit(); - } } diff --git a/lib/game/components/game_flow_controller.dart b/lib/game/components/game_flow_controller.dart index 01ee0c32..957689a9 100644 --- a/lib/game/components/game_flow_controller.dart +++ b/lib/game/components/game_flow_controller.dart @@ -1,8 +1,8 @@ import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template game_flow_controller} /// A [Component] that controls the game over and game restart logic diff --git a/lib/game/components/google_word.dart b/lib/game/components/google_word.dart index 754a0fff..34609c64 100644 --- a/lib/game/components/google_word.dart +++ b/lib/game/components/google_word.dart @@ -4,9 +4,9 @@ import 'dart:async'; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template google_word} /// Loads all [GoogleLetter]s to compose a [GoogleWord]. diff --git a/lib/game/components/launcher.dart b/lib/game/components/launcher.dart index 79211d80..f3238152 100644 --- a/lib/game/components/launcher.dart +++ b/lib/game/components/launcher.dart @@ -1,6 +1,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball/game/components/components.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template launcher} /// A [Blueprint] which creates the [Plunger], [RocketSpriteComponent] and diff --git a/lib/game/components/score_effect_controller.dart b/lib/game/components/score_effect_controller.dart index f9fe9349..f4a185e1 100644 --- a/lib/game/components/score_effect_controller.dart +++ b/lib/game/components/score_effect_controller.dart @@ -2,9 +2,9 @@ import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame_bloc/flame_bloc.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template score_effect_controller} /// A [ComponentController] responsible for adding [ScoreText]s diff --git a/lib/game/components/score_points.dart b/lib/game/components/score_points.dart index ce13c718..f0d6ec3a 100644 --- a/lib/game/components/score_points.dart +++ b/lib/game/components/score_points.dart @@ -34,10 +34,7 @@ class BallScorePointsCallback extends ContactCallback { ScorePoints scorePoints, Contact __, ) { - _gameRef.read().add( - Scored(points: scorePoints.points), - ); - + _gameRef.read().add(Scored(points: scorePoints.points)); _gameRef.audio.score(); } } diff --git a/lib/game/components/sparky_fire_zone.dart b/lib/game/components/sparky_fire_zone.dart index bf8ba883..0a5abe88 100644 --- a/lib/game/components/sparky_fire_zone.dart +++ b/lib/game/components/sparky_fire_zone.dart @@ -3,9 +3,9 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flutter/material.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template sparky_fire_zone} /// Area positioned at the top left of the [Board] where the [Ball] diff --git a/lib/game/pinball_game.dart b/lib/game/pinball_game.dart index 34210329..26a844f8 100644 --- a/lib/game/pinball_game.dart +++ b/lib/game/pinball_game.dart @@ -5,11 +5,11 @@ import 'package:flame/components.dart'; import 'package:flame/input.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:pinball/flame/flame.dart'; import 'package:pinball/game/game.dart'; import 'package:pinball/gen/assets.gen.dart'; import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:pinball_theme/pinball_theme.dart' hide Assets; class PinballGame extends Forge2DGame diff --git a/packages/pinball_components/lib/src/components/backboard/backboard_game_over.dart b/packages/pinball_components/lib/src/components/backboard/backboard_game_over.dart index 05f89217..98ae6ae0 100644 --- a/packages/pinball_components/lib/src/components/backboard/backboard_game_over.dart +++ b/packages/pinball_components/lib/src/components/backboard/backboard_game_over.dart @@ -4,6 +4,7 @@ import 'dart:math'; import 'package:flame/components.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// Signature for the callback called when the used has /// submettied their initials on the [BackboardGameOver] diff --git a/packages/pinball_components/lib/src/components/backboard/backboard_letter_prompt.dart b/packages/pinball_components/lib/src/components/backboard/backboard_letter_prompt.dart index 8f404d53..61d2074d 100644 --- a/packages/pinball_components/lib/src/components/backboard/backboard_letter_prompt.dart +++ b/packages/pinball_components/lib/src/components/backboard/backboard_letter_prompt.dart @@ -5,6 +5,7 @@ import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template backboard_letter_prompt} /// A [PositionComponent] that renders a letter prompt used diff --git a/packages/pinball_components/lib/src/components/ball.dart b/packages/pinball_components/lib/src/components/ball.dart index 86ae269f..43cabd7b 100644 --- a/packages/pinball_components/lib/src/components/ball.dart +++ b/packages/pinball_components/lib/src/components/ball.dart @@ -14,13 +14,18 @@ class Ball extends BodyComponent /// {@macro ball} Ball({ required this.baseColor, - }) { + }) : super( + children: [ + _BallSpriteComponent()..tint(baseColor.withOpacity(0.5)), + ], + ) { // TODO(ruimiguel): while developing Ball can be launched by clicking mouse, // and default layer is Layer.all. But on final game Ball will be always be // be launched from Plunger and LauncherRamp will modify it to Layer.board. // We need to see what happens if Ball appears from other place like nest // bumper, it will need to explicit change layer to Layer.board then. layer = Layer.board; + renderBody = false; } /// The size of the [Ball]. @@ -32,20 +37,6 @@ class Ball extends BodyComponent double _boostTimer = 0; static const _boostDuration = 2.0; - final _BallSpriteComponent _spriteComponent = _BallSpriteComponent(); - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - - await add( - _spriteComponent..tint(baseColor.withOpacity(0.5)), - ); - - renderBody = false; - } - @override Body createBody() { final shape = CircleShape()..radius = size.x / 2; @@ -117,7 +108,10 @@ class Ball extends BodyComponent ((standardizedYPosition / boardHeight) * (1 - maxShrinkValue)); body.fixtures.first.shape.radius = (size.x / 2) * scaleFactor; - _spriteComponent.scale = Vector2.all(scaleFactor); + + // TODO(alestiago): Revisit and see if there's a better way to do this. + final spriteComponent = firstChild<_BallSpriteComponent>(); + spriteComponent?.scale = Vector2.all(scaleFactor); } void _setPositionalGravity() { diff --git a/packages/pinball_components/lib/src/components/baseboard.dart b/packages/pinball_components/lib/src/components/baseboard.dart index 03826d6c..29d7285b 100644 --- a/packages/pinball_components/lib/src/components/baseboard.dart +++ b/packages/pinball_components/lib/src/components/baseboard.dart @@ -11,7 +11,12 @@ class Baseboard extends BodyComponent with InitialPosition { /// {@macro baseboard} Baseboard({ required BoardSide side, - }) : _side = side; + }) : _side = side, + super( + children: [_BaseboardSpriteComponent(side: side)], + ) { + renderBody = false; + } /// Whether the [Baseboard] is on the left or right side of the board. final BoardSide _side; @@ -79,13 +84,6 @@ class Baseboard extends BodyComponent with InitialPosition { return fixturesDef; } - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - await add(_BaseboardSpriteComponent(side: _side)); - } - @override Body createBody() { const angle = 37.1 * (math.pi / 180); diff --git a/packages/pinball_components/lib/src/components/boundaries.dart b/packages/pinball_components/lib/src/components/boundaries.dart index b7f2595f..4025def9 100644 --- a/packages/pinball_components/lib/src/components/boundaries.dart +++ b/packages/pinball_components/lib/src/components/boundaries.dart @@ -3,6 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template boundaries} /// A [Blueprint] which creates the [_BottomBoundary] and [_OuterBoundary]. @@ -23,7 +24,13 @@ class Boundaries extends Forge2DBlueprint { /// {@endtemplate bottom_boundary} class _BottomBoundary extends BodyComponent with InitialPosition { /// {@macro bottom_boundary} - _BottomBoundary() : super(priority: RenderPriority.bottomBoundary); + _BottomBoundary() + : super( + priority: RenderPriority.bottomBoundary, + children: [_BottomBoundarySpriteComponent()], + ) { + renderBody = false; + } List _createFixtureDefs() { final fixturesDefs = []; @@ -59,13 +66,6 @@ class _BottomBoundary extends BodyComponent with InitialPosition { return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - await add(_BottomBoundarySpriteComponent()); - } } class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef { @@ -88,7 +88,13 @@ class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef { /// {@endtemplate outer_boundary} class _OuterBoundary extends BodyComponent with InitialPosition { /// {@macro outer_boundary} - _OuterBoundary() : super(priority: RenderPriority.outerBoudary); + _OuterBoundary() + : super( + priority: RenderPriority.outerBoudary, + children: [_OuterBoundarySpriteComponent()], + ) { + renderBody = false; + } List _createFixtureDefs() { final fixturesDefs = []; @@ -130,13 +136,6 @@ class _OuterBoundary extends BodyComponent with InitialPosition { return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - await add(_OuterBoundarySpriteComponent()); - } } class _OuterBoundarySpriteComponent extends SpriteComponent with HasGameRef { diff --git a/packages/pinball_components/lib/src/components/components.dart b/packages/pinball_components/lib/src/components/components.dart index 36fe6954..846482f2 100644 --- a/packages/pinball_components/lib/src/components/components.dart +++ b/packages/pinball_components/lib/src/components/components.dart @@ -19,8 +19,8 @@ export 'joint_anchor.dart'; export 'kicker.dart'; export 'launch_ramp.dart'; export 'layer.dart'; +export 'layer_sensor.dart'; export 'plunger.dart'; -export 'ramp_opening.dart'; export 'render_priority.dart'; export 'rocket.dart'; export 'score_text.dart'; diff --git a/packages/pinball_components/lib/src/components/dino_walls.dart b/packages/pinball_components/lib/src/components/dino_walls.dart index 97da2da0..033336bf 100644 --- a/packages/pinball_components/lib/src/components/dino_walls.dart +++ b/packages/pinball_components/lib/src/components/dino_walls.dart @@ -6,6 +6,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template dinowalls} /// A [Blueprint] which creates walls for the [ChromeDino]. @@ -28,7 +29,13 @@ class DinoWalls extends Forge2DBlueprint { /// {@endtemplate} class _DinoTopWall extends BodyComponent with InitialPosition { ///{@macro dino_top_wall} - _DinoTopWall() : super(priority: RenderPriority.dinoTopWall); + _DinoTopWall() + : super( + priority: RenderPriority.dinoTopWall, + children: [_DinoTopWallSpriteComponent()], + ) { + renderBody = false; + } List _createFixtureDefs() { final fixturesDef = []; @@ -97,14 +104,6 @@ class _DinoTopWall extends BodyComponent with InitialPosition { return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - - await add(_DinoTopWallSpriteComponent()); - } } class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef { @@ -125,7 +124,13 @@ class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef { /// {@endtemplate} class _DinoBottomWall extends BodyComponent with InitialPosition { ///{@macro dino_top_wall} - _DinoBottomWall() : super(priority: RenderPriority.dinoBottomWall); + _DinoBottomWall() + : super( + priority: RenderPriority.dinoBottomWall, + children: [_DinoBottomWallSpriteComponent()], + ) { + renderBody = false; + } List _createFixtureDefs() { final fixturesDef = []; @@ -205,14 +210,6 @@ class _DinoBottomWall extends BodyComponent with InitialPosition { return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - - await add(_DinoBottomWallSpriteComponent()); - } } class _DinoBottomWallSpriteComponent extends SpriteComponent with HasGameRef { diff --git a/packages/pinball_components/lib/src/components/flipper.dart b/packages/pinball_components/lib/src/components/flipper.dart index f825070a..1d0a3c5d 100644 --- a/packages/pinball_components/lib/src/components/flipper.dart +++ b/packages/pinball_components/lib/src/components/flipper.dart @@ -13,7 +13,11 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition { /// {@macro flipper} Flipper({ required this.side, - }); + }) : super( + children: [_FlipperSpriteComponent(side: side)], + ) { + renderBody = false; + } /// The size of the [Flipper]. static final size = Vector2(13.5, 4.3); @@ -112,10 +116,8 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition { @override Future onLoad() async { await super.onLoad(); - renderBody = false; await _anchorToJoint(); - await add(_FlipperSpriteComponent(side: side)); } @override diff --git a/packages/pinball_components/lib/src/components/flutter_sign_post.dart b/packages/pinball_components/lib/src/components/flutter_sign_post.dart index 210e9bdf..6e85d694 100644 --- a/packages/pinball_components/lib/src/components/flutter_sign_post.dart +++ b/packages/pinball_components/lib/src/components/flutter_sign_post.dart @@ -7,14 +7,12 @@ import 'package:pinball_components/pinball_components.dart'; /// {@endtemplate} class FlutterSignPost extends BodyComponent with InitialPosition { /// {@macro flutter_sign_post} - FlutterSignPost() : super(priority: RenderPriority.flutterSignPost); - - @override - Future onLoad() async { - await super.onLoad(); + FlutterSignPost() + : super( + priority: RenderPriority.flutterSignPost, + children: [_FlutterSignPostSpriteComponent()], + ) { renderBody = false; - - await add(_FlutterSignPostSpriteComponent()); } @override diff --git a/packages/pinball_components/lib/src/components/kicker.dart b/packages/pinball_components/lib/src/components/kicker.dart index a932b441..26e6c8f9 100644 --- a/packages/pinball_components/lib/src/components/kicker.dart +++ b/packages/pinball_components/lib/src/components/kicker.dart @@ -16,7 +16,12 @@ class Kicker extends BodyComponent with InitialPosition { /// {@macro kicker} Kicker({ required BoardSide side, - }) : _side = side; + }) : _side = side, + super( + children: [_KickerSpriteComponent(side: side)], + ) { + renderBody = false; + } /// The size of the [Kicker] body. static final Vector2 size = Vector2(4.4, 15); @@ -120,13 +125,6 @@ class Kicker extends BodyComponent with InitialPosition { return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - await add(_KickerSpriteComponent(side: _side)); - } } class _KickerSpriteComponent extends SpriteComponent with HasGameRef { diff --git a/packages/pinball_components/lib/src/components/launch_ramp.dart b/packages/pinball_components/lib/src/components/launch_ramp.dart index 4043d3c8..a9693576 100644 --- a/packages/pinball_components/lib/src/components/launch_ramp.dart +++ b/packages/pinball_components/lib/src/components/launch_ramp.dart @@ -5,6 +5,7 @@ import 'dart:math' as math; import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template launch_ramp} /// A [Blueprint] which creates the [_LaunchRampBase] and @@ -14,7 +15,7 @@ class LaunchRamp extends Forge2DBlueprint { @override void build(_) { addAllContactCallback([ - RampOpeningBallContactCallback<_LaunchRampExit>(), + LayerSensorBallContactCallback<_LaunchRampExit>(), ]); final launchRampBase = _LaunchRampBase(); @@ -236,10 +237,10 @@ class _LaunchRampCloseWall extends BodyComponent with InitialPosition, Layered { } /// {@template launch_ramp_exit} -/// [RampOpening] with [Layer.launcher] to filter [Ball]s exiting the +/// [LayerSensor] with [Layer.launcher] to filter [Ball]s exiting the /// [LaunchRamp]. /// {@endtemplate} -class _LaunchRampExit extends RampOpening { +class _LaunchRampExit extends LayerSensor { /// {@macro launch_ramp_exit} _LaunchRampExit({ required double rotation, @@ -247,7 +248,7 @@ class _LaunchRampExit extends RampOpening { super( insideLayer: Layer.launcher, outsideLayer: Layer.board, - orientation: RampOrientation.down, + orientation: LayerEntranceOrientation.down, insidePriority: RenderPriority.ballOnLaunchRamp, outsidePriority: RenderPriority.ballOnBoard, ) { diff --git a/packages/pinball_components/lib/src/components/layer_sensor.dart b/packages/pinball_components/lib/src/components/layer_sensor.dart new file mode 100644 index 00000000..85cc8506 --- /dev/null +++ b/packages/pinball_components/lib/src/components/layer_sensor.dart @@ -0,0 +1,110 @@ +// ignore_for_file: avoid_renaming_method_parameters + +import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:pinball_components/pinball_components.dart'; + +/// {@template layer_entrance_orientation} +/// Determines if a layer entrance is oriented [up] or [down] on the board. +/// {@endtemplate} +enum LayerEntranceOrientation { + /// Facing up on the Board. + up, + + /// Facing down on the Board. + down, +} + +/// {@template layer_sensor} +/// [BodyComponent] located at the entrance and exit of a [Layer]. +/// +/// [LayerSensorBallContactCallback] detects when a [Ball] passes +/// through this sensor. +/// +/// By default the base [layer] is set to [Layer.board] and the +/// [outsidePriority] is set to the lowest possible [Layer]. +/// {@endtemplate} +abstract class LayerSensor extends BodyComponent with InitialPosition, Layered { + /// {@macro layer_sensor} + LayerSensor({ + required Layer insideLayer, + Layer? outsideLayer, + required int insidePriority, + int? outsidePriority, + required this.orientation, + }) : _insideLayer = insideLayer, + _outsideLayer = outsideLayer ?? Layer.board, + _insidePriority = insidePriority, + _outsidePriority = outsidePriority ?? RenderPriority.ballOnBoard { + layer = Layer.opening; + } + final Layer _insideLayer; + final Layer _outsideLayer; + final int _insidePriority; + final int _outsidePriority; + + /// Mask bits value for collisions on [Layer]. + Layer get insideLayer => _insideLayer; + + /// Mask bits value for collisions outside of [Layer]. + Layer get outsideLayer => _outsideLayer; + + /// Render priority for the [Ball] on [Layer]. + int get insidePriority => _insidePriority; + + /// Render priority for the [Ball] outside of [Layer]. + int get outsidePriority => _outsidePriority; + + /// The [Shape] of the [LayerSensor]. + Shape get shape; + + /// {@macro layer_entrance_orientation} + // TODO(ruimiguel): Try to remove the need of [LayerEntranceOrientation] for + // collision calculations. + final LayerEntranceOrientation orientation; + + @override + Body createBody() { + final fixtureDef = FixtureDef( + shape, + isSensor: true, + ); + final bodyDef = BodyDef( + position: initialPosition, + userData: this, + ); + + return world.createBody(bodyDef)..createFixture(fixtureDef); + } +} + +/// {@template layer_sensor_ball_contact_callback} +/// Detects when a [Ball] enters or exits a [Layer] through a [LayerSensor]. +/// +/// Modifies [Ball]'s [Layer] and render priority depending on whether the +/// [Ball] is on or outside of a [Layer]. +/// {@endtemplate} +class LayerSensorBallContactCallback + extends ContactCallback { + @override + void begin(Ball ball, LayerEntrance layerEntrance, Contact _) { + if (ball.layer != layerEntrance.insideLayer) { + final isBallEnteringOpening = + (layerEntrance.orientation == LayerEntranceOrientation.down && + ball.body.linearVelocity.y < 0) || + (layerEntrance.orientation == LayerEntranceOrientation.up && + ball.body.linearVelocity.y > 0); + + if (isBallEnteringOpening) { + ball + ..layer = layerEntrance.insideLayer + ..priority = layerEntrance.insidePriority + ..reorderChildren(); + } + } else { + ball + ..layer = layerEntrance.outsideLayer + ..priority = layerEntrance.outsidePriority + ..reorderChildren(); + } + } +} diff --git a/packages/pinball_components/lib/src/components/ramp_opening.dart b/packages/pinball_components/lib/src/components/ramp_opening.dart deleted file mode 100644 index 2434b31a..00000000 --- a/packages/pinball_components/lib/src/components/ramp_opening.dart +++ /dev/null @@ -1,129 +0,0 @@ -// ignore_for_file: avoid_renaming_method_parameters - -import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:pinball_components/pinball_components.dart'; - -/// {@template ramp_orientation} -/// Determines if a ramp is facing [up] or [down] on the Board. -/// {@endtemplate} -enum RampOrientation { - /// Facing up on the Board. - up, - - /// Facing down on the Board. - down, -} - -/// {@template ramp_opening} -/// [BodyComponent] located at the entrance and exit of a ramp. -/// -/// [RampOpeningBallContactCallback] detects when a [Ball] passes -/// through this opening. -/// -/// By default the base [layer] is set to [Layer.board] and the -/// [outsidePriority] is set to the lowest possible [Layer]. -/// {@endtemplate} -// TODO(ruialonso): Consider renaming the class. -abstract class RampOpening extends BodyComponent with InitialPosition, Layered { - /// {@macro ramp_opening} - RampOpening({ - required Layer insideLayer, - Layer? outsideLayer, - required int insidePriority, - int? outsidePriority, - required this.orientation, - }) : _insideLayer = insideLayer, - _outsideLayer = outsideLayer ?? Layer.board, - _insidePriority = insidePriority, - _outsidePriority = outsidePriority ?? RenderPriority.ballOnBoard { - layer = Layer.opening; - } - final Layer _insideLayer; - final Layer _outsideLayer; - final int _insidePriority; - final int _outsidePriority; - - /// Mask of category bits for collision inside ramp. - Layer get insideLayer => _insideLayer; - - /// Mask of category bits for collision outside ramp. - Layer get outsideLayer => _outsideLayer; - - /// Priority for the [Ball] inside ramp. - int get insidePriority => _insidePriority; - - /// Priority for the [Ball] outside ramp. - int get outsidePriority => _outsidePriority; - - /// The [Shape] of the [RampOpening]. - Shape get shape; - - /// {@macro ramp_orientation} - // TODO(ruimiguel): Try to remove the need of [RampOrientation] for collision - // calculations. - final RampOrientation orientation; - - @override - Body createBody() { - final fixtureDef = FixtureDef( - shape, - isSensor: true, - ); - final bodyDef = BodyDef( - position: initialPosition, - userData: this, - ); - - return world.createBody(bodyDef)..createFixture(fixtureDef); - } -} - -/// {@template ramp_opening_ball_contact_callback} -/// Detects when a [Ball] enters or exits a ramp through a [RampOpening]. -/// -/// Modifies [Ball]'s [Layer] accordingly depending on whether the [Ball] is -/// outside or inside a ramp. -/// {@endtemplate} -class RampOpeningBallContactCallback - extends ContactCallback { - /// [Ball]s currently inside the ramp. - final _ballsInside = {}; - - @override - void begin(Ball ball, Opening opening, Contact _) { - Layer layer; - - if (!_ballsInside.contains(ball)) { - layer = opening.insideLayer; - _ballsInside.add(ball); - ball - ..sendTo(opening.insidePriority) - ..layer = layer; - } else { - _ballsInside.remove(ball); - } - } - - @override - void end(Ball ball, Opening opening, Contact _) { - if (!_ballsInside.contains(ball)) { - ball.layer = opening.outsideLayer; - } else { - // TODO(ruimiguel): change this code. Check what happens with ball that - // slightly touch Opening and goes out again. With InitialPosition change - // now doesn't work position.y comparison - final isBallOutsideOpening = - (opening.orientation == RampOrientation.down && - ball.body.linearVelocity.y > 0) || - (opening.orientation == RampOrientation.up && - ball.body.linearVelocity.y < 0); - - if (isBallOutsideOpening) { - ball - ..sendTo(opening.outsidePriority) - ..layer = opening.outsideLayer; - _ballsInside.remove(ball); - } - } - } -} diff --git a/packages/pinball_components/lib/src/components/render_priority.dart b/packages/pinball_components/lib/src/components/render_priority.dart index 01fa2e72..25f51a04 100644 --- a/packages/pinball_components/lib/src/components/render_priority.dart +++ b/packages/pinball_components/lib/src/components/render_priority.dart @@ -23,7 +23,7 @@ abstract class RenderPriority { static const int ballOnSpaceship = _above + spaceshipSaucer; /// Render priority for the [Ball] while it's on the [SpaceshipRail]. - static const int ballOnSpaceshipRail = _above + spaceshipRail; + static const int ballOnSpaceshipRail = _below + spaceshipSaucer; /// Render priority for the [Ball] while it's on the [LaunchRamp]. static const int ballOnLaunchRamp = _above + launchRamp; diff --git a/packages/pinball_components/lib/src/components/slingshot.dart b/packages/pinball_components/lib/src/components/slingshot.dart index 99333136..52cdb698 100644 --- a/packages/pinball_components/lib/src/components/slingshot.dart +++ b/packages/pinball_components/lib/src/components/slingshot.dart @@ -3,6 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template slingshots} /// A [Blueprint] which creates the pair of [Slingshot]s on the right side of @@ -41,15 +42,17 @@ class Slingshot extends BodyComponent with InitialPosition { required String spritePath, }) : _length = length, _angle = angle, - _spritePath = spritePath, - super(priority: RenderPriority.slingshot); + super( + priority: RenderPriority.slingshot, + children: [_SlinghsotSpriteComponent(spritePath, angle: angle)], + ) { + renderBody = false; + } final double _length; final double _angle; - final String _spritePath; - List _createFixtureDefs() { final fixturesDef = []; const circleRadius = 1.55; @@ -103,24 +106,25 @@ class Slingshot extends BodyComponent with InitialPosition { return body; } +} + +class _SlinghsotSpriteComponent extends SpriteComponent with HasGameRef { + _SlinghsotSpriteComponent( + String path, { + required double angle, + }) : _path = path, + super( + angle: -angle, + anchor: Anchor.center, + ); + + final String _path; @override Future onLoad() async { await super.onLoad(); - await _loadSprite(); - renderBody = false; - } - - Future _loadSprite() async { - final sprite = await gameRef.loadSprite(_spritePath); - - await add( - SpriteComponent( - sprite: sprite, - size: sprite.originalSize / 10, - anchor: Anchor.center, - angle: -_angle, - ), - ); + final sprite = await gameRef.loadSprite(_path); + this.sprite = sprite; + size = sprite.originalSize / 10; } } diff --git a/packages/pinball_components/lib/src/components/spaceship.dart b/packages/pinball_components/lib/src/components/spaceship.dart index 28e29ae3..b3d674dc 100644 --- a/packages/pinball_components/lib/src/components/spaceship.dart +++ b/packages/pinball_components/lib/src/components/spaceship.dart @@ -7,6 +7,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template spaceship} /// A [Blueprint] which creates the spaceship feature. @@ -24,19 +25,22 @@ class Spaceship extends Forge2DBlueprint { @override void build(_) { addAllContactCallback([ - SpaceshipHoleBallContactCallback(), - SpaceshipEntranceBallContactCallback(), + LayerSensorBallContactCallback<_SpaceshipEntrance>(), + LayerSensorBallContactCallback<_SpaceshipHole>(), ]); addAll([ SpaceshipSaucer()..initialPosition = position, - SpaceshipEntrance()..initialPosition = position, + _SpaceshipEntrance()..initialPosition = position, AndroidHead()..initialPosition = position, - SpaceshipHole( + _SpaceshipHole( outsideLayer: Layer.spaceshipExitRail, outsidePriority: RenderPriority.ballOnSpaceshipRail, )..initialPosition = position - Vector2(5.2, -4.8), - SpaceshipHole()..initialPosition = position - Vector2(-7.2, -0.8), + _SpaceshipHole( + outsideLayer: Layer.board, + outsidePriority: RenderPriority.ballOnBoard, + )..initialPosition = position - Vector2(-7.2, -0.8), SpaceshipWall()..initialPosition = position, ]); } @@ -91,16 +95,13 @@ class SpaceshipSaucer extends BodyComponent with InitialPosition, Layered { /// {@endtemplate} class AndroidHead extends BodyComponent with InitialPosition, Layered { /// {@macro spaceship_bridge} - AndroidHead() : super(priority: RenderPriority.androidHead) { - layer = Layer.spaceship; - } - - @override - Future onLoad() async { - await super.onLoad(); + AndroidHead() + : super( + priority: RenderPriority.androidHead, + children: [_AndroidHeadSpriteAnimation()], + ) { renderBody = false; - - await add(_AndroidHeadSpriteAnimation()); + layer = Layer.spaceship; } @override @@ -142,17 +143,11 @@ class _AndroidHeadSpriteAnimation extends SpriteAnimationComponent } } -/// {@template spaceship_entrance} -/// A sensor [BodyComponent] used to detect when the ball enters the -/// the spaceship area in order to modify its filter data so the ball -/// can correctly collide only with the Spaceship -/// {@endtemplate} -class SpaceshipEntrance extends RampOpening { - /// {@macro spaceship_entrance} - SpaceshipEntrance() +class _SpaceshipEntrance extends LayerSensor { + _SpaceshipEntrance() : super( insideLayer: Layer.spaceship, - orientation: RampOrientation.up, + orientation: LayerEntranceOrientation.up, insidePriority: RenderPriority.ballOnSpaceship, ) { layer = Layer.spaceship; @@ -176,17 +171,12 @@ class SpaceshipEntrance extends RampOpening { } } -/// {@template spaceship_hole} -/// A sensor [BodyComponent] responsible for sending the [Ball] -/// out from the [Spaceship]. -/// {@endtemplate} -class SpaceshipHole extends RampOpening { - /// {@macro spaceship_hole} - SpaceshipHole({Layer? outsideLayer, int? outsidePriority = 1}) +class _SpaceshipHole extends LayerSensor { + _SpaceshipHole({required Layer outsideLayer, required int outsidePriority}) : super( insideLayer: Layer.spaceship, outsideLayer: outsideLayer, - orientation: RampOrientation.up, + orientation: LayerEntranceOrientation.down, insidePriority: RenderPriority.ballOnSpaceship, outsidePriority: outsidePriority, ) { @@ -258,33 +248,3 @@ class SpaceshipWall extends BodyComponent with InitialPosition, Layered { return world.createBody(bodyDef)..createFixture(fixtureDef); } } - -/// [ContactCallback] that handles the contact between the [Ball] -/// and the [SpaceshipEntrance]. -/// -/// It modifies the [Ball] priority and filter data so it can appear on top of -/// the spaceship and also only collide with the spaceship. -class SpaceshipEntranceBallContactCallback - extends ContactCallback { - @override - void begin(SpaceshipEntrance entrance, Ball ball, _) { - ball - ..sendTo(entrance.insidePriority) - ..layer = Layer.spaceship; - } -} - -/// [ContactCallback] that handles the contact between the [Ball] -/// and a [SpaceshipHole]. -/// -/// It sets the [Ball] priority and filter data so it will outside of the -/// [Spaceship]. -class SpaceshipHoleBallContactCallback - extends ContactCallback { - @override - void begin(SpaceshipHole hole, Ball ball, _) { - ball - ..sendTo(hole.outsidePriority) - ..layer = hole.outsideLayer; - } -} diff --git a/packages/pinball_components/lib/src/components/spaceship_rail.dart b/packages/pinball_components/lib/src/components/spaceship_rail.dart index c88fe738..49fdd475 100644 --- a/packages/pinball_components/lib/src/components/spaceship_rail.dart +++ b/packages/pinball_components/lib/src/components/spaceship_rail.dart @@ -6,6 +6,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template spaceship_rail} /// A [Blueprint] for the spaceship drop tube. @@ -17,11 +18,11 @@ class SpaceshipRail extends Forge2DBlueprint { @override void build(_) { addAllContactCallback([ - SpaceshipRailExitBallContactCallback(), + LayerSensorBallContactCallback<_SpaceshipRailExit>(), ]); final railRamp = _SpaceshipRailRamp(); - final railEnd = SpaceshipRailExit(); + final railEnd = _SpaceshipRailExit(); final topBase = _SpaceshipRailBase(radius: 0.55) ..initialPosition = Vector2(-26.15, -18.65); final bottomBase = _SpaceshipRailBase(radius: 0.8) @@ -194,15 +195,10 @@ class _SpaceshipRailBase extends BodyComponent with InitialPosition { } } -/// {@template spaceship_rail_exit} -/// A sensor [BodyComponent] responsible for sending the [Ball] -/// back to the board. -/// {@endtemplate} -class SpaceshipRailExit extends RampOpening { - /// {@macro spaceship_rail_exit} - SpaceshipRailExit() +class _SpaceshipRailExit extends LayerSensor { + _SpaceshipRailExit() : super( - orientation: RampOrientation.down, + orientation: LayerEntranceOrientation.down, insideLayer: Layer.spaceshipExitRail, insidePriority: RenderPriority.ballOnSpaceshipRail, ) { @@ -220,18 +216,3 @@ class SpaceshipRailExit extends RampOpening { ); } } - -/// [ContactCallback] that handles the contact between the [Ball] -/// and a [SpaceshipRailExit]. -/// -/// It resets the [Ball] priority and filter data so it will "be back" on the -/// board. -class SpaceshipRailExitBallContactCallback - extends ContactCallback { - @override - void begin(SpaceshipRailExit exitRail, Ball ball, _) { - ball - ..sendTo(exitRail.outsidePriority) - ..layer = exitRail.outsideLayer; - } -} diff --git a/packages/pinball_components/lib/src/components/spaceship_ramp.dart b/packages/pinball_components/lib/src/components/spaceship_ramp.dart index 480c2549..f2d8801c 100644 --- a/packages/pinball_components/lib/src/components/spaceship_ramp.dart +++ b/packages/pinball_components/lib/src/components/spaceship_ramp.dart @@ -6,6 +6,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/pinball_components.dart' hide Assets; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template spaceship_ramp} /// A [Blueprint] which creates the ramp leading into the [Spaceship]. @@ -17,7 +18,7 @@ class SpaceshipRamp extends Forge2DBlueprint { @override void build(_) { addAllContactCallback([ - RampOpeningBallContactCallback<_SpaceshipRampOpening>(), + LayerSensorBallContactCallback<_SpaceshipRampOpening>(), ]); final rightOpening = _SpaceshipRampOpening( @@ -170,8 +171,12 @@ class _SpaceshipRampBoardOpeningSpriteComponent extends SpriteComponent class _SpaceshipRampForegroundRailing extends BodyComponent with InitialPosition, Layered { _SpaceshipRampForegroundRailing() - : super(priority: RenderPriority.spaceshipRampForegroundRailing) { + : super( + priority: RenderPriority.spaceshipRampForegroundRailing, + children: [_SpaceshipRampForegroundRailingSpriteComponent()], + ) { layer = Layer.spaceshipEntranceRamp; + renderBody = false; } List _createFixtureDefs() { @@ -222,14 +227,6 @@ class _SpaceshipRampForegroundRailing extends BodyComponent return body; } - - @override - Future onLoad() async { - await super.onLoad(); - renderBody = false; - - await add(_SpaceshipRampForegroundRailingSpriteComponent()); - } } class _SpaceshipRampForegroundRailingSpriteComponent extends SpriteComponent @@ -277,10 +274,10 @@ class _SpaceshipRampBase extends BodyComponent with InitialPosition, Layered { } /// {@template spaceship_ramp_opening} -/// [RampOpening] with [Layer.spaceshipEntranceRamp] to filter [Ball] collisions +/// [LayerSensor] with [Layer.spaceshipEntranceRamp] to filter [Ball] collisions /// inside [_SpaceshipRampBackground]. /// {@endtemplate} -class _SpaceshipRampOpening extends RampOpening { +class _SpaceshipRampOpening extends LayerSensor { /// {@macro spaceship_ramp_opening} _SpaceshipRampOpening({ Layer? outsideLayer, @@ -290,7 +287,7 @@ class _SpaceshipRampOpening extends RampOpening { super( insideLayer: Layer.spaceshipEntranceRamp, outsideLayer: outsideLayer, - orientation: RampOrientation.down, + orientation: LayerEntranceOrientation.down, insidePriority: RenderPriority.ballOnSpaceshipRamp, outsidePriority: outsidePriority, ) { diff --git a/packages/pinball_components/lib/src/components/sparky_computer.dart b/packages/pinball_components/lib/src/components/sparky_computer.dart index 1cf4ee83..427847ae 100644 --- a/packages/pinball_components/lib/src/components/sparky_computer.dart +++ b/packages/pinball_components/lib/src/components/sparky_computer.dart @@ -3,6 +3,7 @@ import 'package:flame/components.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; /// {@template sparky_computer} /// A [Blueprint] which creates the [_ComputerBase] and diff --git a/packages/pinball_components/lib/src/flame/flame.dart b/packages/pinball_components/lib/src/flame/flame.dart deleted file mode 100644 index 9b766995..00000000 --- a/packages/pinball_components/lib/src/flame/flame.dart +++ /dev/null @@ -1,3 +0,0 @@ -export 'blueprint.dart'; -export 'keyboard_input_controller.dart'; -export 'priority.dart'; diff --git a/packages/pinball_components/lib/src/flame/priority.dart b/packages/pinball_components/lib/src/flame/priority.dart deleted file mode 100644 index f4dccabf..00000000 --- a/packages/pinball_components/lib/src/flame/priority.dart +++ /dev/null @@ -1,39 +0,0 @@ -import 'dart:math' as math; -import 'package:flame/components.dart'; - -/// Helper methods to change the [priority] of a [Component]. -extension ComponentPriorityX on Component { - static const _lowestPriority = 0; - - /// Changes the priority to a specific one. - void sendTo(int destinationPriority) { - if (priority != destinationPriority) { - priority = math.max(destinationPriority, _lowestPriority); - reorderChildren(); - } - } - - /// Changes the priority to the lowest possible. - void sendToBack() { - if (priority != _lowestPriority) { - priority = _lowestPriority; - reorderChildren(); - } - } - - /// Decreases the priority to be lower than another [Component]. - void showBehindOf(Component other) { - if (priority >= other.priority) { - priority = math.max(other.priority - 1, _lowestPriority); - reorderChildren(); - } - } - - /// Increases the priority to be higher than another [Component]. - void showInFrontOf(Component other) { - if (priority <= other.priority) { - priority = other.priority + 1; - reorderChildren(); - } - } -} diff --git a/packages/pinball_components/lib/src/pinball_components.dart b/packages/pinball_components/lib/src/pinball_components.dart index 50dee227..e50f9875 100644 --- a/packages/pinball_components/lib/src/pinball_components.dart +++ b/packages/pinball_components/lib/src/pinball_components.dart @@ -1,3 +1,2 @@ export 'components/components.dart'; export 'extensions/extensions.dart'; -export 'flame/flame.dart'; diff --git a/packages/pinball_components/pubspec.yaml b/packages/pinball_components/pubspec.yaml index d27084f1..be06949c 100644 --- a/packages/pinball_components/pubspec.yaml +++ b/packages/pinball_components/pubspec.yaml @@ -14,6 +14,8 @@ dependencies: geometry: path: ../geometry intl: ^0.17.0 + pinball_flame: + path: ../pinball_flame dev_dependencies: diff --git a/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart b/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart index 0bc2755d..ab984045 100644 --- a/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/boundaries/boundaries_game.dart @@ -1,5 +1,6 @@ import 'package:flame/extensions.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; diff --git a/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart b/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart index 9c14e77a..2d636e30 100644 --- a/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/launch_ramp/launch_ramp_game.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class LaunchRampGame extends BasicBallGame { diff --git a/packages/pinball_components/sandbox/lib/stories/slingshot/slingshot_game.dart b/packages/pinball_components/sandbox/lib/stories/slingshot/slingshot_game.dart index dd1df4de..7d941099 100644 --- a/packages/pinball_components/sandbox/lib/stories/slingshot/slingshot_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/slingshot/slingshot_game.dart @@ -1,5 +1,6 @@ import 'package:flame/extensions.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/common/common.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; diff --git a/packages/pinball_components/sandbox/lib/stories/spaceship/basic_spaceship_game.dart b/packages/pinball_components/sandbox/lib/stories/spaceship/basic_spaceship_game.dart index 95afcd7f..6c00f476 100644 --- a/packages/pinball_components/sandbox/lib/stories/spaceship/basic_spaceship_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/spaceship/basic_spaceship_game.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/common/common.dart'; class BasicSpaceshipGame extends BasicGame with TapDetector { diff --git a/packages/pinball_components/sandbox/lib/stories/spaceship_rail/spaceship_rail_game.dart b/packages/pinball_components/sandbox/lib/stories/spaceship_rail/spaceship_rail_game.dart index 38458649..471333c3 100644 --- a/packages/pinball_components/sandbox/lib/stories/spaceship_rail/spaceship_rail_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/spaceship_rail/spaceship_rail_game.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class SpaceshipRailGame extends BasicBallGame { diff --git a/packages/pinball_components/sandbox/lib/stories/spaceship_ramp/spaceship_ramp_game.dart b/packages/pinball_components/sandbox/lib/stories/spaceship_ramp/spaceship_ramp_game.dart index c71d18c2..a11f6d7d 100644 --- a/packages/pinball_components/sandbox/lib/stories/spaceship_ramp/spaceship_ramp_game.dart +++ b/packages/pinball_components/sandbox/lib/stories/spaceship_ramp/spaceship_ramp_game.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flame/input.dart'; import 'package:flutter/material.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart'; class SpaceshipRampGame extends BasicBallGame { diff --git a/packages/pinball_components/sandbox/pubspec.lock b/packages/pinball_components/sandbox/pubspec.lock index 61af3a8a..7f78e365 100644 --- a/packages/pinball_components/sandbox/pubspec.lock +++ b/packages/pinball_components/sandbox/pubspec.lock @@ -240,6 +240,13 @@ packages: relative: true source: path version: "1.0.0+1" + pinball_flame: + dependency: "direct main" + description: + path: "../../pinball_flame" + relative: true + source: path + version: "1.0.0+1" platform: dependency: transitive description: diff --git a/packages/pinball_components/sandbox/pubspec.yaml b/packages/pinball_components/sandbox/pubspec.yaml index 6687e358..03a46ee0 100644 --- a/packages/pinball_components/sandbox/pubspec.yaml +++ b/packages/pinball_components/sandbox/pubspec.yaml @@ -14,6 +14,8 @@ dependencies: sdk: flutter pinball_components: path: ../ + pinball_flame: + path: ../../pinball_flame dev_dependencies: flutter_test: diff --git a/packages/pinball_components/test/helpers/mocks.dart b/packages/pinball_components/test/helpers/mocks.dart index 21d5d01a..520555df 100644 --- a/packages/pinball_components/test/helpers/mocks.dart +++ b/packages/pinball_components/test/helpers/mocks.dart @@ -13,12 +13,6 @@ class MockBall extends Mock implements Ball {} class MockGame extends Mock implements Forge2DGame {} -class MockSpaceshipEntrance extends Mock implements SpaceshipEntrance {} - -class MockSpaceshipHole extends Mock implements SpaceshipHole {} - -class MockSpaceshipRailExit extends Mock implements SpaceshipRailExit {} - class MockContact extends Mock implements Contact {} class MockContactCallback extends Mock diff --git a/packages/pinball_components/test/src/components/boundaries_test.dart b/packages/pinball_components/test/src/components/boundaries_test.dart index 9fad34be..e62d63e3 100644 --- a/packages/pinball_components/test/src/components/boundaries_test.dart +++ b/packages/pinball_components/test/src/components/boundaries_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -17,6 +18,7 @@ void main() { await game.addFromBlueprint(Boundaries()); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 3.9; + await game.ready(); }, verify: (game, tester) async { await expectLater( diff --git a/packages/pinball_components/test/src/components/dino_walls_test.dart b/packages/pinball_components/test/src/components/dino_walls_test.dart index de3fa2b9..b3a58264 100644 --- a/packages/pinball_components/test/src/components/dino_walls_test.dart +++ b/packages/pinball_components/test/src/components/dino_walls_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -18,6 +19,7 @@ void main() { await game.addFromBlueprint(DinoWalls()); game.camera.followVector2(Vector2.zero()); game.camera.zoom = 6.5; + await game.ready(); }, verify: (game, tester) async { await expectLater( diff --git a/packages/pinball_components/test/src/components/launch_ramp_test.dart b/packages/pinball_components/test/src/components/launch_ramp_test.dart index e56bfae9..1f5d6f26 100644 --- a/packages/pinball_components/test/src/components/launch_ramp_test.dart +++ b/packages/pinball_components/test/src/components/launch_ramp_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; diff --git a/packages/pinball_components/test/src/components/layer_sensor_test.dart b/packages/pinball_components/test/src/components/layer_sensor_test.dart new file mode 100644 index 00000000..c87f02b3 --- /dev/null +++ b/packages/pinball_components/test/src/components/layer_sensor_test.dart @@ -0,0 +1,181 @@ +// ignore_for_file: cascade_invocations +import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:flame_test/flame_test.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:pinball_components/pinball_components.dart'; + +import '../../helpers/helpers.dart'; + +class TestLayerSensor extends LayerSensor { + TestLayerSensor({ + required LayerEntranceOrientation orientation, + required int insidePriority, + required Layer insideLayer, + }) : super( + insideLayer: insideLayer, + insidePriority: insidePriority, + orientation: orientation, + ); + + @override + Shape get shape => PolygonShape()..setAsBoxXY(1, 1); +} + +class TestLayerSensorBallContactCallback + extends LayerSensorBallContactCallback { + TestLayerSensorBallContactCallback() : super(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final flameTester = FlameTester(TestGame.new); + const insidePriority = 1; + + group('LayerSensor', () { + flameTester.test( + 'loads correctly', + (game) async { + final layerSensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: Layer.spaceshipEntranceRamp, + ); + await game.ensureAdd(layerSensor); + + expect(game.contains(layerSensor), isTrue); + }, + ); + + group('body', () { + flameTester.test( + 'is static', + (game) async { + final layerSensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: Layer.spaceshipEntranceRamp, + ); + await game.ensureAdd(layerSensor); + + expect(layerSensor.body.bodyType, equals(BodyType.static)); + }, + ); + + group('first fixture', () { + const pathwayLayer = Layer.spaceshipEntranceRamp; + const openingLayer = Layer.opening; + + flameTester.test( + 'exists', + (game) async { + final layerSensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: pathwayLayer, + )..layer = openingLayer; + await game.ensureAdd(layerSensor); + + expect(layerSensor.body.fixtures[0], isA()); + }, + ); + + flameTester.test( + 'shape is a polygon', + (game) async { + final layerSensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: pathwayLayer, + )..layer = openingLayer; + await game.ensureAdd(layerSensor); + + final fixture = layerSensor.body.fixtures[0]; + expect(fixture.shape.shapeType, equals(ShapeType.polygon)); + }, + ); + + flameTester.test( + 'is sensor', + (game) async { + final layerSensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: pathwayLayer, + )..layer = openingLayer; + await game.ensureAdd(layerSensor); + + final fixture = layerSensor.body.fixtures[0]; + expect(fixture.isSensor, isTrue); + }, + ); + }); + }); + }); + + group('LayerSensorBallContactCallback', () { + late Ball ball; + late Body body; + + setUp(() { + ball = MockBall(); + body = MockBody(); + + when(() => ball.body).thenReturn(body); + when(() => ball.priority).thenReturn(1); + when(() => ball.layer).thenReturn(Layer.board); + }); + + flameTester.test( + 'changes ball layer and priority ' + 'when a ball enters and exits a downward oriented LayerSensor', + (game) async { + final sensor = TestLayerSensor( + orientation: LayerEntranceOrientation.down, + insidePriority: insidePriority, + insideLayer: Layer.spaceshipEntranceRamp, + )..initialPosition = Vector2(0, 10); + final callback = TestLayerSensorBallContactCallback(); + + when(() => body.linearVelocity).thenReturn(Vector2(0, -1)); + + callback.begin(ball, sensor, MockContact()); + verify(() => ball.layer = sensor.insideLayer).called(1); + verify(() => ball.priority = sensor.insidePriority).called(1); + verify(ball.reorderChildren).called(1); + + when(() => ball.layer).thenReturn(sensor.insideLayer); + + callback.begin(ball, sensor, MockContact()); + verify(() => ball.layer = Layer.board); + verify(() => ball.priority = Ball.boardPriority).called(1); + verify(ball.reorderChildren).called(1); + }); + + flameTester.test( + 'changes ball layer and priority ' + 'when a ball enters and exits an upward oriented LayerSensor', + (game) async { + final sensor = TestLayerSensor( + orientation: LayerEntranceOrientation.up, + insidePriority: insidePriority, + insideLayer: Layer.spaceshipEntranceRamp, + )..initialPosition = Vector2(0, 10); + final callback = TestLayerSensorBallContactCallback(); + + when(() => body.linearVelocity).thenReturn(Vector2(0, 1)); + + callback.begin(ball, sensor, MockContact()); + verify(() => ball.layer = sensor.insideLayer).called(1); + verify(() => ball.priority = sensor.insidePriority).called(1); + verify(ball.reorderChildren).called(1); + + when(() => ball.layer).thenReturn(sensor.insideLayer); + + callback.begin(ball, sensor, MockContact()); + verify(() => ball.layer = Layer.board); + verify(() => ball.priority = Ball.boardPriority).called(1); + verify(ball.reorderChildren).called(1); + }); + }); +} diff --git a/packages/pinball_components/test/src/components/ramp_opening_test.dart b/packages/pinball_components/test/src/components/ramp_opening_test.dart deleted file mode 100644 index 37b8edb0..00000000 --- a/packages/pinball_components/test/src/components/ramp_opening_test.dart +++ /dev/null @@ -1,249 +0,0 @@ -// ignore_for_file: cascade_invocations -import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mocktail/mocktail.dart'; -import 'package:pinball_components/pinball_components.dart'; - -import '../../helpers/helpers.dart'; - -class TestRampOpening extends RampOpening { - TestRampOpening({ - required RampOrientation orientation, - required int insidePriority, - required Layer pathwayLayer, - }) : super( - insideLayer: pathwayLayer, - insidePriority: insidePriority, - orientation: orientation, - ); - - @override - Shape get shape => PolygonShape() - ..set([ - Vector2(0, 0), - Vector2(0, 1), - Vector2(1, 1), - Vector2(1, 0), - ]); -} - -class TestRampOpeningBallContactCallback - extends RampOpeningBallContactCallback { - TestRampOpeningBallContactCallback() : super(); -} - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - final flameTester = FlameTester(TestGame.new); - const insidePriority = 1; - - group('RampOpening', () { - flameTester.test( - 'loads correctly', - (game) async { - final ramp = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - ); - await game.ready(); - await game.ensureAdd(ramp); - - expect(game.contains(ramp), isTrue); - }, - ); - - group('body', () { - flameTester.test( - 'is static', - (game) async { - final ramp = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - ); - await game.ensureAdd(ramp); - - expect(ramp.body.bodyType, equals(BodyType.static)); - }, - ); - - group('first fixture', () { - const pathwayLayer = Layer.spaceshipEntranceRamp; - const openingLayer = Layer.opening; - - flameTester.test( - 'exists', - (game) async { - final ramp = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: pathwayLayer, - )..layer = openingLayer; - await game.ensureAdd(ramp); - - expect(ramp.body.fixtures[0], isA()); - }, - ); - - flameTester.test( - 'shape is a polygon', - (game) async { - final ramp = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: pathwayLayer, - )..layer = openingLayer; - await game.ensureAdd(ramp); - - final fixture = ramp.body.fixtures[0]; - expect(fixture.shape.shapeType, equals(ShapeType.polygon)); - }, - ); - - flameTester.test( - 'is sensor', - (game) async { - final ramp = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: pathwayLayer, - )..layer = openingLayer; - await game.ensureAdd(ramp); - - final fixture = ramp.body.fixtures[0]; - expect(fixture.isSensor, isTrue); - }, - ); - }); - }); - }); - - group('RampOpeningBallContactCallback', () { - flameTester.test( - 'changes ball layer ' - 'when a ball enters upwards into a downward ramp opening', - (game) async { - final ball = MockBall(); - final body = MockBody(); - final area = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - ); - final callback = TestRampOpeningBallContactCallback(); - - when(() => ball.body).thenReturn(body); - when(() => ball.priority).thenReturn(1); - when(() => body.position).thenReturn(Vector2.zero()); - when(() => ball.layer).thenReturn(Layer.board); - - callback.begin(ball, area, MockContact()); - verify(() => ball.layer = area.insideLayer).called(1); - }); - - flameTester.test( - 'changes ball layer ' - 'when a ball enters downwards into a upward ramp opening', - (game) async { - final ball = MockBall(); - final body = MockBody(); - final area = TestRampOpening( - orientation: RampOrientation.up, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - ); - final callback = TestRampOpeningBallContactCallback(); - - when(() => ball.body).thenReturn(body); - when(() => ball.priority).thenReturn(1); - when(() => body.position).thenReturn(Vector2.zero()); - when(() => ball.layer).thenReturn(Layer.board); - - callback.begin(ball, area, MockContact()); - verify(() => ball.layer = area.insideLayer).called(1); - }); - - flameTester.test( - 'changes ball layer ' - 'when a ball exits from a downward oriented ramp', (game) async { - final ball = MockBall(); - final body = MockBody(); - final area = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - )..initialPosition = Vector2(0, 10); - final callback = TestRampOpeningBallContactCallback(); - - when(() => ball.body).thenReturn(body); - when(() => ball.priority).thenReturn(1); - when(() => body.position).thenReturn(Vector2.zero()); - when(() => body.linearVelocity).thenReturn(Vector2(0, 1)); - when(() => ball.layer).thenReturn(Layer.board); - - callback.begin(ball, area, MockContact()); - verify(() => ball.layer = area.insideLayer).called(1); - - callback.end(ball, area, MockContact()); - verify(() => ball.layer = Layer.board); - }); - - flameTester.test( - 'changes ball layer ' - 'when a ball exits from a upward oriented ramp', (game) async { - final ball = MockBall(); - final body = MockBody(); - final area = TestRampOpening( - orientation: RampOrientation.up, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - )..initialPosition = Vector2(0, 10); - final callback = TestRampOpeningBallContactCallback(); - - when(() => ball.body).thenReturn(body); - when(() => ball.priority).thenReturn(1); - when(() => body.position).thenReturn(Vector2.zero()); - when(() => body.linearVelocity).thenReturn(Vector2(0, -1)); - when(() => ball.layer).thenReturn(Layer.board); - - callback.begin(ball, area, MockContact()); - verify(() => ball.layer = area.insideLayer).called(1); - - callback.end(ball, area, MockContact()); - verify(() => ball.layer = Layer.board); - }); - - flameTester.test( - 'change ball layer from pathwayLayer to Layer.board ' - 'when a ball enters and exits from ramp', (game) async { - final ball = MockBall(); - final body = MockBody(); - final area = TestRampOpening( - orientation: RampOrientation.down, - insidePriority: insidePriority, - pathwayLayer: Layer.spaceshipEntranceRamp, - )..initialPosition = Vector2(0, 10); - final callback = TestRampOpeningBallContactCallback(); - - when(() => ball.body).thenReturn(body); - when(() => ball.priority).thenReturn(1); - when(() => body.position).thenReturn(Vector2.zero()); - when(() => body.linearVelocity).thenReturn(Vector2(0, -1)); - when(() => ball.layer).thenReturn(Layer.board); - - callback.begin(ball, area, MockContact()); - verify(() => ball.layer = area.insideLayer).called(1); - - callback.end(ball, area, MockContact()); - verifyNever(() => ball.layer = Layer.board); - - callback.begin(ball, area, MockContact()); - verifyNever(() => ball.layer = area.insideLayer); - - callback.end(ball, area, MockContact()); - verify(() => ball.layer = Layer.board); - }); - }); -} diff --git a/packages/pinball_components/test/src/components/slingshot_test.dart b/packages/pinball_components/test/src/components/slingshot_test.dart index f32f01d2..a5535750 100644 --- a/packages/pinball_components/test/src/components/slingshot_test.dart +++ b/packages/pinball_components/test/src/components/slingshot_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -19,6 +20,7 @@ void main() { setUp: (game, tester) async { await game.addFromBlueprint(Slingshots()); game.camera.followVector2(Vector2.zero()); + await game.ready(); }, verify: (game, tester) async { await expectLater( diff --git a/packages/pinball_components/test/src/components/spaceship_rail_test.dart b/packages/pinball_components/test/src/components/spaceship_rail_test.dart index c35798c3..c73c8dee 100644 --- a/packages/pinball_components/test/src/components/spaceship_rail_test.dart +++ b/packages/pinball_components/test/src/components/spaceship_rail_test.dart @@ -3,8 +3,8 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -41,57 +41,4 @@ void main() { }, ); }); - - // TODO(alestiago): Make ContactCallback private and use `beginContact` - // instead. - group('SpaceshipRailExitBallContactCallback', () { - late Forge2DGame game; - late SpaceshipRailExit railExit; - late Ball ball; - late Body body; - late Fixture fixture; - late Filter filterData; - - setUp(() { - game = MockGame(); - - railExit = MockSpaceshipRailExit(); - - ball = MockBall(); - body = MockBody(); - when(() => ball.gameRef).thenReturn(game); - when(() => ball.body).thenReturn(body); - - fixture = MockFixture(); - filterData = MockFilter(); - when(() => body.fixtures).thenReturn([fixture]); - when(() => fixture.filterData).thenReturn(filterData); - }); - - setUp(() { - when(() => ball.priority).thenReturn(1); - when(() => railExit.outsideLayer).thenReturn(Layer.board); - when(() => railExit.outsidePriority).thenReturn(0); - }); - - test('changes the ball priority on contact', () { - SpaceshipRailExitBallContactCallback().begin( - railExit, - ball, - MockContact(), - ); - - verify(() => ball.sendTo(railExit.outsidePriority)).called(1); - }); - - test('changes the ball layer on contact', () { - SpaceshipRailExitBallContactCallback().begin( - railExit, - ball, - MockContact(), - ); - - verify(() => ball.layer = railExit.outsideLayer).called(1); - }); - }); } diff --git a/packages/pinball_components/test/src/components/spaceship_ramp_test.dart b/packages/pinball_components/test/src/components/spaceship_ramp_test.dart index b6afcde2..8b623461 100644 --- a/packages/pinball_components/test/src/components/spaceship_ramp_test.dart +++ b/packages/pinball_components/test/src/components/spaceship_ramp_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -16,6 +17,7 @@ void main() { setUp: (game, tester) async { await game.addFromBlueprint(SpaceshipRamp()); game.camera.followVector2(Vector2(-13, -50)); + await game.ready(); }, verify: (game, tester) async { await expectLater( diff --git a/packages/pinball_components/test/src/components/spaceship_test.dart b/packages/pinball_components/test/src/components/spaceship_test.dart index 0f627be9..c9a90746 100644 --- a/packages/pinball_components/test/src/components/spaceship_test.dart +++ b/packages/pinball_components/test/src/components/spaceship_test.dart @@ -5,6 +5,7 @@ import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; @@ -14,8 +15,6 @@ void main() { late Fixture fixture; late Body body; late Ball ball; - late SpaceshipEntrance entrance; - late SpaceshipHole hole; late Forge2DGame game; setUp(() { @@ -32,9 +31,6 @@ void main() { ball = MockBall(); when(() => ball.gameRef).thenReturn(game); when(() => ball.body).thenReturn(body); - - entrance = MockSpaceshipEntrance(); - hole = MockSpaceshipHole(); }); group('Spaceship', () { @@ -46,6 +42,7 @@ void main() { final position = Vector2(30, -30); await game.addFromBlueprint(Spaceship(position: position)); game.camera.followVector2(position); + await game.ready(); }, verify: (game, tester) async { await expectLater( @@ -55,36 +52,5 @@ void main() { }, ); }); - - group('SpaceshipEntranceBallContactCallback', () { - test('changes the ball priority on contact', () { - when(() => ball.priority).thenReturn(2); - when(() => entrance.insidePriority).thenReturn(3); - - SpaceshipEntranceBallContactCallback().begin( - entrance, - ball, - MockContact(), - ); - - verify(() => ball.sendTo(entrance.insidePriority)).called(1); - }); - }); - - group('SpaceshipHoleBallContactCallback', () { - test('changes the ball priority on contact', () { - when(() => ball.priority).thenReturn(2); - when(() => hole.outsideLayer).thenReturn(Layer.board); - when(() => hole.outsidePriority).thenReturn(1); - - SpaceshipHoleBallContactCallback().begin( - hole, - ball, - MockContact(), - ); - - verify(() => ball.sendTo(hole.outsidePriority)).called(1); - }); - }); }); } diff --git a/packages/pinball_components/test/src/components/sparky_computer_test.dart b/packages/pinball_components/test/src/components/sparky_computer_test.dart index c7573338..3d67106d 100644 --- a/packages/pinball_components/test/src/components/sparky_computer_test.dart +++ b/packages/pinball_components/test/src/components/sparky_computer_test.dart @@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; import '../../helpers/helpers.dart'; diff --git a/packages/pinball_components/test/src/flame/priority_test.dart b/packages/pinball_components/test/src/flame/priority_test.dart deleted file mode 100644 index 231c7744..00000000 --- a/packages/pinball_components/test/src/flame/priority_test.dart +++ /dev/null @@ -1,221 +0,0 @@ -// ignore_for_file: cascade_invocations -import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:flame_test/flame_test.dart'; -import 'package:flutter_test/flutter_test.dart'; -import 'package:mocktail/mocktail.dart'; -import 'package:pinball_components/src/flame/priority.dart'; - -import '../../helpers/helpers.dart'; - -class TestBodyComponent extends BodyComponent { - @override - Body createBody() { - final fixtureDef = FixtureDef(CircleShape()); - return world.createBody(BodyDef())..createFixture(fixtureDef); - } -} - -void main() { - final flameTester = FlameTester(Forge2DGame.new); - - group('ComponentPriorityX', () { - group('sendTo', () { - flameTester.test( - 'changes the priority correctly to other level', - (game) async { - const newPriority = 5; - final component = TestBodyComponent()..priority = 4; - - component.sendTo(newPriority); - - expect(component.priority, equals(newPriority)); - }, - ); - - flameTester.test( - 'calls reorderChildren if the new priority is different', - (game) async { - const newPriority = 5; - final component = MockComponent(); - when(() => component.priority).thenReturn(4); - - component.sendTo(newPriority); - - verify(component.reorderChildren).called(1); - }, - ); - - flameTester.test( - "doesn't call reorderChildren if the priority is the same", - (game) async { - const newPriority = 5; - final component = MockComponent(); - when(() => component.priority).thenReturn(newPriority); - - component.sendTo(newPriority); - - verifyNever(component.reorderChildren); - }, - ); - }); - - group('sendToBack', () { - flameTester.test( - 'changes the priority correctly to board level', - (game) async { - final component = TestBodyComponent()..priority = 4; - - component.sendToBack(); - - expect(component.priority, equals(0)); - }, - ); - - flameTester.test( - 'calls reorderChildren if the priority is greater than lowest level', - (game) async { - final component = MockComponent(); - when(() => component.priority).thenReturn(4); - - component.sendToBack(); - - verify(component.reorderChildren).called(1); - }, - ); - - flameTester.test( - "doesn't call reorderChildren if the priority is the lowest level", - (game) async { - final component = MockComponent(); - when(() => component.priority).thenReturn(0); - - component.sendToBack(); - - verifyNever(component.reorderChildren); - }, - ); - }); - - group('showBehindOf', () { - flameTester.test( - 'changes the priority if it is greater than other component', - (game) async { - const startPriority = 2; - final component = TestBodyComponent()..priority = startPriority; - final otherComponent = TestBodyComponent() - ..priority = startPriority - 1; - - component.showBehindOf(otherComponent); - - expect(component.priority, equals(otherComponent.priority - 1)); - }, - ); - - flameTester.test( - "doesn't change the priority if it is lower than other component", - (game) async { - const startPriority = 2; - final component = TestBodyComponent()..priority = startPriority; - final otherComponent = TestBodyComponent() - ..priority = startPriority + 1; - - component.showBehindOf(otherComponent); - - expect(component.priority, equals(startPriority)); - }, - ); - - flameTester.test( - 'calls reorderChildren if the priority is greater than other component', - (game) async { - const startPriority = 2; - final component = MockComponent(); - final otherComponent = MockComponent(); - when(() => component.priority).thenReturn(startPriority); - when(() => otherComponent.priority).thenReturn(startPriority - 1); - - component.showBehindOf(otherComponent); - - verify(component.reorderChildren).called(1); - }, - ); - - flameTester.test( - "doesn't call reorderChildren if the priority is lower than other " - 'component', - (game) async { - const startPriority = 2; - final component = MockComponent(); - final otherComponent = MockComponent(); - when(() => component.priority).thenReturn(startPriority); - when(() => otherComponent.priority).thenReturn(startPriority + 1); - - component.showBehindOf(otherComponent); - - verifyNever(component.reorderChildren); - }, - ); - }); - - group('showInFrontOf', () { - flameTester.test( - 'changes the priority if it is lower than other component', - (game) async { - const startPriority = 2; - final component = TestBodyComponent()..priority = startPriority; - final otherComponent = TestBodyComponent() - ..priority = startPriority + 1; - - component.showInFrontOf(otherComponent); - - expect(component.priority, equals(otherComponent.priority + 1)); - }, - ); - - flameTester.test( - "doesn't change the priority if it is greater than other component", - (game) async { - const startPriority = 2; - final component = TestBodyComponent()..priority = startPriority; - final otherComponent = TestBodyComponent() - ..priority = startPriority - 1; - - component.showInFrontOf(otherComponent); - - expect(component.priority, equals(startPriority)); - }, - ); - - flameTester.test( - 'calls reorderChildren if the priority is lower than other component', - (game) async { - const startPriority = 2; - final component = MockComponent(); - final otherComponent = MockComponent(); - when(() => component.priority).thenReturn(startPriority); - when(() => otherComponent.priority).thenReturn(startPriority + 1); - - component.showInFrontOf(otherComponent); - - verify(component.reorderChildren).called(1); - }, - ); - - flameTester.test( - "doesn't call reorderChildren if the priority is greater than other " - 'component', - (game) async { - const startPriority = 2; - final component = MockComponent(); - final otherComponent = MockComponent(); - when(() => component.priority).thenReturn(startPriority); - when(() => otherComponent.priority).thenReturn(startPriority - 1); - - component.showInFrontOf(otherComponent); - - verifyNever(component.reorderChildren); - }, - ); - }); - }); -} diff --git a/packages/pinball_flame/.gitignore b/packages/pinball_flame/.gitignore new file mode 100644 index 00000000..d6130351 --- /dev/null +++ b/packages/pinball_flame/.gitignore @@ -0,0 +1,39 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# VSCode related +.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Web related +lib/generated_plugin_registrant.dart + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json diff --git a/packages/pinball_flame/README.md b/packages/pinball_flame/README.md new file mode 100644 index 00000000..ecf0f4d4 --- /dev/null +++ b/packages/pinball_flame/README.md @@ -0,0 +1,11 @@ +# pinball_flame + +[![style: very good analysis][very_good_analysis_badge]][very_good_analysis_link] +[![License: MIT][license_badge]][license_link] + +Set of out-of-the-way solutions for common Pinball game problems. + +[license_badge]: https://img.shields.io/badge/license-MIT-blue.svg +[license_link]: https://opensource.org/licenses/MIT +[very_good_analysis_badge]: https://img.shields.io/badge/style-very_good_analysis-B22C89.svg +[very_good_analysis_link]: https://pub.dev/packages/very_good_analysis \ No newline at end of file diff --git a/packages/pinball_flame/analysis_options.yaml b/packages/pinball_flame/analysis_options.yaml new file mode 100644 index 00000000..3742fc3d --- /dev/null +++ b/packages/pinball_flame/analysis_options.yaml @@ -0,0 +1 @@ +include: package:very_good_analysis/analysis_options.2.4.0.yaml \ No newline at end of file diff --git a/packages/pinball_flame/lib/pinball_flame.dart b/packages/pinball_flame/lib/pinball_flame.dart new file mode 100644 index 00000000..2d2e760b --- /dev/null +++ b/packages/pinball_flame/lib/pinball_flame.dart @@ -0,0 +1,5 @@ +library pinball_flame; + +export 'src/blueprint.dart'; +export 'src/component_controller.dart'; +export 'src/keyboard_input_controller.dart'; diff --git a/packages/pinball_components/lib/src/flame/blueprint.dart b/packages/pinball_flame/lib/src/blueprint.dart similarity index 100% rename from packages/pinball_components/lib/src/flame/blueprint.dart rename to packages/pinball_flame/lib/src/blueprint.dart diff --git a/lib/flame/component_controller.dart b/packages/pinball_flame/lib/src/component_controller.dart similarity index 91% rename from lib/flame/component_controller.dart rename to packages/pinball_flame/lib/src/component_controller.dart index b9568348..6afc1c40 100644 --- a/lib/flame/component_controller.dart +++ b/packages/pinball_flame/lib/src/component_controller.dart @@ -1,12 +1,9 @@ import 'package:flame/components.dart'; -import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/foundation.dart'; /// {@template component_controller} /// A [ComponentController] is a [Component] in charge of handling the logic /// associated with another [Component]. -/// -/// [ComponentController]s usually implement [BlocComponent]. /// {@endtemplate} abstract class ComponentController extends Component { /// {@macro component_controller} diff --git a/packages/pinball_components/lib/src/flame/keyboard_input_controller.dart b/packages/pinball_flame/lib/src/keyboard_input_controller.dart similarity index 100% rename from packages/pinball_components/lib/src/flame/keyboard_input_controller.dart rename to packages/pinball_flame/lib/src/keyboard_input_controller.dart diff --git a/packages/pinball_flame/pubspec.yaml b/packages/pinball_flame/pubspec.yaml new file mode 100644 index 00000000..ad8ec131 --- /dev/null +++ b/packages/pinball_flame/pubspec.yaml @@ -0,0 +1,20 @@ +name: pinball_flame +description: Set of out-of-the-way solutions for common Pinball game problems. +version: 1.0.0+1 +publish_to: none + +environment: + sdk: ">=2.16.0 <3.0.0" + +dependencies: + flame: ^1.1.1 + flame_forge2d: ^0.11.0 + flutter: + sdk: flutter + +dev_dependencies: + flame_test: ^1.3.0 + flutter_test: + sdk: flutter + mocktail: ^0.3.0 + very_good_analysis: ^2.4.0 diff --git a/packages/pinball_flame/test/helpers/helpers.dart b/packages/pinball_flame/test/helpers/helpers.dart new file mode 100644 index 00000000..efe914f6 --- /dev/null +++ b/packages/pinball_flame/test/helpers/helpers.dart @@ -0,0 +1 @@ +export 'mocks.dart'; diff --git a/packages/pinball_flame/test/helpers/mocks.dart b/packages/pinball_flame/test/helpers/mocks.dart new file mode 100644 index 00000000..bf96390d --- /dev/null +++ b/packages/pinball_flame/test/helpers/mocks.dart @@ -0,0 +1,10 @@ +import 'package:flame/components.dart'; +import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:mocktail/mocktail.dart'; + +class MockForge2DGame extends Mock implements Forge2DGame {} + +class MockContactCallback extends Mock + implements ContactCallback {} + +class MockComponent extends Mock implements Component {} diff --git a/packages/pinball_components/test/src/flame/blueprint_test.dart b/packages/pinball_flame/test/src/blueprint_test.dart similarity index 82% rename from packages/pinball_components/test/src/flame/blueprint_test.dart rename to packages/pinball_flame/test/src/blueprint_test.dart index a9629422..f1c58dc9 100644 --- a/packages/pinball_components/test/src/flame/blueprint_test.dart +++ b/packages/pinball_flame/test/src/blueprint_test.dart @@ -1,9 +1,12 @@ import 'package:flame/components.dart'; +import 'package:flame_forge2d/contact_callbacks.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; -import '../../helpers/helpers.dart'; +import '../helpers/helpers.dart'; + +class TestContactCallback extends ContactCallback {} class MyBlueprint extends Blueprint { @override @@ -51,19 +54,19 @@ void main() { }); test('components can be added to it', () { - final blueprint = MyBlueprint()..build(MockGame()); + final blueprint = MyBlueprint()..build(MockForge2DGame()); expect(blueprint.components.length, equals(3)); }); test('blueprints can be added to it', () { - final blueprint = MyComposedBlueprint()..build(MockGame()); + final blueprint = MyComposedBlueprint()..build(MockForge2DGame()); expect(blueprint.blueprints.length, equals(3)); }); test('adds the components to a game on attach', () { - final mockGame = MockGame(); + final mockGame = MockForge2DGame(); when(() => mockGame.addAll(any())).thenAnswer((_) async {}); MyBlueprint().attach(mockGame); @@ -71,7 +74,7 @@ void main() { }); test('adds components from a child Blueprint the to a game on attach', () { - final mockGame = MockGame(); + final mockGame = MockForge2DGame(); when(() => mockGame.addAll(any())).thenAnswer((_) async {}); MyComposedBlueprint().attach(mockGame); @@ -81,7 +84,7 @@ void main() { test( 'throws assertion error when adding to an already attached blueprint', () async { - final mockGame = MockGame(); + final mockGame = MockForge2DGame(); when(() => mockGame.addAll(any())).thenAnswer((_) async {}); final blueprint = MyBlueprint(); await blueprint.attach(mockGame); @@ -94,17 +97,17 @@ void main() { group('Forge2DBlueprint', () { setUpAll(() { - registerFallbackValue(SpaceshipHoleBallContactCallback()); + registerFallbackValue(TestContactCallback()); }); test('callbacks can be added to it', () { - final blueprint = MyForge2dBlueprint()..build(MockGame()); + final blueprint = MyForge2dBlueprint()..build(MockForge2DGame()); expect(blueprint.callbacks.length, equals(3)); }); test('adds the callbacks to a game on attach', () async { - final mockGame = MockGame(); + final mockGame = MockForge2DGame(); when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {}); await MyForge2dBlueprint().attach(mockGame); @@ -115,7 +118,7 @@ void main() { test( 'throws assertion error when adding to an already attached blueprint', () async { - final mockGame = MockGame(); + final mockGame = MockForge2DGame(); when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {}); final blueprint = MyForge2dBlueprint(); diff --git a/test/flame/component_controller_test.dart b/packages/pinball_flame/test/src/component_controller_test.dart similarity index 97% rename from test/flame/component_controller_test.dart rename to packages/pinball_flame/test/src/component_controller_test.dart index e1973274..0e08be92 100644 --- a/test/flame/component_controller_test.dart +++ b/packages/pinball_flame/test/src/component_controller_test.dart @@ -4,7 +4,7 @@ import 'package:flame/game.dart'; import 'package:flame/src/components/component.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; -import 'package:pinball/flame/flame.dart'; +import 'package:pinball_flame/pinball_flame.dart'; class TestComponentController extends ComponentController { TestComponentController(Component component) : super(component); diff --git a/packages/pinball_components/test/src/flame/keyboard_input_controller_test.dart b/packages/pinball_flame/test/src/keyboard_input_controller_test.dart similarity index 96% rename from packages/pinball_components/test/src/flame/keyboard_input_controller_test.dart rename to packages/pinball_flame/test/src/keyboard_input_controller_test.dart index 991f1143..99a0006b 100644 --- a/packages/pinball_components/test/src/flame/keyboard_input_controller_test.dart +++ b/packages/pinball_flame/test/src/keyboard_input_controller_test.dart @@ -4,7 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; -import 'package:pinball_components/pinball_components.dart'; +import 'package:pinball_flame/pinball_flame.dart'; abstract class _KeyCallStub { bool onCall(); diff --git a/pubspec.lock b/pubspec.lock index 08188ef7..1a502f37 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -483,6 +483,13 @@ packages: relative: true source: path version: "1.0.0+1" + pinball_flame: + dependency: "direct main" + description: + path: "packages/pinball_flame" + relative: true + source: path + version: "1.0.0+1" pinball_theme: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 6141415c..f7676247 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -27,6 +27,8 @@ dependencies: path: packages/pinball_audio pinball_components: path: packages/pinball_components + pinball_flame: + path: packages/pinball_flame pinball_theme: path: packages/pinball_theme diff --git a/test/game/bloc/game_bloc_test.dart b/test/game/bloc/game_bloc_test.dart index e83c35d3..37e14f73 100644 --- a/test/game/bloc/game_bloc_test.dart +++ b/test/game/bloc/game_bloc_test.dart @@ -21,7 +21,6 @@ void main() { const GameState( score: 0, balls: 2, - activatedDashNests: {}, bonusHistory: [], ), ], @@ -40,13 +39,11 @@ void main() { const GameState( score: 2, balls: 3, - activatedDashNests: {}, bonusHistory: [], ), const GameState( score: 5, balls: 3, - activatedDashNests: {}, bonusHistory: [], ), ], @@ -66,56 +63,22 @@ void main() { const GameState( score: 0, balls: 2, - activatedDashNests: {}, bonusHistory: [], ), const GameState( score: 0, balls: 1, - activatedDashNests: {}, bonusHistory: [], ), const GameState( score: 0, balls: 0, - activatedDashNests: {}, bonusHistory: [], ), ], ); }); - group('DashNestActivated', () { - blocTest( - 'adds the bonus when all nests are activated', - build: GameBloc.new, - act: (bloc) => bloc - ..add(const DashNestActivated('0')) - ..add(const DashNestActivated('1')) - ..add(const DashNestActivated('2')), - expect: () => const [ - GameState( - score: 0, - balls: 3, - activatedDashNests: {'0'}, - bonusHistory: [], - ), - GameState( - score: 0, - balls: 3, - activatedDashNests: {'0', '1'}, - bonusHistory: [], - ), - GameState( - score: 0, - balls: 4, - activatedDashNests: {}, - bonusHistory: [GameBonus.dashNest], - ), - ], - ); - }); - group( 'BonusActivated', () { @@ -129,13 +92,11 @@ void main() { GameState( score: 0, balls: 3, - activatedDashNests: {}, bonusHistory: [GameBonus.googleWord], ), GameState( score: 0, balls: 3, - activatedDashNests: {}, bonusHistory: [GameBonus.googleWord, GameBonus.dashNest], ), ], @@ -152,7 +113,6 @@ void main() { GameState( score: 0, balls: 3, - activatedDashNests: {}, bonusHistory: [GameBonus.sparkyTurboCharge], ), ], diff --git a/test/game/bloc/game_event_test.dart b/test/game/bloc/game_event_test.dart index ef2a9f54..d7d587bd 100644 --- a/test/game/bloc/game_event_test.dart +++ b/test/game/bloc/game_event_test.dart @@ -59,23 +59,6 @@ void main() { }); }); - group('DashNestActivated', () { - test('can be instantiated', () { - expect(const DashNestActivated('0'), isNotNull); - }); - - test('supports value equality', () { - expect( - DashNestActivated('0'), - equals(DashNestActivated('0')), - ); - expect( - DashNestActivated('0'), - isNot(equals(DashNestActivated('1'))), - ); - }); - }); - group('SparkyTurboChargeActivated', () { test('can be instantiated', () { expect(const SparkyTurboChargeActivated(), isNotNull); diff --git a/test/game/bloc/game_state_test.dart b/test/game/bloc/game_state_test.dart index 81ca29f1..8170346f 100644 --- a/test/game/bloc/game_state_test.dart +++ b/test/game/bloc/game_state_test.dart @@ -10,14 +10,12 @@ void main() { GameState( score: 0, balls: 0, - activatedDashNests: const {}, bonusHistory: const [], ), equals( const GameState( score: 0, balls: 0, - activatedDashNests: {}, bonusHistory: [], ), ), @@ -30,7 +28,6 @@ void main() { const GameState( score: 0, balls: 0, - activatedDashNests: {}, bonusHistory: [], ), isNotNull, @@ -46,7 +43,6 @@ void main() { () => GameState( balls: -1, score: 0, - activatedDashNests: const {}, bonusHistory: const [], ), throwsAssertionError, @@ -62,7 +58,6 @@ void main() { () => GameState( balls: 0, score: -1, - activatedDashNests: const {}, bonusHistory: const [], ), throwsAssertionError, @@ -77,7 +72,6 @@ void main() { const gameState = GameState( balls: 0, score: 0, - activatedDashNests: {}, bonusHistory: [], ); expect(gameState.isGameOver, isTrue); @@ -89,7 +83,6 @@ void main() { const gameState = GameState( balls: 1, score: 0, - activatedDashNests: {}, bonusHistory: [], ); expect(gameState.isGameOver, isFalse); @@ -104,7 +97,6 @@ void main() { const gameState = GameState( balls: 0, score: 2, - activatedDashNests: {}, bonusHistory: [], ); expect( @@ -121,7 +113,6 @@ void main() { const gameState = GameState( balls: 0, score: 2, - activatedDashNests: {}, bonusHistory: [], ); expect( @@ -138,13 +129,11 @@ void main() { const gameState = GameState( score: 2, balls: 0, - activatedDashNests: {}, bonusHistory: [], ); final otherGameState = GameState( score: gameState.score + 1, balls: gameState.balls + 1, - activatedDashNests: const {'1'}, bonusHistory: const [GameBonus.googleWord], ); expect(gameState, isNot(equals(otherGameState))); @@ -153,7 +142,6 @@ void main() { gameState.copyWith( score: otherGameState.score, balls: otherGameState.balls, - activatedDashNests: otherGameState.activatedDashNests, bonusHistory: otherGameState.bonusHistory, ), equals(otherGameState), diff --git a/test/game/components/controlled_flipper_test.dart b/test/game/components/controlled_flipper_test.dart index 3c0fc1b0..01982129 100644 --- a/test/game/components/controlled_flipper_test.dart +++ b/test/game/components/controlled_flipper_test.dart @@ -21,7 +21,6 @@ void main() { score: 0, balls: 0, bonusHistory: [], - activatedDashNests: {}, ); whenListen(bloc, Stream.value(state), initialState: state); return bloc; diff --git a/test/game/components/controlled_plunger_test.dart b/test/game/components/controlled_plunger_test.dart index a377487e..eee2bcb0 100644 --- a/test/game/components/controlled_plunger_test.dart +++ b/test/game/components/controlled_plunger_test.dart @@ -22,7 +22,6 @@ void main() { score: 0, balls: 0, bonusHistory: [], - activatedDashNests: {}, ); whenListen(bloc, Stream.value(state), initialState: state); return bloc; diff --git a/test/game/components/flutter_forest_test.dart b/test/game/components/flutter_forest_test.dart index 7ad5a3de..2089b7b7 100644 --- a/test/game/components/flutter_forest_test.dart +++ b/test/game/components/flutter_forest_test.dart @@ -79,105 +79,21 @@ void main() { ); }); - group('controller', () { - group('listenWhen', () { - final gameBloc = MockGameBloc(); - final flameBlocTester = FlameBlocTester( - gameBuilder: TestGame.new, - blocBuilder: () => gameBloc, - ); - - flameBlocTester.testGameWidget( - 'listens when a Bonus.dashNest and a bonusBall is added', - verify: (game, tester) async { - final flutterForest = FlutterForest(); - - const state = GameState( - score: 0, - balls: 3, - activatedDashNests: {}, - bonusHistory: [GameBonus.dashNest], - ); - - expect( - flutterForest.controller - .listenWhen(const GameState.initial(), state), - isTrue, - ); - }, - ); - }); - }); - - flameTester.test( - 'onNewState adds a new ball after a duration', - (game) async { - final flutterForest = FlutterForest(); - await game.ensureAdd(flutterForest); - - final previousBalls = game.descendants().whereType().length; - flutterForest.controller.onNewState(MockGameState()); - - await Future.delayed(const Duration(milliseconds: 700)); - await game.ready(); - - expect( - game.descendants().whereType().length, - greaterThan(previousBalls), - ); - }, - ); - - flameTester.test( - 'onNewState starts Dash animatronic', - (game) async { - final flutterForest = FlutterForest(); - await game.ensureAdd(flutterForest); - - flutterForest.controller.onNewState(MockGameState()); - final dashAnimatronic = - game.descendants().whereType().single; - - expect(dashAnimatronic.playing, isTrue); - }, - ); - group('bumpers', () { late Ball ball; late GameBloc gameBloc; setUp(() { ball = Ball(baseColor: const Color(0xFF00FFFF)); - gameBloc = MockGameBloc(); - whenListen( - gameBloc, - const Stream.empty(), - initialState: const GameState.initial(), - ); }); final flameBlocTester = FlameBlocTester( gameBuilder: EmptyPinballTestGame.new, - blocBuilder: () => gameBloc, - ); - - flameBlocTester.testGameWidget( - 'add DashNestActivated event', - setUp: (game, tester) async { - final flutterForest = FlutterForest(); - await game.ensureAdd(flutterForest); - await game.ensureAdd(ball); - - final bumpers = - flutterForest.descendants().whereType(); - - for (final bumper in bumpers) { - beginContact(game, bumper, ball); - final controller = bumper.firstChild()!; - verify( - () => gameBloc.add(DashNestActivated(controller.id)), - ).called(1); - } + blocBuilder: () { + gameBloc = MockGameBloc(); + const state = GameState.initial(); + whenListen(gameBloc, Stream.value(state), initialState: state); + return gameBloc; }, ); @@ -185,8 +101,10 @@ void main() { 'add Scored event', setUp: (game, tester) async { final flutterForest = FlutterForest(); - await game.ensureAdd(flutterForest); - await game.ensureAdd(ball); + await game.ensureAddAll([ + flutterForest, + ball, + ]); game.addContactCallback(BallScorePointsCallback(game)); final bumpers = flutterForest.descendants().whereType(); @@ -201,122 +119,58 @@ void main() { } }, ); - }); - }); - - group('DashNestBumperController', () { - late DashNestBumper dashNestBumper; - setUp(() { - dashNestBumper = MockDashNestBumper(); - }); - - group( - 'listensWhen', - () { - late GameState previousState; - late GameState newState; - - setUp( - () { - previousState = MockGameState(); - newState = MockGameState(); - }, - ); - - test('listens when the id is added to activatedDashNests', () { - const id = ''; - final controller = DashNestBumperController( - dashNestBumper, - id: id, - ); - - when(() => previousState.activatedDashNests).thenReturn({}); - when(() => newState.activatedDashNests).thenReturn({id}); - - expect(controller.listenWhen(previousState, newState), isTrue); - }); - - test('listens when the id is removed from activatedDashNests', () { - const id = ''; - final controller = DashNestBumperController( - dashNestBumper, - id: id, - ); - - when(() => previousState.activatedDashNests).thenReturn({id}); - when(() => newState.activatedDashNests).thenReturn({}); - - expect(controller.listenWhen(previousState, newState), isTrue); - }); - - test("doesn't listen when the id is never in activatedDashNests", () { - final controller = DashNestBumperController( - dashNestBumper, - id: '', - ); - - when(() => previousState.activatedDashNests).thenReturn({}); - when(() => newState.activatedDashNests).thenReturn({}); - - expect(controller.listenWhen(previousState, newState), isFalse); - }); - - test("doesn't listen when the id still in activatedDashNests", () { - const id = ''; - final controller = DashNestBumperController( - dashNestBumper, - id: id, - ); - - when(() => previousState.activatedDashNests).thenReturn({id}); - when(() => newState.activatedDashNests).thenReturn({id}); - - expect(controller.listenWhen(previousState, newState), isFalse); - }); - }, - ); - - group( - 'onNewState', - () { - late GameState state; - - setUp(() { - state = MockGameState(); - }); - - test( - 'activates the bumper when id in activatedDashNests', - () { - const id = ''; - final controller = DashNestBumperController( - dashNestBumper, - id: id, - ); - - when(() => state.activatedDashNests).thenReturn({id}); - controller.onNewState(state); + flameBlocTester.testGameWidget( + 'adds GameBonus.dashNest to the game when 3 bumpers are activated', + setUp: (game, _) async { + final ball = Ball(baseColor: const Color(0xFFFF0000)); + final flutterForest = FlutterForest(); + await game.ensureAddAll([flutterForest, ball]); - verify(() => dashNestBumper.activate()).called(1); - }, - ); + final bumpers = flutterForest.children.whereType(); + expect(bumpers.length, equals(3)); + for (final bumper in bumpers) { + beginContact(game, bumper, ball); + await game.ready(); + + if (bumper == bumpers.last) { + verify( + () => gameBloc.add(const BonusActivated(GameBonus.dashNest)), + ).called(1); + } else { + verifyNever( + () => gameBloc.add(const BonusActivated(GameBonus.dashNest)), + ); + } + } + }, + ); - test( - 'deactivates the bumper when id not in activatedDashNests', - () { - final controller = DashNestBumperController( - dashNestBumper, - id: '', - ); + flameBlocTester.testGameWidget( + 'deactivates bumpers when 3 are active', + setUp: (game, _) async { + final ball = Ball(baseColor: const Color(0xFFFF0000)); + final flutterForest = FlutterForest(); + await game.ensureAddAll([flutterForest, ball]); - when(() => state.activatedDashNests).thenReturn({}); - controller.onNewState(state); + final bumpers = [ + MockDashNestBumper(), + MockDashNestBumper(), + MockDashNestBumper(), + ]; - verify(() => dashNestBumper.deactivate()).called(1); - }, - ); - }, - ); + for (final bumper in bumpers) { + flutterForest.controller.activateBumper(bumper); + await game.ready(); + + if (bumper == bumpers.last) { + for (final bumper in bumpers) { + verify(bumper.deactivate).called(1); + } + } + } + }, + ); + }); }); } diff --git a/test/game/components/game_flow_controller_test.dart b/test/game/components/game_flow_controller_test.dart index 8bb81a6c..b9a6181a 100644 --- a/test/game/components/game_flow_controller_test.dart +++ b/test/game/components/game_flow_controller_test.dart @@ -16,7 +16,6 @@ void main() { score: 10, balls: 0, bonusHistory: const [], - activatedDashNests: const {}, ); final previous = GameState.initial(); @@ -66,7 +65,6 @@ void main() { score: 10, balls: 0, bonusHistory: const [], - activatedDashNests: const {}, ), ); diff --git a/test/game/components/score_effect_controller_test.dart b/test/game/components/score_effect_controller_test.dart index 9d2b5310..b5c76dc6 100644 --- a/test/game/components/score_effect_controller_test.dart +++ b/test/game/components/score_effect_controller_test.dart @@ -31,7 +31,6 @@ void main() { score: 10, balls: 3, bonusHistory: [], - activatedDashNests: {}, ); expect(controller.listenWhen(previous, current), isTrue); }); @@ -44,7 +43,6 @@ void main() { score: 10, balls: 3, bonusHistory: [], - activatedDashNests: {}, ); expect(controller.listenWhen(null, current), isTrue); }, @@ -69,7 +67,6 @@ void main() { score: 10, balls: 3, bonusHistory: [], - activatedDashNests: {}, ); controller.onNewState(state); @@ -87,7 +84,6 @@ void main() { score: 10, balls: 3, bonusHistory: [], - activatedDashNests: {}, ), ); @@ -96,7 +92,6 @@ void main() { score: 14, balls: 3, bonusHistory: [], - activatedDashNests: {}, ), ); diff --git a/test/game/view/game_hud_test.dart b/test/game/view/game_hud_test.dart index 2d5f50d9..cdc56832 100644 --- a/test/game/view/game_hud_test.dart +++ b/test/game/view/game_hud_test.dart @@ -12,7 +12,6 @@ void main() { const initialState = GameState( score: 10, balls: 2, - activatedDashNests: {}, bonusHistory: [], ); diff --git a/test/helpers/mocks.dart b/test/helpers/mocks.dart index 12e6d366..fd01a509 100644 --- a/test/helpers/mocks.dart +++ b/test/helpers/mocks.dart @@ -31,11 +31,6 @@ class MockContact extends Mock implements Contact {} class MockContactCallback extends Mock implements ContactCallback {} -class MockRampOpening extends Mock implements RampOpening {} - -class MockRampOpeningBallContactCallback extends Mock - implements RampOpeningBallContactCallback {} - class MockGameBloc extends Mock implements GameBloc {} class MockGameState extends Mock implements GameState {}