Merge branch 'main' into refactor/bumper-animation-logic

pull/204/head
Allison Ryan 3 years ago
commit 7a9befc48f

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 MiB

After

Width:  |  Height:  |  Size: 2.2 MiB

@ -11,8 +11,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/landing/landing.dart'; import 'package:pinball/theme/theme.dart';
import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_audio/pinball_audio.dart';
class App extends StatelessWidget { class App extends StatelessWidget {
@ -34,20 +35,17 @@ class App extends StatelessWidget {
RepositoryProvider.value(value: _leaderboardRepository), RepositoryProvider.value(value: _leaderboardRepository),
RepositoryProvider.value(value: _pinballAudio), RepositoryProvider.value(value: _pinballAudio),
], ],
child: MaterialApp( child: BlocProvider(
title: 'I/O Pinball', create: (context) => ThemeCubit(),
theme: ThemeData( child: const MaterialApp(
appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)), title: 'I/O Pinball',
colorScheme: ColorScheme.fromSwatch( localizationsDelegates: [
accentColor: const Color(0xFF13B9FF), AppLocalizations.delegate,
), GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: PinballGamePage(),
), ),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
home: const LandingPage(),
), ),
); );
} }

@ -42,7 +42,7 @@ class Board extends Component {
// TODO(alestiago): Consider renaming once entire Board is defined. // TODO(alestiago): Consider renaming once entire Board is defined.
class _BottomGroup extends Component { class _BottomGroup extends Component {
/// {@macro bottom_group} /// {@macro bottom_group}
_BottomGroup(); _BottomGroup() : super(priority: RenderPriority.bottomGroup);
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

@ -18,7 +18,7 @@ class ControlledBall extends Ball with Controls<BallController> {
required PinballTheme theme, required PinballTheme theme,
}) : super(baseColor: theme.characterTheme.ballColor) { }) : super(baseColor: theme.characterTheme.ballColor) {
controller = BallController(this); controller = BallController(this);
priority = Ball.launchRampPriority; priority = RenderPriority.ballOnLaunchRamp;
layer = Layer.launcher; layer = Layer.launcher;
} }
@ -31,13 +31,13 @@ class ControlledBall extends Ball with Controls<BallController> {
required PinballTheme theme, required PinballTheme theme,
}) : super(baseColor: theme.characterTheme.ballColor) { }) : super(baseColor: theme.characterTheme.ballColor) {
controller = BallController(this); controller = BallController(this);
priority = Ball.boardPriority; priority = RenderPriority.ballOnBoard;
} }
/// [Ball] used in [DebugPinballGame]. /// [Ball] used in [DebugPinballGame].
ControlledBall.debug() : super(baseColor: const Color(0xFFFF0000)) { ControlledBall.debug() : super(baseColor: const Color(0xFFFF0000)) {
controller = DebugBallController(this); controller = DebugBallController(this);
priority = Ball.boardPriority; priority = RenderPriority.ballOnBoard;
} }
} }

@ -16,8 +16,8 @@ class Launcher extends Forge2DBlueprint {
@override @override
void build(Forge2DGame gameRef) { void build(Forge2DGame gameRef) {
plunger = ControlledPlunger(compressionDistance: 12.3) plunger = ControlledPlunger(compressionDistance: 14)
..initialPosition = Vector2(40.1, 38); ..initialPosition = Vector2(40.7, 38);
final _rocket = RocketSpriteComponent()..position = Vector2(43, 62); final _rocket = RocketSpriteComponent()..position = Vector2(43, 62);

@ -5,6 +5,7 @@ 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:flutter/material.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';
@ -28,6 +29,9 @@ class PinballGame extends Forge2DGame
/// Identifier of the play button overlay /// Identifier of the play button overlay
static const playButtonOverlay = 'play_button'; static const playButtonOverlay = 'play_button';
@override
Color backgroundColor() => Colors.transparent;
final PinballTheme theme; final PinballTheme theme;
final PinballAudio audio; final PinballAudio audio;
@ -164,7 +168,7 @@ class DebugPinballGame extends PinballGame with TapDetector {
anchor: Anchor.center, anchor: Anchor.center,
) )
..position = Vector2(0, -7.8) ..position = Vector2(0, -7.8)
..priority = -4; ..priority = RenderPriority.background;
await add(spriteComponent); await add(spriteComponent);
} }

@ -5,45 +5,25 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball/theme/theme.dart';
import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_theme/pinball_theme.dart';
class PinballGamePage extends StatelessWidget { class PinballGamePage extends StatelessWidget {
const PinballGamePage({ const PinballGamePage({
Key? key, Key? key,
required this.theme, this.isDebugMode = kDebugMode,
required this.game,
}) : super(key: key); }) : super(key: key);
final PinballTheme theme; final bool isDebugMode;
final PinballGame game;
static Route route({ static Route route({
required PinballTheme theme,
bool isDebugMode = kDebugMode, bool isDebugMode = kDebugMode,
}) { }) {
return MaterialPageRoute<void>( return MaterialPageRoute<void>(
builder: (context) { builder: (context) {
final audio = context.read<PinballAudio>(); return PinballGamePage(
isDebugMode: isDebugMode,
final game = isDebugMode
? DebugPinballGame(theme: theme, audio: audio)
: PinballGame(theme: theme, audio: audio);
final pinballAudio = context.read<PinballAudio>();
final loadables = [
...game.preLoadAssets(),
pinballAudio.load(),
];
return MultiBlocProvider(
providers: [
BlocProvider(create: (_) => GameBloc()),
BlocProvider(
create: (_) => AssetsManagerCubit(loadables)..load(),
),
],
child: PinballGamePage(theme: theme, game: game),
); );
}, },
); );
@ -51,7 +31,29 @@ class PinballGamePage extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return PinballGameView(game: game); final theme = context.read<ThemeCubit>().state.theme;
final audio = context.read<PinballAudio>();
final pinballAudio = context.read<PinballAudio>();
final game = isDebugMode
? DebugPinballGame(theme: theme, audio: audio)
: PinballGame(theme: theme, audio: audio);
final loadables = [
...game.preLoadAssets(),
pinballAudio.load(),
];
return MultiBlocProvider(
providers: [
BlocProvider(create: (_) => StartGameBloc(game: game)),
BlocProvider(create: (_) => GameBloc()),
BlocProvider(
create: (_) => AssetsManagerCubit(loadables)..load(),
),
],
child: PinballGameView(game: game),
);
} }
} }
@ -65,18 +67,51 @@ class PinballGameView extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final loadingProgress = context.watch<AssetsManagerCubit>().state.progress; final isLoading = context.select(
(AssetsManagerCubit bloc) => bloc.state.progress != 1,
);
if (loadingProgress != 1) { return Scaffold(
return Scaffold( backgroundColor: Colors.blue,
body: Center( body: isLoading
child: Text( ? const _PinballGameLoadingView()
loadingProgress.toString(), : PinballGameLoadedView(game: game),
), );
}
}
class _PinballGameLoadingView extends StatelessWidget {
const _PinballGameLoadingView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final loadingProgress = context.select(
(AssetsManagerCubit bloc) => bloc.state.progress,
);
return Padding(
padding: const EdgeInsets.all(24),
child: Center(
child: LinearProgressIndicator(
color: Colors.white,
value: loadingProgress,
), ),
); ),
} );
}
}
@visibleForTesting
class PinballGameLoadedView extends StatelessWidget {
const PinballGameLoadedView({
Key? key,
required this.game,
}) : super(key: key);
final PinballGame game;
@override
Widget build(BuildContext context) {
return Stack( return Stack(
children: [ children: [
Positioned.fill( Positioned.fill(

@ -1,6 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/game/pinball_game.dart'; import 'package:pinball/game/pinball_game.dart';
import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/theme/theme.dart';
/// {@template play_button_overlay} /// {@template play_button_overlay}
/// [Widget] that renders the button responsible to starting the game /// [Widget] that renders the button responsible to starting the game
@ -18,9 +19,27 @@ class PlayButtonOverlay extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final l10n = context.l10n; final l10n = context.l10n;
return Center( return Center(
child: ElevatedButton( child: ElevatedButton(
onPressed: _game.gameFlowController.start, onPressed: () {
_game.gameFlowController.start();
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) {
final height = MediaQuery.of(context).size.height * 0.5;
return Center(
child: SizedBox(
height: height,
width: height * 1.4,
child: const CharacterSelectionDialog(),
),
);
},
);
},
child: Text(l10n.play), child: Text(l10n.play),
), ),
); );

@ -1 +0,0 @@
export 'view/landing_page.dart';

@ -69,7 +69,7 @@ class LeaderboardView extends StatelessWidget {
const SizedBox(height: 20), const SizedBox(height: 20),
TextButton( TextButton(
onPressed: () => Navigator.of(context).push<void>( onPressed: () => Navigator.of(context).push<void>(
CharacterSelectionPage.route(), CharacterSelectionDialog.route(),
), ),
child: Text(l10n.retry), child: Text(l10n.retry),
), ),

@ -1 +1,2 @@
export 'bloc/start_game_bloc.dart'; export 'bloc/start_game_bloc.dart';
export 'widgets/widgets.dart';

@ -2,42 +2,9 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/theme/theme.dart';
class LandingPage extends StatelessWidget { class HowToPlayDialog extends StatelessWidget {
const LandingPage({Key? key}) : super(key: key); const HowToPlayDialog({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () => Navigator.of(context).push<void>(
CharacterSelectionPage.route(),
),
child: Text(l10n.play),
),
TextButton(
onPressed: () => showDialog<void>(
context: context,
builder: (_) => const _HowToPlayDialog(),
),
child: Text(l10n.howToPlay),
),
],
),
),
);
}
}
class _HowToPlayDialog extends StatelessWidget {
const _HowToPlayDialog({Key? key}) : super(key: key);
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {

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

@ -2,17 +2,17 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/l10n/l10n.dart'; import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball/theme/theme.dart'; import 'package:pinball/theme/theme.dart';
import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball_theme/pinball_theme.dart';
class CharacterSelectionPage extends StatelessWidget { class CharacterSelectionDialog extends StatelessWidget {
const CharacterSelectionPage({Key? key}) : super(key: key); const CharacterSelectionDialog({Key? key}) : super(key: key);
static Route route() { static Route route() {
return MaterialPageRoute<void>( return MaterialPageRoute<void>(
builder: (_) => const CharacterSelectionPage(), builder: (_) => const CharacterSelectionDialog(),
); );
} }
@ -46,11 +46,13 @@ class CharacterSelectionView extends StatelessWidget {
const _CharacterSelectionGridView(), const _CharacterSelectionGridView(),
const SizedBox(height: 20), const SizedBox(height: 20),
TextButton( TextButton(
onPressed: () => Navigator.of(context).push<void>( onPressed: () {
PinballGamePage.route( Navigator.of(context).pop();
theme: context.read<ThemeCubit>().state.theme, showDialog<void>(
), context: context,
), builder: (_) => const HowToPlayDialog(),
);
},
child: Text(l10n.start), child: Text(l10n.start),
), ),
], ],

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 290 KiB

@ -18,6 +18,7 @@ class AlienBumper extends BodyComponent with InitialPosition {
}) : _majorRadius = majorRadius, }) : _majorRadius = majorRadius,
_minorRadius = minorRadius, _minorRadius = minorRadius,
super( super(
priority: RenderPriority.alienBumper,
children: [ children: [
_AlienBumperSpriteGroupComponent( _AlienBumperSpriteGroupComponent(
onAssetPath: onAssetPath, onAssetPath: onAssetPath,

@ -29,21 +29,6 @@ class Ball<T extends Forge2DGame> extends BodyComponent<T>
renderBody = false; renderBody = false;
} }
/// Render priority for the [Ball] while it's on the board.
static const int boardPriority = 0;
/// Render priority for the [Ball] while it's on the [SpaceshipRamp].
static const int spaceshipRampPriority = 4;
/// Render priority for the [Ball] while it's on the [Spaceship].
static const int spaceshipPriority = 4;
/// Render priority for the [Ball] while it's on the [SpaceshipRail].
static const int spaceshipRailPriority = 2;
/// Render priority for the [Ball] while it's on the [LaunchRamp].
static const int launchRampPriority = -2;
/// The size of the [Ball]. /// The size of the [Ball].
static final Vector2 size = Vector2.all(4.13); static final Vector2 size = Vector2.all(4.13);
@ -152,7 +137,7 @@ class _TurboChargeSpriteAnimationComponent extends SpriteAnimationComponent
_TurboChargeSpriteAnimationComponent() _TurboChargeSpriteAnimationComponent()
: super( : super(
anchor: const Anchor(0.53, 0.72), anchor: const Anchor(0.53, 0.72),
priority: Ball.boardPriority + 1, priority: RenderPriority.turboChargeFlame,
removeOnFinish: true, removeOnFinish: true,
); );

@ -26,8 +26,7 @@ class _BottomBoundary extends BodyComponent with InitialPosition {
/// {@macro bottom_boundary} /// {@macro bottom_boundary}
_BottomBoundary() _BottomBoundary()
: super( : super(
// TODO(ruimiguel): set final priority when RenderPriority PR merged. priority: RenderPriority.bottomBoundary,
priority: Ball.boardPriority + 2,
children: [_BottomBoundarySpriteComponent()], children: [_BottomBoundarySpriteComponent()],
) { ) {
renderBody = false; renderBody = false;
@ -91,7 +90,7 @@ class _OuterBoundary extends BodyComponent with InitialPosition {
/// {@macro outer_boundary} /// {@macro outer_boundary}
_OuterBoundary() _OuterBoundary()
: super( : super(
priority: Ball.launchRampPriority - 1, priority: RenderPriority.outerBoudary,
children: [_OuterBoundarySpriteComponent()], children: [_OuterBoundarySpriteComponent()],
) { ) {
renderBody = false; renderBody = false;

@ -12,10 +12,12 @@ import 'package:pinball_components/pinball_components.dart';
/// {@endtemplate} /// {@endtemplate}
class ChromeDino extends BodyComponent with InitialPosition { class ChromeDino extends BodyComponent with InitialPosition {
/// {@macro chrome_dino} /// {@macro chrome_dino}
ChromeDino() { ChromeDino()
// TODO(alestiago): Remove once sprites are defined. : super(
paint = Paint()..color = Colors.blue; // TODO(alestiago): Remove once sprites are defined.
} paint: Paint()..color = Colors.blue,
priority: RenderPriority.dino,
);
/// The size of the dinosaur mouth. /// The size of the dinosaur mouth.
static final size = Vector2(5, 2.5); static final size = Vector2(5, 2.5);

@ -21,6 +21,7 @@ export 'launch_ramp.dart';
export 'layer.dart'; export 'layer.dart';
export 'layer_sensor.dart'; export 'layer_sensor.dart';
export 'plunger.dart'; export 'plunger.dart';
export 'render_priority.dart';
export 'rocket.dart'; export 'rocket.dart';
export 'score_text.dart'; export 'score_text.dart';
export 'shapes/shapes.dart'; export 'shapes/shapes.dart';

@ -10,6 +10,7 @@ class DashAnimatronic extends SpriteAnimationComponent with HasGameRef {
: super( : super(
anchor: Anchor.center, anchor: Anchor.center,
playing: false, playing: false,
priority: RenderPriority.dashAnimatronic,
); );
@override @override

@ -19,6 +19,7 @@ class DashNestBumper extends BodyComponent with InitialPosition {
}) : _majorRadius = majorRadius, }) : _majorRadius = majorRadius,
_minorRadius = minorRadius, _minorRadius = minorRadius,
super( super(
priority: RenderPriority.dashBumper,
children: [ children: [
_DashNestBumperSpriteGroupComponent( _DashNestBumperSpriteGroupComponent(
activeAssetPath: activeAssetPath, activeAssetPath: activeAssetPath,

@ -31,8 +31,7 @@ class _DinoTopWall extends BodyComponent with InitialPosition {
///{@macro dino_top_wall} ///{@macro dino_top_wall}
_DinoTopWall() _DinoTopWall()
: super( : super(
// TODO(ruimiguel): set final priority when RenderPriority PR merged. priority: RenderPriority.dinoTopWall,
priority: Ball.boardPriority + 1,
children: [_DinoTopWallSpriteComponent()], children: [_DinoTopWallSpriteComponent()],
) { ) {
renderBody = false; renderBody = false;
@ -127,8 +126,7 @@ class _DinoBottomWall extends BodyComponent with InitialPosition {
///{@macro dino_top_wall} ///{@macro dino_top_wall}
_DinoBottomWall() _DinoBottomWall()
: super( : super(
// TODO(ruimiguel): set final priority when RenderPriority PR merged. priority: RenderPriority.dinoBottomWall,
priority: Ball.boardPriority + 1,
children: [_DinoBottomWallSpriteComponent()], children: [_DinoBottomWallSpriteComponent()],
) { ) {
renderBody = false; renderBody = false;

@ -9,6 +9,7 @@ class FlutterSignPost extends BodyComponent with InitialPosition {
/// {@macro flutter_sign_post} /// {@macro flutter_sign_post}
FlutterSignPost() FlutterSignPost()
: super( : super(
priority: RenderPriority.flutterSignPost,
children: [_FlutterSignPostSpriteComponent()], children: [_FlutterSignPostSpriteComponent()],
) { ) {
renderBody = false; renderBody = false;

@ -44,7 +44,7 @@ class _LaunchRampBase extends BodyComponent with InitialPosition, Layered {
/// {@macro launch_ramp_base} /// {@macro launch_ramp_base}
_LaunchRampBase() _LaunchRampBase()
: super( : super(
priority: Ball.launchRampPriority - 1, priority: RenderPriority.launchRamp,
children: [ children: [
_LaunchRampBackgroundRailingSpriteComponent(), _LaunchRampBackgroundRailingSpriteComponent(),
_LaunchRampBaseSpriteComponent(), _LaunchRampBaseSpriteComponent(),
@ -166,7 +166,7 @@ class _LaunchRampForegroundRailing extends BodyComponent with InitialPosition {
/// {@macro launch_ramp_foreground_railing} /// {@macro launch_ramp_foreground_railing}
_LaunchRampForegroundRailing() _LaunchRampForegroundRailing()
: super( : super(
priority: Ball.launchRampPriority + 1, priority: RenderPriority.launchRampForegroundRailing,
children: [_LaunchRampForegroundRailingSpriteComponent()], children: [_LaunchRampForegroundRailingSpriteComponent()],
) { ) {
renderBody = false; renderBody = false;
@ -265,8 +265,8 @@ class _LaunchRampExit extends LayerSensor {
insideLayer: Layer.launcher, insideLayer: Layer.launcher,
outsideLayer: Layer.board, outsideLayer: Layer.board,
orientation: LayerEntranceOrientation.down, orientation: LayerEntranceOrientation.down,
insidePriority: Ball.launchRampPriority, insidePriority: RenderPriority.ballOnLaunchRamp,
outsidePriority: 0, outsidePriority: RenderPriority.ballOnBoard,
) { ) {
layer = Layer.launcher; layer = Layer.launcher;
renderBody = false; renderBody = false;

@ -34,7 +34,7 @@ abstract class LayerSensor extends BodyComponent with InitialPosition, Layered {
}) : _insideLayer = insideLayer, }) : _insideLayer = insideLayer,
_outsideLayer = outsideLayer ?? Layer.board, _outsideLayer = outsideLayer ?? Layer.board,
_insidePriority = insidePriority, _insidePriority = insidePriority,
_outsidePriority = outsidePriority ?? Ball.boardPriority { _outsidePriority = outsidePriority ?? RenderPriority.ballOnBoard {
layer = Layer.opening; layer = Layer.opening;
} }
final Layer _insideLayer; final Layer _insideLayer;

@ -14,25 +14,49 @@ class Plunger extends BodyComponent with InitialPosition, Layered {
required this.compressionDistance, required this.compressionDistance,
// TODO(ruimiguel): set to priority +1 over LaunchRamp once all priorities // TODO(ruimiguel): set to priority +1 over LaunchRamp once all priorities
// are fixed. // are fixed.
}) : super(priority: 0) { }) : super(priority: RenderPriority.plunger) {
layer = Layer.launcher; layer = Layer.launcher;
renderBody = false;
} }
/// Distance the plunger can lower. /// Distance the plunger can lower.
final double compressionDistance; final double compressionDistance;
late final _PlungerSpriteAnimationGroupComponent _spriteComponent;
List<FixtureDef> _createFixtureDefs() {
final fixturesDef = <FixtureDef>[];
final leftShapeVertices = [
Vector2(0, 0),
Vector2(-1.8, 0),
Vector2(-1.8, -2.2),
Vector2(0, -0.3),
]..map((vector) => vector.rotate(BoardDimensions.perspectiveAngle))
.toList();
final leftTriangleShape = PolygonShape()..set(leftShapeVertices);
final leftTriangleFixtureDef = FixtureDef(leftTriangleShape)..density = 80;
fixturesDef.add(leftTriangleFixtureDef);
final rightShapeVertices = [
Vector2(0, 0),
Vector2(1.8, 0),
Vector2(1.8, -2.2),
Vector2(0, -0.3),
]..map((vector) => vector.rotate(BoardDimensions.perspectiveAngle))
.toList();
final rightTriangleShape = PolygonShape()..set(rightShapeVertices);
final rightTriangleFixtureDef = FixtureDef(rightTriangleShape)
..density = 80;
fixturesDef.add(rightTriangleFixtureDef);
return fixturesDef;
}
@override @override
Body createBody() { Body createBody() {
final shape = PolygonShape()
..setAsBox(
1.35,
0.5,
Vector2.zero(),
BoardDimensions.perspectiveAngle,
);
final fixtureDef = FixtureDef(shape)..density = 80;
final bodyDef = BodyDef( final bodyDef = BodyDef(
position: initialPosition, position: initialPosition,
userData: this, userData: this,
@ -40,12 +64,15 @@ class Plunger extends BodyComponent with InitialPosition, Layered {
gravityScale: Vector2.zero(), gravityScale: Vector2.zero(),
); );
return world.createBody(bodyDef)..createFixture(fixtureDef); final body = world.createBody(bodyDef);
_createFixtureDefs().forEach(body.createFixture);
return body;
} }
/// Set a constant downward velocity on the [Plunger]. /// Set a constant downward velocity on the [Plunger].
void pull() { void pull() {
body.linearVelocity = Vector2(0, 7); body.linearVelocity = Vector2(0, 7);
_spriteComponent.pull();
} }
/// Set an upward velocity on the [Plunger]. /// Set an upward velocity on the [Plunger].
@ -55,6 +82,7 @@ class Plunger extends BodyComponent with InitialPosition, Layered {
void release() { void release() {
final velocity = (initialPosition.y - body.position.y) * 5; final velocity = (initialPosition.y - body.position.y) * 5;
body.linearVelocity = Vector2(0, velocity); body.linearVelocity = Vector2(0, velocity);
_spriteComponent.release();
} }
/// Anchors the [Plunger] to the [PrismaticJoint] that controls its vertical /// Anchors the [Plunger] to the [PrismaticJoint] that controls its vertical
@ -77,24 +105,84 @@ class Plunger extends BodyComponent with InitialPosition, Layered {
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
await _anchorToJoint(); await _anchorToJoint();
renderBody = false;
await add(_PlungerSpriteComponent()); _spriteComponent = _PlungerSpriteAnimationGroupComponent();
await add(_spriteComponent);
} }
} }
class _PlungerSpriteComponent extends SpriteComponent with HasGameRef { /// Animation states associated with a [Plunger].
enum _PlungerAnimationState {
/// Pull state.
pull,
/// Release state.
release,
}
/// Animations for pulling and releasing [Plunger].
class _PlungerSpriteAnimationGroupComponent
extends SpriteAnimationGroupComponent<_PlungerAnimationState>
with HasGameRef {
_PlungerSpriteAnimationGroupComponent()
: super(
anchor: Anchor.center,
position: Vector2(1.87, 14.9),
);
void pull() {
if (current != _PlungerAnimationState.pull) {
animation?.reset();
}
current = _PlungerAnimationState.pull;
}
void release() {
if (current != _PlungerAnimationState.release) {
animation?.reset();
}
current = _PlungerAnimationState.release;
}
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
final sprite = await gameRef.loadSprite(
final spriteSheet = await gameRef.images.load(
Assets.images.plunger.plunger.keyName, Assets.images.plunger.plunger.keyName,
); );
this.sprite = sprite; const amountPerRow = 20;
size = sprite.originalSize / 10; const amountPerColumn = 1;
anchor = Anchor.center;
position = Vector2(1.5, 13.4); final textureSize = Vector2(
angle = -0.008; spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
// TODO(ruimiguel): we only need plunger pull animation, and release is just
// to reverse it, so we need to divide by 2 while we don't have only half of
// the animation (but amountPerRow and amountPerColumn needs to be correct
// in order of calculate textureSize correctly).
final pullAnimation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn ~/ 2,
amountPerRow: amountPerRow ~/ 2,
stepTime: 1 / 24,
textureSize: textureSize,
texturePosition: Vector2.zero(),
loop: false,
),
);
animations = {
_PlungerAnimationState.release: pullAnimation.reversed(),
_PlungerAnimationState.pull: pullAnimation,
};
current = _PlungerAnimationState.release;
} }
} }

@ -0,0 +1,114 @@
// ignore_for_file: public_member_api_docs
import 'package:pinball_components/pinball_components.dart';
/// {@template render_priority}
/// Priorities for the component rendering order in the pinball game.
/// {@endtemplate}
// TODO(allisonryan0002): find alternative to section comments.
abstract class RenderPriority {
static const _base = 0;
static const _above = 1;
static const _below = -1;
// Ball
/// Render priority for the [Ball] while it's on the board.
static const int ballOnBoard = _base;
/// Render priority for the [Ball] while it's on the [SpaceshipRamp].
static const int ballOnSpaceshipRamp =
_above + spaceshipRampBackgroundRailing;
/// Render priority for the [Ball] while it's on the [Spaceship].
static const int ballOnSpaceship = _above + spaceshipSaucer;
/// Render priority for the [Ball] while it's on the [SpaceshipRail].
static const int ballOnSpaceshipRail = _below + spaceshipSaucer;
/// Render priority for the [Ball] while it's on the [LaunchRamp].
static const int ballOnLaunchRamp = _above + launchRamp;
// Background
// TODO(allisonryan0002): fix this magic priority. Could bump all priorities
// so there are no negatives.
static const int background = 3 * _below + _base;
// Boundaries
static const int bottomBoundary = _above + dinoBottomWall;
static const int outerBoudary = _above + background;
// Bottom Group
static const int bottomGroup = _above + ballOnBoard;
// Launcher
static const int launchRamp = _above + outerBoudary;
static const int launchRampForegroundRailing = _above + ballOnLaunchRamp;
static const int plunger = _above + launchRamp;
static const int rocket = _above + bottomBoundary;
// Dino Land
static const int dinoTopWall = _above + ballOnBoard;
static const int dino = _above + dinoTopWall;
static const int dinoBottomWall = _above + dino;
static const int slingshot = _above + ballOnBoard;
// Flutter Forest
static const int flutterSignPost = _above + launchRampForegroundRailing;
static const int dashBumper = _above + ballOnBoard;
static const int dashAnimatronic = _above + launchRampForegroundRailing;
// Sparky Fire Zone
static const int computerBase = _below + ballOnBoard;
static const int computerTop = _above + ballOnBoard;
static const int sparkyAnimatronic = _above + spaceshipRampForegroundRailing;
static const int sparkyBumper = _above + ballOnBoard;
static const int turboChargeFlame = _above + ballOnBoard;
// Android Spaceship
static const int spaceshipRail = _above + bottomGroup;
static const int spaceshipRailForeground = _above + spaceshipRail;
static const int spaceshipSaucer = _above + spaceshipRail;
static const int spaceshipSaucerWall = _above + spaceshipSaucer;
static const int androidHead = _above + spaceshipSaucer;
static const int spaceshipRamp = _above + ballOnBoard;
static const int spaceshipRampBackgroundRailing = _above + spaceshipRamp;
static const int spaceshipRampForegroundRailing =
_above + ballOnSpaceshipRamp;
static const int spaceshipRampBoardOpening = _below + ballOnBoard;
static const int alienBumper = _above + ballOnBoard;
// Score Text
static const int scoreText = _above + spaceshipRampForegroundRailing;
}

@ -9,7 +9,7 @@ class RocketSpriteComponent extends SpriteComponent with HasGameRef {
// TODO(ruimiguel): change this priority to be over launcher ramp and bottom // TODO(ruimiguel): change this priority to be over launcher ramp and bottom
// wall. // wall.
/// {@macro rocket_sprite_component} /// {@macro rocket_sprite_component}
RocketSpriteComponent() : super(priority: 5); RocketSpriteComponent() : super(priority: RenderPriority.rocket);
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

@ -18,7 +18,7 @@ class ScoreText extends TextComponent {
text: text, text: text,
position: position, position: position,
anchor: Anchor.center, anchor: Anchor.center,
priority: Ball.spaceshipRampPriority + 1, priority: RenderPriority.scoreText,
); );
late final Effect _effect; late final Effect _effect;

@ -43,7 +43,7 @@ class Slingshot extends BodyComponent with InitialPosition {
}) : _length = length, }) : _length = length,
_angle = angle, _angle = angle,
super( super(
priority: 1, priority: RenderPriority.slingshot,
children: [_SlinghsotSpriteComponent(spritePath, angle: angle)], children: [_SlinghsotSpriteComponent(spritePath, angle: angle)],
) { ) {
renderBody = false; renderBody = false;

@ -35,9 +35,12 @@ class Spaceship extends Forge2DBlueprint {
AndroidHead()..initialPosition = position, AndroidHead()..initialPosition = position,
_SpaceshipHole( _SpaceshipHole(
outsideLayer: Layer.spaceshipExitRail, outsideLayer: Layer.spaceshipExitRail,
outsidePriority: Ball.spaceshipRailPriority, 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,
]); ]);
} }
@ -48,7 +51,7 @@ class Spaceship extends Forge2DBlueprint {
/// {@endtemplate} /// {@endtemplate}
class SpaceshipSaucer extends BodyComponent with InitialPosition, Layered { class SpaceshipSaucer extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_saucer} /// {@macro spaceship_saucer}
SpaceshipSaucer() : super(priority: Ball.spaceshipPriority - 1) { SpaceshipSaucer() : super(priority: RenderPriority.spaceshipSaucer) {
layer = Layer.spaceship; layer = Layer.spaceship;
} }
@ -94,7 +97,7 @@ class AndroidHead extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_bridge} /// {@macro spaceship_bridge}
AndroidHead() AndroidHead()
: super( : super(
priority: Ball.spaceshipPriority + 1, priority: RenderPriority.androidHead,
children: [_AndroidHeadSpriteAnimation()], children: [_AndroidHeadSpriteAnimation()],
) { ) {
renderBody = false; renderBody = false;
@ -145,7 +148,7 @@ class _SpaceshipEntrance extends LayerSensor {
: super( : super(
insideLayer: Layer.spaceship, insideLayer: Layer.spaceship,
orientation: LayerEntranceOrientation.up, orientation: LayerEntranceOrientation.up,
insidePriority: Ball.spaceshipPriority, insidePriority: RenderPriority.ballOnSpaceship,
) { ) {
layer = Layer.spaceship; layer = Layer.spaceship;
} }
@ -169,12 +172,12 @@ class _SpaceshipEntrance extends LayerSensor {
} }
class _SpaceshipHole extends LayerSensor { class _SpaceshipHole extends LayerSensor {
_SpaceshipHole({Layer? outsideLayer, int? outsidePriority = 1}) _SpaceshipHole({required Layer outsideLayer, required int outsidePriority})
: super( : super(
insideLayer: Layer.spaceship, insideLayer: Layer.spaceship,
outsideLayer: outsideLayer, outsideLayer: outsideLayer,
orientation: LayerEntranceOrientation.down, orientation: LayerEntranceOrientation.down,
insidePriority: 4, insidePriority: RenderPriority.ballOnSpaceship,
outsidePriority: outsidePriority, outsidePriority: outsidePriority,
) { ) {
renderBody = false; renderBody = false;
@ -225,7 +228,7 @@ class _SpaceshipWallShape extends ChainShape {
/// {@endtemplate} /// {@endtemplate}
class SpaceshipWall extends BodyComponent with InitialPosition, Layered { class SpaceshipWall extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_wall} /// {@macro spaceship_wall}
SpaceshipWall() : super(priority: Ball.spaceshipPriority + 1) { SpaceshipWall() : super(priority: RenderPriority.spaceshipSaucerWall) {
layer = Layer.spaceship; layer = Layer.spaceship;
} }

@ -41,10 +41,7 @@ class SpaceshipRail extends Forge2DBlueprint {
/// Represents the spaceship drop rail from the [Spaceship]. /// Represents the spaceship drop rail from the [Spaceship].
class _SpaceshipRailRamp extends BodyComponent with InitialPosition, Layered { class _SpaceshipRailRamp extends BodyComponent with InitialPosition, Layered {
_SpaceshipRailRamp() _SpaceshipRailRamp() : super(priority: RenderPriority.spaceshipRail) {
: super(
priority: Ball.spaceshipRailPriority - 1,
) {
layer = Layer.spaceshipExitRail; layer = Layer.spaceshipExitRail;
} }
@ -160,7 +157,8 @@ class _SpaceshipRailRampSpriteComponent extends SpriteComponent
} }
class _SpaceshipRailForeground extends SpriteComponent with HasGameRef { class _SpaceshipRailForeground extends SpriteComponent with HasGameRef {
_SpaceshipRailForeground() : super(priority: Ball.spaceshipRailPriority + 1); _SpaceshipRailForeground()
: super(priority: RenderPriority.spaceshipRailForeground);
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
@ -177,13 +175,9 @@ class _SpaceshipRailForeground extends SpriteComponent with HasGameRef {
} }
/// Represents the ground bases of the [_SpaceshipRailRamp]. /// Represents the ground bases of the [_SpaceshipRailRamp].
class _SpaceshipRailBase extends BodyComponent with InitialPosition, Layered { class _SpaceshipRailBase extends BodyComponent with InitialPosition {
_SpaceshipRailBase({required this.radius}) _SpaceshipRailBase({required this.radius}) {
: super(
priority: Ball.spaceshipRailPriority + 1,
) {
renderBody = false; renderBody = false;
layer = Layer.board;
} }
final double radius; final double radius;
@ -206,7 +200,7 @@ class _SpaceshipRailExit extends LayerSensor {
: super( : super(
orientation: LayerEntranceOrientation.down, orientation: LayerEntranceOrientation.down,
insideLayer: Layer.spaceshipExitRail, insideLayer: Layer.spaceshipExitRail,
insidePriority: Ball.spaceshipRailPriority, insidePriority: RenderPriority.ballOnSpaceshipRail,
) { ) {
renderBody = false; renderBody = false;
layer = Layer.spaceshipExitRail; layer = Layer.spaceshipExitRail;

@ -22,15 +22,14 @@ class SpaceshipRamp extends Forge2DBlueprint {
]); ]);
final rightOpening = _SpaceshipRampOpening( final rightOpening = _SpaceshipRampOpening(
// TODO(ruimiguel): set Board priority when defined. outsidePriority: RenderPriority.ballOnBoard,
outsidePriority: 1,
rotation: math.pi, rotation: math.pi,
) )
..initialPosition = Vector2(1.7, -19.8) ..initialPosition = Vector2(1.7, -19.8)
..layer = Layer.opening; ..layer = Layer.opening;
final leftOpening = _SpaceshipRampOpening( final leftOpening = _SpaceshipRampOpening(
outsideLayer: Layer.spaceship, outsideLayer: Layer.spaceship,
outsidePriority: Ball.spaceshipPriority, outsidePriority: RenderPriority.ballOnSpaceship,
rotation: math.pi, rotation: math.pi,
) )
..initialPosition = Vector2(-13.7, -18.6) ..initialPosition = Vector2(-13.7, -18.6)
@ -51,6 +50,7 @@ class SpaceshipRamp extends Forge2DBlueprint {
rightOpening, rightOpening,
leftOpening, leftOpening,
baseRight, baseRight,
_SpaceshipRampBackgroundRailingSpriteComponent(),
spaceshipRamp, spaceshipRamp,
spaceshipRampForegroundRailing, spaceshipRampForegroundRailing,
]); ]);
@ -59,7 +59,7 @@ class SpaceshipRamp extends Forge2DBlueprint {
class _SpaceshipRampBackground extends BodyComponent class _SpaceshipRampBackground extends BodyComponent
with InitialPosition, Layered { with InitialPosition, Layered {
_SpaceshipRampBackground() : super(priority: Ball.spaceshipRampPriority - 1) { _SpaceshipRampBackground() : super(priority: RenderPriority.spaceshipRamp) {
layer = Layer.spaceshipEntranceRamp; layer = Layer.spaceshipEntranceRamp;
} }
@ -119,12 +119,13 @@ class _SpaceshipRampBackground extends BodyComponent
renderBody = false; renderBody = false;
await add(_SpaceshipRampBackgroundRampSpriteComponent()); await add(_SpaceshipRampBackgroundRampSpriteComponent());
await add(_SpaceshipRampBackgroundRailingSpriteComponent());
} }
} }
class _SpaceshipRampBackgroundRailingSpriteComponent extends SpriteComponent class _SpaceshipRampBackgroundRailingSpriteComponent extends SpriteComponent
with HasGameRef { with HasGameRef {
_SpaceshipRampBackgroundRailingSpriteComponent()
: super(priority: RenderPriority.spaceshipRampBackgroundRailing);
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
@ -171,7 +172,7 @@ class _SpaceshipRampForegroundRailing extends BodyComponent
with InitialPosition, Layered { with InitialPosition, Layered {
_SpaceshipRampForegroundRailing() _SpaceshipRampForegroundRailing()
: super( : super(
priority: Ball.spaceshipRampPriority + 1, priority: RenderPriority.spaceshipRampForegroundRailing,
children: [_SpaceshipRampForegroundRailingSpriteComponent()], children: [_SpaceshipRampForegroundRailingSpriteComponent()],
) { ) {
layer = Layer.spaceshipEntranceRamp; layer = Layer.spaceshipEntranceRamp;
@ -287,7 +288,7 @@ class _SpaceshipRampOpening extends LayerSensor {
insideLayer: Layer.spaceshipEntranceRamp, insideLayer: Layer.spaceshipEntranceRamp,
outsideLayer: outsideLayer, outsideLayer: outsideLayer,
orientation: LayerEntranceOrientation.down, orientation: LayerEntranceOrientation.down,
insidePriority: Ball.spaceshipRampPriority, insidePriority: RenderPriority.ballOnSpaceshipRamp,
outsidePriority: outsidePriority, outsidePriority: outsidePriority,
) { ) {
renderBody = false; renderBody = false;

@ -19,6 +19,7 @@ class SparkyBumper extends BodyComponent with InitialPosition {
}) : _majorRadius = majorRadius, }) : _majorRadius = majorRadius,
_minorRadius = minorRadius, _minorRadius = minorRadius,
super( super(
priority: RenderPriority.sparkyBumper,
children: [ children: [
_SparkyBumperSpriteGroupComponent( _SparkyBumperSpriteGroupComponent(
onAssetPath: onAssetPath, onAssetPath: onAssetPath,

@ -23,7 +23,7 @@ class SparkyComputer extends Forge2DBlueprint {
} }
class _ComputerBase extends BodyComponent with InitialPosition { class _ComputerBase extends BodyComponent with InitialPosition {
_ComputerBase(); _ComputerBase() : super(priority: RenderPriority.computerBase);
List<FixtureDef> _createFixtureDefs() { List<FixtureDef> _createFixtureDefs() {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
@ -101,7 +101,7 @@ class _ComputerTopSpriteComponent extends SpriteComponent with HasGameRef {
: super( : super(
anchor: Anchor.center, anchor: Anchor.center,
position: Vector2(-12.45, -49.75), position: Vector2(-12.45, -49.75),
priority: 1, priority: RenderPriority.computerTop,
); );
@override @override

@ -10,7 +10,7 @@ class LaunchRampGame extends BasicBallGame {
LaunchRampGame() LaunchRampGame()
: super( : super(
color: Colors.blue, color: Colors.blue,
ballPriority: Ball.launchRampPriority, ballPriority: RenderPriority.ballOnLaunchRamp,
ballLayer: Layer.launcher, ballLayer: Layer.launcher,
); );

@ -10,7 +10,7 @@ class SpaceshipRailGame extends BasicBallGame {
SpaceshipRailGame() SpaceshipRailGame()
: super( : super(
color: Colors.blue, color: Colors.blue,
ballPriority: Ball.spaceshipRailPriority, ballPriority: RenderPriority.ballOnSpaceshipRail,
ballLayer: Layer.spaceshipExitRail, ballLayer: Layer.spaceshipExitRail,
); );

@ -10,7 +10,7 @@ class SpaceshipRampGame extends BasicBallGame {
SpaceshipRampGame() SpaceshipRampGame()
: super( : super(
color: Colors.blue, color: Colors.blue,
ballPriority: Ball.spaceshipRampPriority, ballPriority: RenderPriority.ballOnSpaceshipRamp,
ballLayer: Layer.spaceshipEntranceRamp, ballLayer: Layer.spaceshipEntranceRamp,
); );

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

@ -148,7 +148,7 @@ void main() {
callback.begin(ball, sensor, MockContact()); callback.begin(ball, sensor, MockContact());
verify(() => ball.layer = Layer.board); verify(() => ball.layer = Layer.board);
verify(() => ball.priority = Ball.boardPriority).called(1); verify(() => ball.priority = RenderPriority.ballOnBoard).called(1);
verify(ball.reorderChildren).called(1); verify(ball.reorderChildren).called(1);
}); });
@ -174,7 +174,7 @@ void main() {
callback.begin(ball, sensor, MockContact()); callback.begin(ball, sensor, MockContact());
verify(() => ball.layer = Layer.board); verify(() => ball.layer = Layer.board);
verify(() => ball.priority = Ball.boardPriority).called(1); verify(() => ball.priority = RenderPriority.ballOnBoard).called(1);
verify(ball.reorderChildren).called(1); verify(ball.reorderChildren).called(1);
}); });
}); });

@ -23,9 +23,21 @@ void main() {
game.camera.zoom = 4.1; game.camera.zoom = 4.1;
}, },
verify: (game, tester) async { verify: (game, tester) async {
final plunger = game.descendants().whereType<Plunger>().first;
plunger.pull();
game.update(1);
await tester.pump();
await expectLater( await expectLater(
find.byGame<TestGame>(), find.byGame<TestGame>(),
matchesGoldenFile('golden/plunger.png'), matchesGoldenFile('golden/plunger/pull.png'),
);
plunger.release();
game.update(1);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/plunger/release.png'),
); );
}, },
); );
@ -110,12 +122,17 @@ void main() {
}); });
group('pull', () { group('pull', () {
late Plunger plunger;
setUp(() {
plunger = Plunger(
compressionDistance: compressionDistance,
);
});
flameTester.test( flameTester.test(
'moves downwards when pull is called', 'moves downwards when pull is called',
(game) async { (game) async {
final plunger = Plunger(
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
plunger.pull(); plunger.pull();
@ -123,6 +140,18 @@ void main() {
expect(plunger.body.linearVelocity.x, isZero); expect(plunger.body.linearVelocity.x, isZero);
}, },
); );
flameTester.test(
'moves downwards when pull is called '
'and plunger is below its starting position', (game) async {
await game.ensureAdd(plunger);
plunger.pull();
plunger.release();
plunger.pull();
expect(plunger.body.linearVelocity.y, isPositive);
expect(plunger.body.linearVelocity.x, isZero);
});
}); });
group('release', () { group('release', () {

@ -7,8 +7,9 @@
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart'; import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/app/app.dart'; import 'package:pinball/app/app.dart';
import 'package:pinball/landing/landing.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_audio/pinball_audio.dart'; import 'package:pinball_audio/pinball_audio.dart';
import '../../helpers/mocks.dart'; import '../../helpers/mocks.dart';
@ -21,16 +22,18 @@ void main() {
setUp(() { setUp(() {
leaderboardRepository = MockLeaderboardRepository(); leaderboardRepository = MockLeaderboardRepository();
pinballAudio = MockPinballAudio(); pinballAudio = MockPinballAudio();
when(pinballAudio.load).thenAnswer((_) => Future.value());
}); });
testWidgets('renders LandingPage', (tester) async { testWidgets('renders PinballGamePage', (tester) async {
await tester.pumpWidget( await tester.pumpWidget(
App( App(
leaderboardRepository: leaderboardRepository, leaderboardRepository: leaderboardRepository,
pinballAudio: pinballAudio, pinballAudio: pinballAudio,
), ),
); );
expect(find.byType(LandingPage), findsOneWidget); expect(find.byType(PinballGamePage), findsOneWidget);
}); });
}); });
} }

@ -5,40 +5,46 @@ import 'package:flame/game.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball/theme/theme.dart';
import '../../helpers/helpers.dart'; import '../../helpers/helpers.dart';
void main() { void main() {
const theme = PinballTheme(characterTheme: DashTheme());
final game = PinballTestGame(); final game = PinballTestGame();
group('PinballGamePage', () { group('PinballGamePage', () {
testWidgets('renders PinballGameView', (tester) async { late ThemeCubit themeCubit;
final gameBloc = MockGameBloc(); late GameBloc gameBloc;
setUp(() {
themeCubit = MockThemeCubit();
gameBloc = MockGameBloc();
whenListen(
themeCubit,
const Stream<ThemeState>.empty(),
initialState: const ThemeState.initial(),
);
whenListen( whenListen(
gameBloc, gameBloc,
Stream.value(const GameState.initial()), Stream.value(const GameState.initial()),
initialState: const GameState.initial(), initialState: const GameState.initial(),
); );
});
testWidgets('renders PinballGameView', (tester) async {
await tester.pumpApp( await tester.pumpApp(
PinballGamePage(theme: theme, game: game), PinballGamePage(),
gameBloc: gameBloc, themeCubit: themeCubit,
); );
expect(find.byType(PinballGameView), findsOneWidget); expect(find.byType(PinballGameView), findsOneWidget);
}); });
testWidgets( testWidgets(
'renders the loading indicator while the assets load', 'renders the loading indicator while the assets load',
(tester) async { (tester) async {
final gameBloc = MockGameBloc();
whenListen(
gameBloc,
Stream.value(const GameState.initial()),
initialState: const GameState.initial(),
);
final assetsManagerCubit = MockAssetsManagerCubit(); final assetsManagerCubit = MockAssetsManagerCubit();
final initialAssetsState = AssetsManagerState( final initialAssetsState = AssetsManagerState(
loadables: [Future<void>.value()], loadables: [Future<void>.value()],
@ -51,27 +57,52 @@ void main() {
); );
await tester.pumpApp( await tester.pumpApp(
PinballGamePage(theme: theme, game: game), PinballGameView(
gameBloc: gameBloc, game: game,
),
assetsManagerCubit: assetsManagerCubit, assetsManagerCubit: assetsManagerCubit,
themeCubit: themeCubit,
); );
expect(find.text('0.0'), findsOneWidget);
final loadedAssetsState = AssetsManagerState( expect(
loadables: [Future<void>.value()], find.byWidgetPredicate(
loaded: [Future<void>.value()], (widget) =>
); widget is LinearProgressIndicator && widget.value == 0.0,
whenListen( ),
assetsManagerCubit, findsOneWidget,
Stream.value(loadedAssetsState),
initialState: loadedAssetsState,
); );
await tester.pump();
expect(find.byType(PinballGameView), findsOneWidget);
}, },
); );
testWidgets(
'renders PinballGameLoadedView after resources have been loaded',
(tester) async {
final assetsManagerCubit = MockAssetsManagerCubit();
final loadedAssetsState = AssetsManagerState(
loadables: [Future<void>.value()],
loaded: [Future<void>.value()],
);
whenListen(
assetsManagerCubit,
Stream.value(loadedAssetsState),
initialState: loadedAssetsState,
);
await tester.pumpApp(
PinballGameView(
game: game,
),
assetsManagerCubit: assetsManagerCubit,
themeCubit: themeCubit,
gameBloc: gameBloc,
);
await tester.pump();
expect(find.byType(PinballGameLoadedView), findsOneWidget);
});
group('route', () { group('route', () {
Future<void> pumpRoute({ Future<void> pumpRoute({
required WidgetTester tester, required WidgetTester tester,
@ -85,7 +116,6 @@ void main() {
onPressed: () { onPressed: () {
Navigator.of(context).push<void>( Navigator.of(context).push<void>(
PinballGamePage.route( PinballGamePage.route(
theme: theme,
isDebugMode: isDebugMode, isDebugMode: isDebugMode,
), ),
); );
@ -95,6 +125,7 @@ void main() {
}, },
), ),
), ),
themeCubit: themeCubit,
); );
await tester.tap(find.text('Tap me')); await tester.tap(find.text('Tap me'));

@ -1,8 +1,9 @@
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/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/theme/theme.dart';
import '../../helpers/helpers.dart'; import '../../../helpers/helpers.dart';
void main() { void main() {
group('PlayButtonOverlay', () { group('PlayButtonOverlay', () {
@ -31,5 +32,15 @@ void main() {
verify(gameFlowController.start).called(1); verify(gameFlowController.start).called(1);
}); });
testWidgets('displays CharacterSelectionDialog when tapped',
(tester) async {
await tester.pumpApp(PlayButtonOverlay(game: game));
await tester.tap(find.text('Play'));
await tester.pump();
expect(find.byType(CharacterSelectionDialog), findsOneWidget);
});
}); });
} }

@ -1,71 +0,0 @@
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockingjay/mockingjay.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball/landing/landing.dart';
import '../../helpers/helpers.dart';
void main() {
group('LandingPage', () {
testWidgets('renders correctly', (tester) async {
final l10n = await AppLocalizations.delegate.load(Locale('en'));
await tester.pumpApp(LandingPage());
expect(find.byType(TextButton), findsNWidgets(2));
expect(find.text(l10n.play), findsOneWidget);
expect(find.text(l10n.howToPlay), findsOneWidget);
});
testWidgets('tapping on play button navigates to CharacterSelectionPage',
(tester) async {
final l10n = await AppLocalizations.delegate.load(Locale('en'));
final navigator = MockNavigator();
when(() => navigator.push<void>(any())).thenAnswer((_) async {});
await tester.pumpApp(
LandingPage(),
navigator: navigator,
);
await tester.tap(find.widgetWithText(TextButton, l10n.play));
verify(() => navigator.push<void>(any())).called(1);
});
testWidgets('tapping on how to play button displays dialog with controls',
(tester) async {
final l10n = await AppLocalizations.delegate.load(Locale('en'));
await tester.pumpApp(LandingPage());
await tester.tap(find.widgetWithText(TextButton, l10n.howToPlay));
await tester.pump();
expect(find.byType(Dialog), findsOneWidget);
});
});
group('KeyIndicator', () {
testWidgets('fromKeyName renders correctly', (tester) async {
const keyName = 'A';
await tester.pumpApp(
KeyIndicator.fromKeyName(keyName: keyName),
);
expect(find.text(keyName), findsOneWidget);
});
testWidgets('fromIcon renders correctly', (tester) async {
const keyIcon = Icons.keyboard_arrow_down;
await tester.pumpApp(
KeyIndicator.fromIcon(keyIcon: keyIcon),
);
expect(find.byIcon(keyIcon), findsOneWidget);
});
});
}

@ -0,0 +1,39 @@
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/start_game/start_game.dart';
import '../../helpers/helpers.dart';
void main() {
group('HowToPlayDialog', () {
testWidgets('displays dialog', (tester) async {
await tester.pumpApp(HowToPlayDialog());
expect(find.byType(Dialog), findsOneWidget);
});
});
group('KeyIndicator', () {
testWidgets('fromKeyName renders correctly', (tester) async {
const keyName = 'A';
await tester.pumpApp(
KeyIndicator.fromKeyName(keyName: keyName),
);
expect(find.text(keyName), findsOneWidget);
});
testWidgets('fromIcon renders correctly', (tester) async {
const keyIcon = Icons.keyboard_arrow_down;
await tester.pumpApp(
KeyIndicator.fromIcon(keyIcon: keyIcon),
);
expect(find.byIcon(keyIcon), findsOneWidget);
});
});
}

@ -4,6 +4,7 @@ import 'package:bloc_test/bloc_test.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:mockingjay/mockingjay.dart'; import 'package:mockingjay/mockingjay.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball/theme/theme.dart'; import 'package:pinball/theme/theme.dart';
import 'package:pinball_theme/pinball_theme.dart'; import 'package:pinball_theme/pinball_theme.dart';
@ -24,7 +25,7 @@ void main() {
group('CharacterSelectionPage', () { group('CharacterSelectionPage', () {
testWidgets('renders CharacterSelectionView', (tester) async { testWidgets('renders CharacterSelectionView', (tester) async {
await tester.pumpApp( await tester.pumpApp(
CharacterSelectionPage(), CharacterSelectionDialog(),
themeCubit: themeCubit, themeCubit: themeCubit,
); );
expect(find.byType(CharacterSelectionView), findsOneWidget); expect(find.byType(CharacterSelectionView), findsOneWidget);
@ -38,7 +39,7 @@ void main() {
return ElevatedButton( return ElevatedButton(
onPressed: () { onPressed: () {
Navigator.of(context) Navigator.of(context)
.push<void>(CharacterSelectionPage.route()); .push<void>(CharacterSelectionDialog.route());
}, },
child: Text('Tap me'), child: Text('Tap me'),
); );
@ -51,7 +52,7 @@ void main() {
await tester.tap(find.text('Tap me')); await tester.tap(find.text('Tap me'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(CharacterSelectionPage), findsOneWidget); expect(find.byType(CharacterSelectionDialog), findsOneWidget);
}); });
}); });
@ -82,20 +83,17 @@ void main() {
verify(() => themeCubit.characterSelected(SparkyTheme())).called(1); verify(() => themeCubit.characterSelected(SparkyTheme())).called(1);
}); });
testWidgets('navigates to PinballGamePage when start is tapped', testWidgets('displays how to play dialog when start is tapped',
(tester) async { (tester) async {
final navigator = MockNavigator();
when(() => navigator.push<void>(any())).thenAnswer((_) async {});
await tester.pumpApp( await tester.pumpApp(
CharacterSelectionView(), CharacterSelectionView(),
themeCubit: themeCubit, themeCubit: themeCubit,
navigator: navigator,
); );
await tester.ensureVisible(find.byType(TextButton)); await tester.ensureVisible(find.byType(TextButton));
await tester.tap(find.byType(TextButton)); await tester.tap(find.byType(TextButton));
await tester.pumpAndSettle();
verify(() => navigator.push<void>(any())).called(1); expect(find.byType(HowToPlayDialog), findsOneWidget);
}); });
}); });

Loading…
Cancel
Save