Merge branch 'main' into feat/priority-management

pull/198/head
Allison Ryan 3 years ago
commit 44d384fd68

@ -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

@ -1 +0,0 @@
export 'component_controller.dart';

@ -12,7 +12,6 @@ class GameBloc extends Bloc<GameEvent, GameState> {
on<BallLost>(_onBallLost); on<BallLost>(_onBallLost);
on<Scored>(_onScored); on<Scored>(_onScored);
on<BonusActivated>(_onBonusActivated); on<BonusActivated>(_onBonusActivated);
on<DashNestActivated>(_onDashNestActivated);
on<SparkyTurboChargeActivated>(_onSparkyTurboChargeActivated); on<SparkyTurboChargeActivated>(_onSparkyTurboChargeActivated);
} }
@ -34,31 +33,6 @@ class GameBloc extends Bloc<GameEvent, GameState> {
); );
} }
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<void> _onSparkyTurboChargeActivated( Future<void> _onSparkyTurboChargeActivated(
SparkyTurboChargeActivated event, SparkyTurboChargeActivated event,
Emitter emit, Emitter emit,

@ -42,15 +42,6 @@ class BonusActivated extends GameEvent {
List<Object?> get props => [bonus]; List<Object?> get props => [bonus];
} }
class DashNestActivated extends GameEvent {
const DashNestActivated(this.nestId);
final String nestId;
@override
List<Object?> get props => [nestId];
}
class SparkyTurboChargeActivated extends GameEvent { class SparkyTurboChargeActivated extends GameEvent {
const SparkyTurboChargeActivated(); const SparkyTurboChargeActivated();

@ -23,14 +23,12 @@ class GameState extends Equatable {
required this.score, required this.score,
required this.balls, required this.balls,
required this.bonusHistory, required this.bonusHistory,
required this.activatedDashNests,
}) : assert(score >= 0, "Score can't be negative"), }) : assert(score >= 0, "Score can't be negative"),
assert(balls >= 0, "Number of balls can't be negative"); assert(balls >= 0, "Number of balls can't be negative");
const GameState.initial() const GameState.initial()
: score = 0, : score = 0,
balls = 3, balls = 3,
activatedDashNests = const {},
bonusHistory = const []; bonusHistory = const [];
/// The current score of the game. /// 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. /// When the number of balls is 0, the game is over.
final int balls; final int balls;
/// Active dash nests.
final Set<String> activatedDashNests;
/// Holds the history of all the [GameBonus]es earned by the player during a /// Holds the history of all the [GameBonus]es earned by the player during a
/// PinballGame. /// PinballGame.
final List<GameBonus> bonusHistory; final List<GameBonus> bonusHistory;
@ -54,7 +49,6 @@ class GameState extends Equatable {
GameState copyWith({ GameState copyWith({
int? score, int? score,
int? balls, int? balls,
Set<String>? activatedDashNests,
List<GameBonus>? bonusHistory, List<GameBonus>? bonusHistory,
}) { }) {
assert( assert(
@ -65,7 +59,6 @@ class GameState extends Equatable {
return GameState( return GameState(
score: score ?? this.score, score: score ?? this.score,
balls: balls ?? this.balls, balls: balls ?? this.balls,
activatedDashNests: activatedDashNests ?? this.activatedDashNests,
bonusHistory: bonusHistory ?? this.bonusHistory, bonusHistory: bonusHistory ?? this.bonusHistory,
); );
} }
@ -74,7 +67,6 @@ class GameState extends Equatable {
List<Object?> get props => [ List<Object?> get props => [
score, score,
balls, balls,
activatedDashNests,
bonusHistory, bonusHistory,
]; ];
} }

@ -3,9 +3,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template alien_zone} /// {@template alien_zone}
/// Area positioned below [Spaceship] where the [Ball] /// Area positioned below [Spaceship] where the [Ball]

@ -1,7 +1,7 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame/game.dart'; import 'package:flame/game.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Adds helpers methods to Flame's [Camera] /// Adds helpers methods to Flame's [Camera]
extension CameraX on Camera { extension CameraX on Camera {

@ -1,9 +1,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/forge2d_game.dart'; import 'package:flame_forge2d/forge2d_game.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball_theme/pinball_theme.dart';
/// {@template controlled_ball} /// {@template controlled_ball}

@ -1,9 +1,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template controlled_flipper} /// {@template controlled_flipper}
/// A [Flipper] with a [FlipperController] attached. /// A [Flipper] with a [FlipperController] attached.

@ -1,9 +1,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template controlled_plunger} /// {@template controlled_plunger}
/// A [Plunger] with a [PlungerController] attached. /// A [Plunger] with a [PlungerController] attached.

@ -3,9 +3,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template controlled_sparky_computer} /// {@template controlled_sparky_computer}
/// [SparkyComputer] with a [SparkyComputerController] attached. /// [SparkyComputer] with a [SparkyComputerController] attached.

@ -1,12 +1,10 @@
// ignore_for_file: avoid_renaming_method_parameters // ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.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/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template flutter_forest} /// {@template flutter_forest}
/// Area positioned at the top right of the [Board] where the [Ball] /// 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] /// When all [DashNestBumper]s are hit at least once, the [GameBonus.dashNest]
/// is awarded, and the [BigDashNestBumper] releases a new [Ball]. /// is awarded, and the [BigDashNestBumper] releases a new [Ball].
/// {@endtemplate} /// {@endtemplate}
// TODO(alestiago): Make a [Blueprint] once [Blueprint] inherits from class FlutterForest extends Component
// [Component]. with Controls<_FlutterForestController>, HasGameRef<PinballGame> {
class FlutterForest extends Component with Controls<_FlutterForestController> {
/// {@macro flutter_forest} /// {@macro flutter_forest}
FlutterForest() { FlutterForest() {
controller = _FlutterForestController(this); controller = _FlutterForestController(this);
@ -26,17 +23,16 @@ class FlutterForest extends Component with Controls<_FlutterForestController> {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
gameRef.addContactCallback(_DashNestBumperBallContactCallback());
final signPost = FlutterSignPost()..initialPosition = Vector2(8.35, -58.3); final signPost = FlutterSignPost()..initialPosition = Vector2(8.35, -58.3);
final bigNest = _ControlledBigDashNestBumper( final bigNest = _BigDashNestBumper()
id: 'big_nest_bumper', ..initialPosition = Vector2(18.55, -59.35);
)..initialPosition = Vector2(18.55, -59.35); final smallLeftNest = _SmallDashNestBumper.a()
final smallLeftNest = _ControlledSmallDashNestBumper.a( ..initialPosition = Vector2(8.95, -51.95);
id: 'small_nest_bumper_a', final smallRightNest = _SmallDashNestBumper.b()
)..initialPosition = Vector2(8.95, -51.95); ..initialPosition = Vector2(23.3, -46.75);
final smallRightNest = _ControlledSmallDashNestBumper.b(
id: 'small_nest_bumper_b',
)..initialPosition = Vector2(23.3, -46.75);
final dashAnimatronic = DashAnimatronic()..position = Vector2(20, -66); final dashAnimatronic = DashAnimatronic()..position = Vector2(20, -66);
await addAll([ await addAll([
@ -50,31 +46,31 @@ class FlutterForest extends Component with Controls<_FlutterForestController> {
} }
class _FlutterForestController extends ComponentController<FlutterForest> class _FlutterForestController extends ComponentController<FlutterForest>
with BlocComponent<GameBloc, GameState>, HasGameRef<PinballGame> { with HasGameRef<PinballGame> {
_FlutterForestController(FlutterForest flutterForest) : super(flutterForest); _FlutterForestController(FlutterForest flutterForest) : super(flutterForest);
@override final _activatedBumpers = <DashNestBumper>{};
Future<void> onLoad() async {
await super.onLoad();
gameRef.addContactCallback(_ControlledDashNestBumperBallContactCallback());
}
@override void activateBumper(DashNestBumper dashNestBumper) {
bool listenWhen(GameState? previousState, GameState newState) { if (!_activatedBumpers.add(dashNestBumper)) return;
return (previousState?.bonusHistory.length ?? 0) <
newState.bonusHistory.length &&
newState.bonusHistory.last == GameBonus.dashNest;
}
@override dashNestBumper.activate();
void onNewState(GameState state) {
super.onNewState(state);
component.firstChild<DashAnimatronic>()?.playing = true; final activatedBonus = _activatedBumpers.length == 3;
if (activatedBonus) {
_addBonusBall(); _addBonusBall();
gameRef.read<GameBloc>().add(const BonusActivated(GameBonus.dashNest));
_activatedBumpers
..forEach((bumper) => bumper.deactivate())
..clear();
component.firstChild<DashAnimatronic>()?.playing = true;
}
} }
Future<void> _addBonusBall() async { Future<void> _addBonusBall() async {
// TODO(alestiago): Remove hardcoded duration.
await Future<void>.delayed(const Duration(milliseconds: 700)); await Future<void>.delayed(const Duration(milliseconds: 700));
await gameRef.add( await gameRef.add(
ControlledBall.bonus(theme: gameRef.theme) ControlledBall.bonus(theme: gameRef.theme)
@ -83,83 +79,29 @@ class _FlutterForestController extends ComponentController<FlutterForest>
} }
} }
class _ControlledBigDashNestBumper extends BigDashNestBumper // TODO(alestiago): Revisit ScorePoints logic once the FlameForge2D
with Controls<DashNestBumperController>, ScorePoints { // ContactCallback process is enhanced.
_ControlledBigDashNestBumper({required String id}) : super() { class _BigDashNestBumper extends BigDashNestBumper with ScorePoints {
controller = DashNestBumperController(this, id: id);
}
@override @override
int get points => 20; int get points => 20;
} }
class _ControlledSmallDashNestBumper extends SmallDashNestBumper class _SmallDashNestBumper extends SmallDashNestBumper with ScorePoints {
with Controls<DashNestBumperController>, ScorePoints { _SmallDashNestBumper.a() : super.a();
_ControlledSmallDashNestBumper.a({required String id}) : super.a() {
controller = DashNestBumperController(this, id: id);
}
_ControlledSmallDashNestBumper.b({required String id}) : super.b() { _SmallDashNestBumper.b() : super.b();
controller = DashNestBumperController(this, id: id);
}
@override @override
int get points => 10; int get points => 20;
} }
/// {@template dash_nest_bumper_controller} class _DashNestBumperBallContactCallback
/// Controls a [DashNestBumper]. extends ContactCallback<DashNestBumper, Ball> {
/// {@endtemplate}
@visibleForTesting
class DashNestBumperController extends ComponentController<DashNestBumper>
with BlocComponent<GameBloc, GameState>, HasGameRef<PinballGame> {
/// {@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 @override
bool listenWhen(GameState? previousState, GameState newState) { void begin(DashNestBumper dashNestBumper, _, __) {
final wasActive = previousState?.activatedDashNests.contains(id) ?? false; final parent = dashNestBumper.parent;
final isActive = newState.activatedDashNests.contains(id); if (parent is FlutterForest) {
parent.controller.activateBumper(dashNestBumper);
return wasActive != isActive;
} }
@override
void onNewState(GameState state) {
super.onNewState(state);
if (state.activatedDashNests.contains(id)) {
component.activate();
} else {
component.deactivate();
}
}
/// Registers when a [DashNestBumper] is hit by a [Ball].
///
/// Triggered by [_ControlledDashNestBumperBallContactCallback].
void hit() {
gameRef.read<GameBloc>().add(DashNestActivated(id));
}
}
/// Listens when a [Ball] bounces bounces against a [DashNestBumper].
class _ControlledDashNestBumperBallContactCallback
extends ContactCallback<Controls<DashNestBumperController>, Ball> {
@override
void begin(
Controls<DashNestBumperController> controlledDashNestBumper,
Ball _,
Contact __,
) {
controlledDashNestBumper.controller.hit();
} }
} }

@ -1,8 +1,8 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template game_flow_controller} /// {@template game_flow_controller}
/// A [Component] that controls the game over and game restart logic /// A [Component] that controls the game over and game restart logic

@ -4,9 +4,9 @@ import 'dart:async';
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template google_word} /// {@template google_word}
/// Loads all [GoogleLetter]s to compose a [GoogleWord]. /// Loads all [GoogleLetter]s to compose a [GoogleWord].

@ -1,6 +1,7 @@
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/components/components.dart'; import 'package:pinball/game/components/components.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_flame/pinball_flame.dart';
/// {@template launcher} /// {@template launcher}
/// A [Blueprint] which creates the [Plunger], [RocketSpriteComponent] and /// A [Blueprint] which creates the [Plunger], [RocketSpriteComponent] and

@ -2,9 +2,9 @@ import 'dart:math';
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template score_effect_controller} /// {@template score_effect_controller}
/// A [ComponentController] responsible for adding [ScoreText]s /// A [ComponentController] responsible for adding [ScoreText]s

@ -34,10 +34,7 @@ class BallScorePointsCallback extends ContactCallback<Ball, ScorePoints> {
ScorePoints scorePoints, ScorePoints scorePoints,
Contact __, Contact __,
) { ) {
_gameRef.read<GameBloc>().add( _gameRef.read<GameBloc>().add(Scored(points: scorePoints.points));
Scored(points: scorePoints.points),
);
_gameRef.audio.score(); _gameRef.audio.score();
} }
} }

@ -3,9 +3,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template sparky_fire_zone} /// {@template sparky_fire_zone}
/// Area positioned at the top left of the [Board] where the [Ball] /// Area positioned at the top left of the [Board] where the [Ball]

@ -5,11 +5,11 @@ import 'package:flame/components.dart';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/flame/flame.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/gen/assets.gen.dart'; import 'package:pinball/gen/assets.gen.dart';
import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; 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; import 'package:pinball_theme/pinball_theme.dart' hide Assets;
class PinballGame extends Forge2DGame class PinballGame extends Forge2DGame

@ -4,6 +4,7 @@ import 'dart:math';
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Signature for the callback called when the used has /// Signature for the callback called when the used has
/// submettied their initials on the [BackboardGameOver] /// submettied their initials on the [BackboardGameOver]

@ -5,6 +5,7 @@ import 'package:flame/components.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template backboard_letter_prompt} /// {@template backboard_letter_prompt}
/// A [PositionComponent] that renders a letter prompt used /// A [PositionComponent] that renders a letter prompt used

@ -14,13 +14,18 @@ class Ball<T extends Forge2DGame> extends BodyComponent<T>
/// {@macro ball} /// {@macro ball}
Ball({ Ball({
required this.baseColor, required this.baseColor,
}) { }) : super(
children: [
_BallSpriteComponent()..tint(baseColor.withOpacity(0.5)),
],
) {
// TODO(ruimiguel): while developing Ball can be launched by clicking mouse, // 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 // 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. // 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 // 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. // bumper, it will need to explicit change layer to Layer.board then.
layer = Layer.board; layer = Layer.board;
renderBody = false;
} }
/// The size of the [Ball]. /// The size of the [Ball].
@ -32,20 +37,6 @@ class Ball<T extends Forge2DGame> extends BodyComponent<T>
double _boostTimer = 0; double _boostTimer = 0;
static const _boostDuration = 2.0; static const _boostDuration = 2.0;
final _BallSpriteComponent _spriteComponent = _BallSpriteComponent();
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(
_spriteComponent..tint(baseColor.withOpacity(0.5)),
);
renderBody = false;
}
@override @override
Body createBody() { Body createBody() {
final shape = CircleShape()..radius = size.x / 2; final shape = CircleShape()..radius = size.x / 2;
@ -117,7 +108,10 @@ class Ball<T extends Forge2DGame> extends BodyComponent<T>
((standardizedYPosition / boardHeight) * (1 - maxShrinkValue)); ((standardizedYPosition / boardHeight) * (1 - maxShrinkValue));
body.fixtures.first.shape.radius = (size.x / 2) * scaleFactor; 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() { void _setPositionalGravity() {

@ -11,7 +11,12 @@ class Baseboard extends BodyComponent with InitialPosition {
/// {@macro baseboard} /// {@macro baseboard}
Baseboard({ Baseboard({
required BoardSide side, 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. /// Whether the [Baseboard] is on the left or right side of the board.
final BoardSide _side; final BoardSide _side;
@ -79,13 +84,6 @@ class Baseboard extends BodyComponent with InitialPosition {
return fixturesDef; return fixturesDef;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_BaseboardSpriteComponent(side: _side));
}
@override @override
Body createBody() { Body createBody() {
const angle = 37.1 * (math.pi / 180); const angle = 37.1 * (math.pi / 180);

@ -3,6 +3,7 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template boundaries} /// {@template boundaries}
/// A [Blueprint] which creates the [_BottomBoundary] and [_OuterBoundary]. /// A [Blueprint] which creates the [_BottomBoundary] and [_OuterBoundary].
@ -23,7 +24,13 @@ class Boundaries extends Forge2DBlueprint {
/// {@endtemplate bottom_boundary} /// {@endtemplate bottom_boundary}
class _BottomBoundary extends BodyComponent with InitialPosition { class _BottomBoundary extends BodyComponent with InitialPosition {
/// {@macro bottom_boundary} /// {@macro bottom_boundary}
_BottomBoundary() : super(priority: RenderPriority.bottomBoundary); _BottomBoundary()
: super(
priority: RenderPriority.bottomBoundary,
children: [_BottomBoundarySpriteComponent()],
) {
renderBody = false;
}
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDefs = <FixtureDef>[]; final fixturesDefs = <FixtureDef>[];
@ -59,13 +66,6 @@ class _BottomBoundary extends BodyComponent with InitialPosition {
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_BottomBoundarySpriteComponent());
}
} }
class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef { class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef {
@ -88,7 +88,13 @@ class _BottomBoundarySpriteComponent extends SpriteComponent with HasGameRef {
/// {@endtemplate outer_boundary} /// {@endtemplate outer_boundary}
class _OuterBoundary extends BodyComponent with InitialPosition { class _OuterBoundary extends BodyComponent with InitialPosition {
/// {@macro outer_boundary} /// {@macro outer_boundary}
_OuterBoundary() : super(priority: RenderPriority.outerBoudary); _OuterBoundary()
: super(
priority: RenderPriority.outerBoudary,
children: [_OuterBoundarySpriteComponent()],
) {
renderBody = false;
}
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDefs = <FixtureDef>[]; final fixturesDefs = <FixtureDef>[];
@ -130,13 +136,6 @@ class _OuterBoundary extends BodyComponent with InitialPosition {
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_OuterBoundarySpriteComponent());
}
} }
class _OuterBoundarySpriteComponent extends SpriteComponent with HasGameRef { class _OuterBoundarySpriteComponent extends SpriteComponent with HasGameRef {

@ -19,8 +19,8 @@ export 'joint_anchor.dart';
export 'kicker.dart'; export 'kicker.dart';
export 'launch_ramp.dart'; export 'launch_ramp.dart';
export 'layer.dart'; export 'layer.dart';
export 'layer_sensor.dart';
export 'plunger.dart'; export 'plunger.dart';
export 'ramp_opening.dart';
export 'render_priority.dart'; export 'render_priority.dart';
export 'rocket.dart'; export 'rocket.dart';
export 'score_text.dart'; export 'score_text.dart';

@ -6,6 +6,7 @@ import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_flame/pinball_flame.dart';
/// {@template dinowalls} /// {@template dinowalls}
/// A [Blueprint] which creates walls for the [ChromeDino]. /// A [Blueprint] which creates walls for the [ChromeDino].
@ -28,7 +29,13 @@ class DinoWalls extends Forge2DBlueprint {
/// {@endtemplate} /// {@endtemplate}
class _DinoTopWall extends BodyComponent with InitialPosition { class _DinoTopWall extends BodyComponent with InitialPosition {
///{@macro dino_top_wall} ///{@macro dino_top_wall}
_DinoTopWall() : super(priority: RenderPriority.dinoTopWall); _DinoTopWall()
: super(
priority: RenderPriority.dinoTopWall,
children: [_DinoTopWallSpriteComponent()],
) {
renderBody = false;
}
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
@ -97,14 +104,6 @@ class _DinoTopWall extends BodyComponent with InitialPosition {
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_DinoTopWallSpriteComponent());
}
} }
class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef { class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef {
@ -125,7 +124,13 @@ class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef {
/// {@endtemplate} /// {@endtemplate}
class _DinoBottomWall extends BodyComponent with InitialPosition { class _DinoBottomWall extends BodyComponent with InitialPosition {
///{@macro dino_top_wall} ///{@macro dino_top_wall}
_DinoBottomWall() : super(priority: RenderPriority.dinoBottomWall); _DinoBottomWall()
: super(
priority: RenderPriority.dinoBottomWall,
children: [_DinoBottomWallSpriteComponent()],
) {
renderBody = false;
}
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
@ -205,14 +210,6 @@ class _DinoBottomWall extends BodyComponent with InitialPosition {
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_DinoBottomWallSpriteComponent());
}
} }
class _DinoBottomWallSpriteComponent extends SpriteComponent with HasGameRef { class _DinoBottomWallSpriteComponent extends SpriteComponent with HasGameRef {

@ -13,7 +13,11 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition {
/// {@macro flipper} /// {@macro flipper}
Flipper({ Flipper({
required this.side, required this.side,
}); }) : super(
children: [_FlipperSpriteComponent(side: side)],
) {
renderBody = false;
}
/// The size of the [Flipper]. /// The size of the [Flipper].
static final size = Vector2(13.5, 4.3); static final size = Vector2(13.5, 4.3);
@ -112,10 +116,8 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
renderBody = false;
await _anchorToJoint(); await _anchorToJoint();
await add(_FlipperSpriteComponent(side: side));
} }
@override @override

@ -7,14 +7,12 @@ import 'package:pinball_components/pinball_components.dart';
/// {@endtemplate} /// {@endtemplate}
class FlutterSignPost extends BodyComponent with InitialPosition { class FlutterSignPost extends BodyComponent with InitialPosition {
/// {@macro flutter_sign_post} /// {@macro flutter_sign_post}
FlutterSignPost() : super(priority: RenderPriority.flutterSignPost); FlutterSignPost()
: super(
@override priority: RenderPriority.flutterSignPost,
Future<void> onLoad() async { children: [_FlutterSignPostSpriteComponent()],
await super.onLoad(); ) {
renderBody = false; renderBody = false;
await add(_FlutterSignPostSpriteComponent());
} }
@override @override

@ -16,7 +16,12 @@ class Kicker extends BodyComponent with InitialPosition {
/// {@macro kicker} /// {@macro kicker}
Kicker({ Kicker({
required BoardSide side, required BoardSide side,
}) : _side = side; }) : _side = side,
super(
children: [_KickerSpriteComponent(side: side)],
) {
renderBody = false;
}
/// The size of the [Kicker] body. /// The size of the [Kicker] body.
static final Vector2 size = Vector2(4.4, 15); static final Vector2 size = Vector2(4.4, 15);
@ -120,13 +125,6 @@ class Kicker extends BodyComponent with InitialPosition {
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_KickerSpriteComponent(side: _side));
}
} }
class _KickerSpriteComponent extends SpriteComponent with HasGameRef { class _KickerSpriteComponent extends SpriteComponent with HasGameRef {

@ -5,6 +5,7 @@ import 'dart:math' as math;
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template launch_ramp} /// {@template launch_ramp}
/// A [Blueprint] which creates the [_LaunchRampBase] and /// A [Blueprint] which creates the [_LaunchRampBase] and
@ -14,7 +15,7 @@ class LaunchRamp extends Forge2DBlueprint {
@override @override
void build(_) { void build(_) {
addAllContactCallback([ addAllContactCallback([
RampOpeningBallContactCallback<_LaunchRampExit>(), LayerSensorBallContactCallback<_LaunchRampExit>(),
]); ]);
final launchRampBase = _LaunchRampBase(); final launchRampBase = _LaunchRampBase();
@ -236,10 +237,10 @@ class _LaunchRampCloseWall extends BodyComponent with InitialPosition, Layered {
} }
/// {@template launch_ramp_exit} /// {@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]. /// [LaunchRamp].
/// {@endtemplate} /// {@endtemplate}
class _LaunchRampExit extends RampOpening { class _LaunchRampExit extends LayerSensor {
/// {@macro launch_ramp_exit} /// {@macro launch_ramp_exit}
_LaunchRampExit({ _LaunchRampExit({
required double rotation, required double rotation,
@ -247,7 +248,7 @@ class _LaunchRampExit extends RampOpening {
super( super(
insideLayer: Layer.launcher, insideLayer: Layer.launcher,
outsideLayer: Layer.board, outsideLayer: Layer.board,
orientation: RampOrientation.down, orientation: LayerEntranceOrientation.down,
insidePriority: RenderPriority.ballOnLaunchRamp, insidePriority: RenderPriority.ballOnLaunchRamp,
outsidePriority: RenderPriority.ballOnBoard, outsidePriority: RenderPriority.ballOnBoard,
) { ) {

@ -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<LayerEntrance extends LayerSensor>
extends ContactCallback<Ball, LayerEntrance> {
@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();
}
}
}

@ -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<Opening extends RampOpening>
extends ContactCallback<Ball, Opening> {
/// [Ball]s currently inside the ramp.
final _ballsInside = <Ball>{};
@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);
}
}
}
}

@ -23,7 +23,7 @@ abstract class RenderPriority {
static const int ballOnSpaceship = _above + spaceshipSaucer; static const int ballOnSpaceship = _above + spaceshipSaucer;
/// Render priority for the [Ball] while it's on the [SpaceshipRail]. /// 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]. /// Render priority for the [Ball] while it's on the [LaunchRamp].
static const int ballOnLaunchRamp = _above + launchRamp; static const int ballOnLaunchRamp = _above + launchRamp;

@ -3,6 +3,7 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template slingshots} /// {@template slingshots}
/// A [Blueprint] which creates the pair of [Slingshot]s on the right side of /// 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, required String spritePath,
}) : _length = length, }) : _length = length,
_angle = angle, _angle = angle,
_spritePath = spritePath, super(
super(priority: RenderPriority.slingshot); priority: RenderPriority.slingshot,
children: [_SlinghsotSpriteComponent(spritePath, angle: angle)],
) {
renderBody = false;
}
final double _length; final double _length;
final double _angle; final double _angle;
final String _spritePath;
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
const circleRadius = 1.55; const circleRadius = 1.55;
@ -103,24 +106,25 @@ class Slingshot extends BodyComponent with InitialPosition {
return body; 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 @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
await _loadSprite(); final sprite = await gameRef.loadSprite(_path);
renderBody = false; this.sprite = sprite;
} size = sprite.originalSize / 10;
Future<void> _loadSprite() async {
final sprite = await gameRef.loadSprite(_spritePath);
await add(
SpriteComponent(
sprite: sprite,
size: sprite.originalSize / 10,
anchor: Anchor.center,
angle: -_angle,
),
);
} }
} }

@ -7,6 +7,7 @@ import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_flame/pinball_flame.dart';
/// {@template spaceship} /// {@template spaceship}
/// A [Blueprint] which creates the spaceship feature. /// A [Blueprint] which creates the spaceship feature.
@ -24,19 +25,22 @@ class Spaceship extends Forge2DBlueprint {
@override @override
void build(_) { void build(_) {
addAllContactCallback([ addAllContactCallback([
SpaceshipHoleBallContactCallback(), LayerSensorBallContactCallback<_SpaceshipEntrance>(),
SpaceshipEntranceBallContactCallback(), LayerSensorBallContactCallback<_SpaceshipHole>(),
]); ]);
addAll([ addAll([
SpaceshipSaucer()..initialPosition = position, SpaceshipSaucer()..initialPosition = position,
SpaceshipEntrance()..initialPosition = position, _SpaceshipEntrance()..initialPosition = position,
AndroidHead()..initialPosition = position, AndroidHead()..initialPosition = position,
SpaceshipHole( _SpaceshipHole(
outsideLayer: Layer.spaceshipExitRail, outsideLayer: Layer.spaceshipExitRail,
outsidePriority: RenderPriority.ballOnSpaceshipRail, outsidePriority: RenderPriority.ballOnSpaceshipRail,
)..initialPosition = position - Vector2(5.2, -4.8), )..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, SpaceshipWall()..initialPosition = position,
]); ]);
} }
@ -91,16 +95,13 @@ class SpaceshipSaucer extends BodyComponent with InitialPosition, Layered {
/// {@endtemplate} /// {@endtemplate}
class AndroidHead extends BodyComponent with InitialPosition, Layered { class AndroidHead extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_bridge} /// {@macro spaceship_bridge}
AndroidHead() : super(priority: RenderPriority.androidHead) { AndroidHead()
layer = Layer.spaceship; : super(
} priority: RenderPriority.androidHead,
children: [_AndroidHeadSpriteAnimation()],
@override ) {
Future<void> onLoad() async {
await super.onLoad();
renderBody = false; renderBody = false;
layer = Layer.spaceship;
await add(_AndroidHeadSpriteAnimation());
} }
@override @override
@ -142,17 +143,11 @@ class _AndroidHeadSpriteAnimation extends SpriteAnimationComponent
} }
} }
/// {@template spaceship_entrance} class _SpaceshipEntrance extends LayerSensor {
/// A sensor [BodyComponent] used to detect when the ball enters the _SpaceshipEntrance()
/// 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()
: super( : super(
insideLayer: Layer.spaceship, insideLayer: Layer.spaceship,
orientation: RampOrientation.up, orientation: LayerEntranceOrientation.up,
insidePriority: RenderPriority.ballOnSpaceship, insidePriority: RenderPriority.ballOnSpaceship,
) { ) {
layer = Layer.spaceship; layer = Layer.spaceship;
@ -176,17 +171,12 @@ class SpaceshipEntrance extends RampOpening {
} }
} }
/// {@template spaceship_hole} class _SpaceshipHole extends LayerSensor {
/// A sensor [BodyComponent] responsible for sending the [Ball] _SpaceshipHole({required Layer outsideLayer, required int outsidePriority})
/// out from the [Spaceship].
/// {@endtemplate}
class SpaceshipHole extends RampOpening {
/// {@macro spaceship_hole}
SpaceshipHole({Layer? outsideLayer, int? outsidePriority = 1})
: super( : super(
insideLayer: Layer.spaceship, insideLayer: Layer.spaceship,
outsideLayer: outsideLayer, outsideLayer: outsideLayer,
orientation: RampOrientation.up, orientation: LayerEntranceOrientation.down,
insidePriority: RenderPriority.ballOnSpaceship, insidePriority: RenderPriority.ballOnSpaceship,
outsidePriority: outsidePriority, outsidePriority: outsidePriority,
) { ) {
@ -258,33 +248,3 @@ class SpaceshipWall extends BodyComponent with InitialPosition, Layered {
return world.createBody(bodyDef)..createFixture(fixtureDef); 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<SpaceshipEntrance, Ball> {
@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<SpaceshipHole, Ball> {
@override
void begin(SpaceshipHole hole, Ball ball, _) {
ball
..sendTo(hole.outsidePriority)
..layer = hole.outsideLayer;
}
}

@ -6,6 +6,7 @@ import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_flame/pinball_flame.dart';
/// {@template spaceship_rail} /// {@template spaceship_rail}
/// A [Blueprint] for the spaceship drop tube. /// A [Blueprint] for the spaceship drop tube.
@ -17,11 +18,11 @@ class SpaceshipRail extends Forge2DBlueprint {
@override @override
void build(_) { void build(_) {
addAllContactCallback([ addAllContactCallback([
SpaceshipRailExitBallContactCallback(), LayerSensorBallContactCallback<_SpaceshipRailExit>(),
]); ]);
final railRamp = _SpaceshipRailRamp(); final railRamp = _SpaceshipRailRamp();
final railEnd = SpaceshipRailExit(); final railEnd = _SpaceshipRailExit();
final topBase = _SpaceshipRailBase(radius: 0.55) final topBase = _SpaceshipRailBase(radius: 0.55)
..initialPosition = Vector2(-26.15, -18.65); ..initialPosition = Vector2(-26.15, -18.65);
final bottomBase = _SpaceshipRailBase(radius: 0.8) final bottomBase = _SpaceshipRailBase(radius: 0.8)
@ -194,15 +195,10 @@ class _SpaceshipRailBase extends BodyComponent with InitialPosition {
} }
} }
/// {@template spaceship_rail_exit} class _SpaceshipRailExit extends LayerSensor {
/// A sensor [BodyComponent] responsible for sending the [Ball] _SpaceshipRailExit()
/// back to the board.
/// {@endtemplate}
class SpaceshipRailExit extends RampOpening {
/// {@macro spaceship_rail_exit}
SpaceshipRailExit()
: super( : super(
orientation: RampOrientation.down, orientation: LayerEntranceOrientation.down,
insideLayer: Layer.spaceshipExitRail, insideLayer: Layer.spaceshipExitRail,
insidePriority: RenderPriority.ballOnSpaceshipRail, 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<SpaceshipRailExit, Ball> {
@override
void begin(SpaceshipRailExit exitRail, Ball ball, _) {
ball
..sendTo(exitRail.outsidePriority)
..layer = exitRail.outsideLayer;
}
}

@ -6,6 +6,7 @@ import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/gen/assets.gen.dart'; import 'package:pinball_components/gen/assets.gen.dart';
import 'package:pinball_components/pinball_components.dart' hide Assets; import 'package:pinball_components/pinball_components.dart' hide Assets;
import 'package:pinball_flame/pinball_flame.dart';
/// {@template spaceship_ramp} /// {@template spaceship_ramp}
/// A [Blueprint] which creates the ramp leading into the [Spaceship]. /// A [Blueprint] which creates the ramp leading into the [Spaceship].
@ -17,7 +18,7 @@ class SpaceshipRamp extends Forge2DBlueprint {
@override @override
void build(_) { void build(_) {
addAllContactCallback([ addAllContactCallback([
RampOpeningBallContactCallback<_SpaceshipRampOpening>(), LayerSensorBallContactCallback<_SpaceshipRampOpening>(),
]); ]);
final rightOpening = _SpaceshipRampOpening( final rightOpening = _SpaceshipRampOpening(
@ -170,8 +171,12 @@ class _SpaceshipRampBoardOpeningSpriteComponent extends SpriteComponent
class _SpaceshipRampForegroundRailing extends BodyComponent class _SpaceshipRampForegroundRailing extends BodyComponent
with InitialPosition, Layered { with InitialPosition, Layered {
_SpaceshipRampForegroundRailing() _SpaceshipRampForegroundRailing()
: super(priority: RenderPriority.spaceshipRampForegroundRailing) { : super(
priority: RenderPriority.spaceshipRampForegroundRailing,
children: [_SpaceshipRampForegroundRailingSpriteComponent()],
) {
layer = Layer.spaceshipEntranceRamp; layer = Layer.spaceshipEntranceRamp;
renderBody = false;
} }
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
@ -222,14 +227,6 @@ class _SpaceshipRampForegroundRailing extends BodyComponent
return body; return body;
} }
@override
Future<void> onLoad() async {
await super.onLoad();
renderBody = false;
await add(_SpaceshipRampForegroundRailingSpriteComponent());
}
} }
class _SpaceshipRampForegroundRailingSpriteComponent extends SpriteComponent class _SpaceshipRampForegroundRailingSpriteComponent extends SpriteComponent
@ -277,10 +274,10 @@ class _SpaceshipRampBase extends BodyComponent with InitialPosition, Layered {
} }
/// {@template spaceship_ramp_opening} /// {@template spaceship_ramp_opening}
/// [RampOpening] with [Layer.spaceshipEntranceRamp] to filter [Ball] collisions /// [LayerSensor] with [Layer.spaceshipEntranceRamp] to filter [Ball] collisions
/// inside [_SpaceshipRampBackground]. /// inside [_SpaceshipRampBackground].
/// {@endtemplate} /// {@endtemplate}
class _SpaceshipRampOpening extends RampOpening { class _SpaceshipRampOpening extends LayerSensor {
/// {@macro spaceship_ramp_opening} /// {@macro spaceship_ramp_opening}
_SpaceshipRampOpening({ _SpaceshipRampOpening({
Layer? outsideLayer, Layer? outsideLayer,
@ -290,7 +287,7 @@ class _SpaceshipRampOpening extends RampOpening {
super( super(
insideLayer: Layer.spaceshipEntranceRamp, insideLayer: Layer.spaceshipEntranceRamp,
outsideLayer: outsideLayer, outsideLayer: outsideLayer,
orientation: RampOrientation.down, orientation: LayerEntranceOrientation.down,
insidePriority: RenderPriority.ballOnSpaceshipRamp, insidePriority: RenderPriority.ballOnSpaceshipRamp,
outsidePriority: outsidePriority, outsidePriority: outsidePriority,
) { ) {

@ -3,6 +3,7 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template sparky_computer} /// {@template sparky_computer}
/// A [Blueprint] which creates the [_ComputerBase] and /// A [Blueprint] which creates the [_ComputerBase] and

@ -1,3 +0,0 @@
export 'blueprint.dart';
export 'keyboard_input_controller.dart';
export 'priority.dart';

@ -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();
}
}
}

@ -1,3 +1,2 @@
export 'components/components.dart'; export 'components/components.dart';
export 'extensions/extensions.dart'; export 'extensions/extensions.dart';
export 'flame/flame.dart';

@ -14,6 +14,8 @@ dependencies:
geometry: geometry:
path: ../geometry path: ../geometry
intl: ^0.17.0 intl: ^0.17.0
pinball_flame:
path: ../pinball_flame
dev_dependencies: dev_dependencies:

@ -1,5 +1,6 @@
import 'package:flame/extensions.dart'; import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/common/common.dart'; import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart';

@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart';
class LaunchRampGame extends BasicBallGame { class LaunchRampGame extends BasicBallGame {

@ -1,5 +1,6 @@
import 'package:flame/extensions.dart'; import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/common/common.dart'; import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart';

@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/common/common.dart'; import 'package:sandbox/common/common.dart';
class BasicSpaceshipGame extends BasicGame with TapDetector { class BasicSpaceshipGame extends BasicGame with TapDetector {

@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SpaceshipRailGame extends BasicBallGame { class SpaceshipRailGame extends BasicBallGame {

@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart'; import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SpaceshipRampGame extends BasicBallGame { class SpaceshipRampGame extends BasicBallGame {

@ -240,6 +240,13 @@ packages:
relative: true relative: true
source: path source: path
version: "1.0.0+1" version: "1.0.0+1"
pinball_flame:
dependency: "direct main"
description:
path: "../../pinball_flame"
relative: true
source: path
version: "1.0.0+1"
platform: platform:
dependency: transitive dependency: transitive
description: description:

@ -14,6 +14,8 @@ dependencies:
sdk: flutter sdk: flutter
pinball_components: pinball_components:
path: ../ path: ../
pinball_flame:
path: ../../pinball_flame
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

@ -13,12 +13,6 @@ class MockBall extends Mock implements Ball {}
class MockGame extends Mock implements Forge2DGame {} 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 MockContact extends Mock implements Contact {}
class MockContactCallback extends Mock class MockContactCallback extends Mock

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
@ -17,6 +18,7 @@ void main() {
await game.addFromBlueprint(Boundaries()); await game.addFromBlueprint(Boundaries());
game.camera.followVector2(Vector2.zero()); game.camera.followVector2(Vector2.zero());
game.camera.zoom = 3.9; game.camera.zoom = 3.9;
await game.ready();
}, },
verify: (game, tester) async { verify: (game, tester) async {
await expectLater( await expectLater(

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
@ -18,6 +19,7 @@ void main() {
await game.addFromBlueprint(DinoWalls()); await game.addFromBlueprint(DinoWalls());
game.camera.followVector2(Vector2.zero()); game.camera.followVector2(Vector2.zero());
game.camera.zoom = 6.5; game.camera.zoom = 6.5;
await game.ready();
}, },
verify: (game, tester) async { verify: (game, tester) async {
await expectLater( await expectLater(

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.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<TestLayerSensor> {
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<Fixture>());
},
);
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);
});
});
}

@ -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<TestRampOpening> {
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<Fixture>());
},
);
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);
});
});
}

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
@ -19,6 +20,7 @@ void main() {
setUp: (game, tester) async { setUp: (game, tester) async {
await game.addFromBlueprint(Slingshots()); await game.addFromBlueprint(Slingshots());
game.camera.followVector2(Vector2.zero()); game.camera.followVector2(Vector2.zero());
await game.ready();
}, },
verify: (game, tester) async { verify: (game, tester) async {
await expectLater( await expectLater(

@ -3,8 +3,8 @@
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.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);
});
});
} }

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
@ -16,6 +17,7 @@ void main() {
setUp: (game, tester) async { setUp: (game, tester) async {
await game.addFromBlueprint(SpaceshipRamp()); await game.addFromBlueprint(SpaceshipRamp());
game.camera.followVector2(Vector2(-13, -50)); game.camera.followVector2(Vector2(-13, -50));
await game.ready();
}, },
verify: (game, tester) async { verify: (game, tester) async {
await expectLater( await expectLater(

@ -5,6 +5,7 @@ import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart'; import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
@ -14,8 +15,6 @@ void main() {
late Fixture fixture; late Fixture fixture;
late Body body; late Body body;
late Ball ball; late Ball ball;
late SpaceshipEntrance entrance;
late SpaceshipHole hole;
late Forge2DGame game; late Forge2DGame game;
setUp(() { setUp(() {
@ -32,9 +31,6 @@ void main() {
ball = MockBall(); ball = MockBall();
when(() => ball.gameRef).thenReturn(game); when(() => ball.gameRef).thenReturn(game);
when(() => ball.body).thenReturn(body); when(() => ball.body).thenReturn(body);
entrance = MockSpaceshipEntrance();
hole = MockSpaceshipHole();
}); });
group('Spaceship', () { group('Spaceship', () {
@ -46,6 +42,7 @@ void main() {
final position = Vector2(30, -30); final position = Vector2(30, -30);
await game.addFromBlueprint(Spaceship(position: position)); await game.addFromBlueprint(Spaceship(position: position));
game.camera.followVector2(position); game.camera.followVector2(position);
await game.ready();
}, },
verify: (game, tester) async { verify: (game, tester) async {
await expectLater( 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);
});
});
}); });
} }

@ -4,6 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';

@ -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);
},
);
});
});
}

@ -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

@ -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

@ -0,0 +1 @@
include: package:very_good_analysis/analysis_options.2.4.0.yaml

@ -0,0 +1,5 @@
library pinball_flame;
export 'src/blueprint.dart';
export 'src/component_controller.dart';
export 'src/keyboard_input_controller.dart';

@ -1,12 +1,9 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
/// {@template component_controller} /// {@template component_controller}
/// A [ComponentController] is a [Component] in charge of handling the logic /// A [ComponentController] is a [Component] in charge of handling the logic
/// associated with another [Component]. /// associated with another [Component].
///
/// [ComponentController]s usually implement [BlocComponent].
/// {@endtemplate} /// {@endtemplate}
abstract class ComponentController<T extends Component> extends Component { abstract class ComponentController<T extends Component> extends Component {
/// {@macro component_controller} /// {@macro component_controller}

@ -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

@ -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<dynamic, dynamic> {}
class MockComponent extends Mock implements Component {}

@ -1,9 +1,12 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/contact_callbacks.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.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<dynamic, dynamic> {}
class MyBlueprint extends Blueprint { class MyBlueprint extends Blueprint {
@override @override
@ -51,19 +54,19 @@ void main() {
}); });
test('components can be added to it', () { test('components can be added to it', () {
final blueprint = MyBlueprint()..build(MockGame()); final blueprint = MyBlueprint()..build(MockForge2DGame());
expect(blueprint.components.length, equals(3)); expect(blueprint.components.length, equals(3));
}); });
test('blueprints can be added to it', () { test('blueprints can be added to it', () {
final blueprint = MyComposedBlueprint()..build(MockGame()); final blueprint = MyComposedBlueprint()..build(MockForge2DGame());
expect(blueprint.blueprints.length, equals(3)); expect(blueprint.blueprints.length, equals(3));
}); });
test('adds the components to a game on attach', () { test('adds the components to a game on attach', () {
final mockGame = MockGame(); final mockGame = MockForge2DGame();
when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addAll(any())).thenAnswer((_) async {});
MyBlueprint().attach(mockGame); MyBlueprint().attach(mockGame);
@ -71,7 +74,7 @@ void main() {
}); });
test('adds components from a child Blueprint the to a game on attach', () { 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 {}); when(() => mockGame.addAll(any())).thenAnswer((_) async {});
MyComposedBlueprint().attach(mockGame); MyComposedBlueprint().attach(mockGame);
@ -81,7 +84,7 @@ void main() {
test( test(
'throws assertion error when adding to an already attached blueprint', 'throws assertion error when adding to an already attached blueprint',
() async { () async {
final mockGame = MockGame(); final mockGame = MockForge2DGame();
when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addAll(any())).thenAnswer((_) async {});
final blueprint = MyBlueprint(); final blueprint = MyBlueprint();
await blueprint.attach(mockGame); await blueprint.attach(mockGame);
@ -94,17 +97,17 @@ void main() {
group('Forge2DBlueprint', () { group('Forge2DBlueprint', () {
setUpAll(() { setUpAll(() {
registerFallbackValue(SpaceshipHoleBallContactCallback()); registerFallbackValue(TestContactCallback());
}); });
test('callbacks can be added to it', () { test('callbacks can be added to it', () {
final blueprint = MyForge2dBlueprint()..build(MockGame()); final blueprint = MyForge2dBlueprint()..build(MockForge2DGame());
expect(blueprint.callbacks.length, equals(3)); expect(blueprint.callbacks.length, equals(3));
}); });
test('adds the callbacks to a game on attach', () async { test('adds the callbacks to a game on attach', () async {
final mockGame = MockGame(); final mockGame = MockForge2DGame();
when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addAll(any())).thenAnswer((_) async {});
when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {}); when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {});
await MyForge2dBlueprint().attach(mockGame); await MyForge2dBlueprint().attach(mockGame);
@ -115,7 +118,7 @@ void main() {
test( test(
'throws assertion error when adding to an already attached blueprint', 'throws assertion error when adding to an already attached blueprint',
() async { () async {
final mockGame = MockGame(); final mockGame = MockForge2DGame();
when(() => mockGame.addAll(any())).thenAnswer((_) async {}); when(() => mockGame.addAll(any())).thenAnswer((_) async {});
when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {}); when(() => mockGame.addContactCallback(any())).thenAnswer((_) async {});
final blueprint = MyForge2dBlueprint(); final blueprint = MyForge2dBlueprint();

@ -4,7 +4,7 @@ import 'package:flame/game.dart';
import 'package:flame/src/components/component.dart'; import 'package:flame/src/components/component.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_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 { class TestComponentController extends ComponentController {
TestComponentController(Component component) : super(component); TestComponentController(Component component) : super(component);

@ -4,7 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart'; import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart'; import 'package:pinball_flame/pinball_flame.dart';
abstract class _KeyCallStub { abstract class _KeyCallStub {
bool onCall(); bool onCall();

@ -483,6 +483,13 @@ packages:
relative: true relative: true
source: path source: path
version: "1.0.0+1" 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: pinball_theme:
dependency: "direct main" dependency: "direct main"
description: description:

@ -27,6 +27,8 @@ dependencies:
path: packages/pinball_audio path: packages/pinball_audio
pinball_components: pinball_components:
path: packages/pinball_components path: packages/pinball_components
pinball_flame:
path: packages/pinball_flame
pinball_theme: pinball_theme:
path: packages/pinball_theme path: packages/pinball_theme

@ -21,7 +21,6 @@ void main() {
const GameState( const GameState(
score: 0, score: 0,
balls: 2, balls: 2,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
], ],
@ -40,13 +39,11 @@ void main() {
const GameState( const GameState(
score: 2, score: 2,
balls: 3, balls: 3,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
const GameState( const GameState(
score: 5, score: 5,
balls: 3, balls: 3,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
], ],
@ -66,56 +63,22 @@ void main() {
const GameState( const GameState(
score: 0, score: 0,
balls: 2, balls: 2,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
const GameState( const GameState(
score: 0, score: 0,
balls: 1, balls: 1,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
const GameState( const GameState(
score: 0, score: 0,
balls: 0, balls: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
], ],
); );
}); });
group('DashNestActivated', () {
blocTest<GameBloc, GameState>(
'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( group(
'BonusActivated', 'BonusActivated',
() { () {
@ -129,13 +92,11 @@ void main() {
GameState( GameState(
score: 0, score: 0,
balls: 3, balls: 3,
activatedDashNests: {},
bonusHistory: [GameBonus.googleWord], bonusHistory: [GameBonus.googleWord],
), ),
GameState( GameState(
score: 0, score: 0,
balls: 3, balls: 3,
activatedDashNests: {},
bonusHistory: [GameBonus.googleWord, GameBonus.dashNest], bonusHistory: [GameBonus.googleWord, GameBonus.dashNest],
), ),
], ],
@ -152,7 +113,6 @@ void main() {
GameState( GameState(
score: 0, score: 0,
balls: 3, balls: 3,
activatedDashNests: {},
bonusHistory: [GameBonus.sparkyTurboCharge], bonusHistory: [GameBonus.sparkyTurboCharge],
), ),
], ],

@ -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', () { group('SparkyTurboChargeActivated', () {
test('can be instantiated', () { test('can be instantiated', () {
expect(const SparkyTurboChargeActivated(), isNotNull); expect(const SparkyTurboChargeActivated(), isNotNull);

@ -10,14 +10,12 @@ void main() {
GameState( GameState(
score: 0, score: 0,
balls: 0, balls: 0,
activatedDashNests: const {},
bonusHistory: const [], bonusHistory: const [],
), ),
equals( equals(
const GameState( const GameState(
score: 0, score: 0,
balls: 0, balls: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
), ),
@ -30,7 +28,6 @@ void main() {
const GameState( const GameState(
score: 0, score: 0,
balls: 0, balls: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
), ),
isNotNull, isNotNull,
@ -46,7 +43,6 @@ void main() {
() => GameState( () => GameState(
balls: -1, balls: -1,
score: 0, score: 0,
activatedDashNests: const {},
bonusHistory: const [], bonusHistory: const [],
), ),
throwsAssertionError, throwsAssertionError,
@ -62,7 +58,6 @@ void main() {
() => GameState( () => GameState(
balls: 0, balls: 0,
score: -1, score: -1,
activatedDashNests: const {},
bonusHistory: const [], bonusHistory: const [],
), ),
throwsAssertionError, throwsAssertionError,
@ -77,7 +72,6 @@ void main() {
const gameState = GameState( const gameState = GameState(
balls: 0, balls: 0,
score: 0, score: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );
expect(gameState.isGameOver, isTrue); expect(gameState.isGameOver, isTrue);
@ -89,7 +83,6 @@ void main() {
const gameState = GameState( const gameState = GameState(
balls: 1, balls: 1,
score: 0, score: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );
expect(gameState.isGameOver, isFalse); expect(gameState.isGameOver, isFalse);
@ -104,7 +97,6 @@ void main() {
const gameState = GameState( const gameState = GameState(
balls: 0, balls: 0,
score: 2, score: 2,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );
expect( expect(
@ -121,7 +113,6 @@ void main() {
const gameState = GameState( const gameState = GameState(
balls: 0, balls: 0,
score: 2, score: 2,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );
expect( expect(
@ -138,13 +129,11 @@ void main() {
const gameState = GameState( const gameState = GameState(
score: 2, score: 2,
balls: 0, balls: 0,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );
final otherGameState = GameState( final otherGameState = GameState(
score: gameState.score + 1, score: gameState.score + 1,
balls: gameState.balls + 1, balls: gameState.balls + 1,
activatedDashNests: const {'1'},
bonusHistory: const [GameBonus.googleWord], bonusHistory: const [GameBonus.googleWord],
); );
expect(gameState, isNot(equals(otherGameState))); expect(gameState, isNot(equals(otherGameState)));
@ -153,7 +142,6 @@ void main() {
gameState.copyWith( gameState.copyWith(
score: otherGameState.score, score: otherGameState.score,
balls: otherGameState.balls, balls: otherGameState.balls,
activatedDashNests: otherGameState.activatedDashNests,
bonusHistory: otherGameState.bonusHistory, bonusHistory: otherGameState.bonusHistory,
), ),
equals(otherGameState), equals(otherGameState),

@ -21,7 +21,6 @@ void main() {
score: 0, score: 0,
balls: 0, balls: 0,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
); );
whenListen(bloc, Stream.value(state), initialState: state); whenListen(bloc, Stream.value(state), initialState: state);
return bloc; return bloc;

@ -22,7 +22,6 @@ void main() {
score: 0, score: 0,
balls: 0, balls: 0,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
); );
whenListen(bloc, Stream.value(state), initialState: state); whenListen(bloc, Stream.value(state), initialState: state);
return bloc; return bloc;

@ -79,105 +79,21 @@ void main() {
); );
}); });
group('controller', () {
group('listenWhen', () {
final gameBloc = MockGameBloc();
final flameBlocTester = FlameBlocTester<TestGame, GameBloc>(
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<Ball>().length;
flutterForest.controller.onNewState(MockGameState());
await Future<void>.delayed(const Duration(milliseconds: 700));
await game.ready();
expect(
game.descendants().whereType<Ball>().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<DashAnimatronic>().single;
expect(dashAnimatronic.playing, isTrue);
},
);
group('bumpers', () { group('bumpers', () {
late Ball ball; late Ball ball;
late GameBloc gameBloc; late GameBloc gameBloc;
setUp(() { setUp(() {
ball = Ball(baseColor: const Color(0xFF00FFFF)); ball = Ball(baseColor: const Color(0xFF00FFFF));
gameBloc = MockGameBloc();
whenListen(
gameBloc,
const Stream<GameState>.empty(),
initialState: const GameState.initial(),
);
}); });
final flameBlocTester = FlameBlocTester<PinballGame, GameBloc>( final flameBlocTester = FlameBlocTester<PinballGame, GameBloc>(
gameBuilder: EmptyPinballTestGame.new, gameBuilder: EmptyPinballTestGame.new,
blocBuilder: () => gameBloc, blocBuilder: () {
); gameBloc = MockGameBloc();
const state = GameState.initial();
flameBlocTester.testGameWidget( whenListen(gameBloc, Stream.value(state), initialState: state);
'add DashNestActivated event', return gameBloc;
setUp: (game, tester) async {
final flutterForest = FlutterForest();
await game.ensureAdd(flutterForest);
await game.ensureAdd(ball);
final bumpers =
flutterForest.descendants().whereType<DashNestBumper>();
for (final bumper in bumpers) {
beginContact(game, bumper, ball);
final controller = bumper.firstChild<DashNestBumperController>()!;
verify(
() => gameBloc.add(DashNestActivated(controller.id)),
).called(1);
}
}, },
); );
@ -185,8 +101,10 @@ void main() {
'add Scored event', 'add Scored event',
setUp: (game, tester) async { setUp: (game, tester) async {
final flutterForest = FlutterForest(); final flutterForest = FlutterForest();
await game.ensureAdd(flutterForest); await game.ensureAddAll([
await game.ensureAdd(ball); flutterForest,
ball,
]);
game.addContactCallback(BallScorePointsCallback(game)); game.addContactCallback(BallScorePointsCallback(game));
final bumpers = flutterForest.descendants().whereType<ScorePoints>(); final bumpers = flutterForest.descendants().whereType<ScorePoints>();
@ -201,122 +119,58 @@ void main() {
} }
}, },
); );
});
});
group('DashNestBumperController', () { flameBlocTester.testGameWidget(
late DashNestBumper dashNestBumper; 'adds GameBonus.dashNest to the game when 3 bumpers are activated',
setUp: (game, _) async {
setUp(() { final ball = Ball(baseColor: const Color(0xFFFF0000));
dashNestBumper = MockDashNestBumper(); final flutterForest = FlutterForest();
}); await game.ensureAddAll([flutterForest, ball]);
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); final bumpers = flutterForest.children.whereType<DashNestBumper>();
}); expect(bumpers.length, equals(3));
for (final bumper in bumpers) {
beginContact(game, bumper, ball);
await game.ready();
test("doesn't listen when the id still in activatedDashNests", () { if (bumper == bumpers.last) {
const id = ''; verify(
final controller = DashNestBumperController( () => gameBloc.add(const BonusActivated(GameBonus.dashNest)),
dashNestBumper, ).called(1);
id: id, } else {
verifyNever(
() => gameBloc.add(const BonusActivated(GameBonus.dashNest)),
); );
}
when(() => previousState.activatedDashNests).thenReturn({id}); }
when(() => newState.activatedDashNests).thenReturn({id});
expect(controller.listenWhen(previousState, newState), isFalse);
});
}, },
); );
group( flameBlocTester.testGameWidget(
'onNewState', 'deactivates bumpers when 3 are active',
() { setUp: (game, _) async {
late GameState state; final ball = Ball(baseColor: const Color(0xFFFF0000));
final flutterForest = FlutterForest();
setUp(() { await game.ensureAddAll([flutterForest, ball]);
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);
verify(() => dashNestBumper.activate()).called(1);
},
);
test( final bumpers = [
'deactivates the bumper when id not in activatedDashNests', MockDashNestBumper(),
() { MockDashNestBumper(),
final controller = DashNestBumperController( MockDashNestBumper(),
dashNestBumper, ];
id: '',
);
when(() => state.activatedDashNests).thenReturn({}); for (final bumper in bumpers) {
controller.onNewState(state); flutterForest.controller.activateBumper(bumper);
await game.ready();
verify(() => dashNestBumper.deactivate()).called(1); if (bumper == bumpers.last) {
}, for (final bumper in bumpers) {
); verify(bumper.deactivate).called(1);
}
}
}
}, },
); );
}); });
});
} }

@ -16,7 +16,6 @@ void main() {
score: 10, score: 10,
balls: 0, balls: 0,
bonusHistory: const [], bonusHistory: const [],
activatedDashNests: const {},
); );
final previous = GameState.initial(); final previous = GameState.initial();
@ -66,7 +65,6 @@ void main() {
score: 10, score: 10,
balls: 0, balls: 0,
bonusHistory: const [], bonusHistory: const [],
activatedDashNests: const {},
), ),
); );

@ -31,7 +31,6 @@ void main() {
score: 10, score: 10,
balls: 3, balls: 3,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
); );
expect(controller.listenWhen(previous, current), isTrue); expect(controller.listenWhen(previous, current), isTrue);
}); });
@ -44,7 +43,6 @@ void main() {
score: 10, score: 10,
balls: 3, balls: 3,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
); );
expect(controller.listenWhen(null, current), isTrue); expect(controller.listenWhen(null, current), isTrue);
}, },
@ -69,7 +67,6 @@ void main() {
score: 10, score: 10,
balls: 3, balls: 3,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
); );
controller.onNewState(state); controller.onNewState(state);
@ -87,7 +84,6 @@ void main() {
score: 10, score: 10,
balls: 3, balls: 3,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
), ),
); );
@ -96,7 +92,6 @@ void main() {
score: 14, score: 14,
balls: 3, balls: 3,
bonusHistory: [], bonusHistory: [],
activatedDashNests: {},
), ),
); );

@ -12,7 +12,6 @@ void main() {
const initialState = GameState( const initialState = GameState(
score: 10, score: 10,
balls: 2, balls: 2,
activatedDashNests: {},
bonusHistory: [], bonusHistory: [],
); );

@ -31,11 +31,6 @@ class MockContact extends Mock implements Contact {}
class MockContactCallback extends Mock class MockContactCallback extends Mock
implements ContactCallback<Object, Object> {} implements ContactCallback<Object, Object> {}
class MockRampOpening extends Mock implements RampOpening {}
class MockRampOpeningBallContactCallback extends Mock
implements RampOpeningBallContactCallback {}
class MockGameBloc extends Mock implements GameBloc {} class MockGameBloc extends Mock implements GameBloc {}
class MockGameState extends Mock implements GameState {} class MockGameState extends Mock implements GameState {}

Loading…
Cancel
Save