Merge branch 'main' into fix/firebase-config

pull/302/head
Tom Arra 3 years ago committed by GitHub
commit c26a6e4d28
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,13 +10,21 @@ jobs:
runs-on: ubuntu-latest
name: Deploy Development
steps:
- uses: actions/checkout@v2
- uses: subosito/flutter-action@v2
- name: Checkout Repo
uses: actions/checkout@v2
- name: Setup Flutter
uses: subosito/flutter-action@v2
with:
channel: stable
- run: flutter packages get
- run: flutter build web --target lib/main_development.dart --web-renderer canvaskit --release
- uses: FirebaseExtended/action-hosting-deploy@v0
- name: Build Flutter App
run: |
flutter packages get
flutter build web --target lib/main_development.dart --web-renderer canvaskit --release
- name: Deploy to Firebase
uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: "${{ secrets.GITHUB_TOKEN }}"
firebaseServiceAccount: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_PINBALL_DEV }}"

@ -1,8 +1 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
export 'view/app.dart';

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
// ignore_for_file: public_member_api_docs
import 'package:authentication_repository/authentication_repository.dart';

@ -0,0 +1,2 @@
export 'cubit/assets_manager_cubit.dart';
export 'views/views.dart';

@ -0,0 +1,46 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/assets_manager/assets_manager.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_ui/pinball_ui.dart';
/// {@template assets_loading_page}
/// Widget used to indicate the loading progress of the different assets used
/// in the game
/// {@endtemplate}
class AssetsLoadingPage extends StatelessWidget {
/// {@macro assets_loading_page}
const AssetsLoadingPage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final headline1 = Theme.of(context).textTheme.headline1;
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
l10n.ioPinball,
style: headline1!.copyWith(fontSize: 80),
textAlign: TextAlign.center,
),
const SizedBox(height: 40),
AnimatedEllipsisText(
l10n.loading,
style: headline1,
),
const SizedBox(height: 40),
FractionallySizedBox(
widthFactor: 0.8,
child: BlocBuilder<AssetsManagerCubit, AssetsManagerState>(
builder: (context, state) {
return PinballLoadingIndicator(value: state.progress);
},
),
),
],
),
);
}
}

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

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
// ignore_for_file: public_member_api_docs
import 'dart:async';

@ -1,6 +1,8 @@
// ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/components/android_acres/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
@ -16,6 +18,11 @@ class AndroidAcres extends Component {
SpaceshipRamp(),
SpaceshipRail(),
AndroidSpaceship(position: Vector2(-26.5, -28.5)),
AndroidAnimatronic(
children: [
ScoringBehavior(points: Points.twoHundredThousand),
],
)..initialPosition = Vector2(-26, -28.25),
AndroidBumper.a(
children: [
ScoringBehavior(points: Points.twentyThousand),
@ -31,6 +38,13 @@ class AndroidAcres extends Component {
ScoringBehavior(points: Points.twentyThousand),
],
)..initialPosition = Vector2(-20.5, -13.8),
AndroidSpaceshipBonusBehavior(),
],
);
/// Creates [AndroidAcres] without any children.
///
/// This can be used for testing [AndroidAcres]'s behaviors in isolation.
@visibleForTesting
AndroidAcres.test();
}

@ -0,0 +1,27 @@
import 'package:flame/components.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Adds a [GameBonus.androidSpaceship] when [AndroidSpaceship] has a bonus.
class AndroidSpaceshipBonusBehavior extends Component
with HasGameRef<PinballGame>, ParentIsA<AndroidAcres> {
@override
void onMount() {
super.onMount();
final androidSpaceship = parent.firstChild<AndroidSpaceship>()!;
// TODO(alestiago): Refactor subscription management once the following is
// merged:
// https://github.com/flame-engine/flame/pull/1538
androidSpaceship.bloc.stream.listen((state) {
final listenWhen = state == AndroidSpaceshipState.withBonus;
if (!listenWhen) return;
gameRef
.read<GameBloc>()
.add(const BonusActivated(GameBonus.androidSpaceship));
androidSpaceship.bloc.onBonusAwarded();
});
}
}

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

@ -1,10 +1,10 @@
export 'android_acres.dart';
export 'android_acres/android_acres.dart';
export 'bottom_group.dart';
export 'camera_controller.dart';
export 'controlled_ball.dart';
export 'controlled_flipper.dart';
export 'controlled_plunger.dart';
export 'dino_desert.dart';
export 'dino_desert/dino_desert.dart';
export 'drain.dart';
export 'flutter_forest/flutter_forest.dart';
export 'game_flow_controller.dart';

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

@ -0,0 +1,24 @@
import 'package:flame/components.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// Adds a [GameBonus.dinoChomp] when a [Ball] is chomped by the [ChromeDino].
class ChromeDinoBonusBehavior extends Component
with HasGameRef<PinballGame>, ParentIsA<DinoDesert> {
@override
void onMount() {
super.onMount();
final chromeDino = parent.firstChild<ChromeDino>()!;
// TODO(alestiago): Refactor subscription management once the following is
// merged:
// https://github.com/flame-engine/flame/pull/1538
chromeDino.bloc.stream.listen((state) {
final listenWhen = state.status == ChromeDinoStatus.chomping;
if (!listenWhen) return;
gameRef.read<GameBloc>().add(const BonusActivated(GameBonus.dinoChomp));
});
}
}

@ -1,11 +1,13 @@
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/components/dino_desert/behaviors/behaviors.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
/// {@template dino_desert}
/// Area located next to the [Launcher] containing the [ChromeDino] and
/// [DinoWalls].
/// Area located next to the [Launcher] containing the [ChromeDino],
/// [DinoWalls], and the [Slingshots].
/// {@endtemplate}
class DinoDesert extends Component {
/// {@macro dino_desert}
@ -21,8 +23,15 @@ class DinoDesert extends Component {
_BarrierBehindDino(),
DinoWalls(),
Slingshots(),
ChromeDinoBonusBehavior(),
],
);
/// Creates [DinoDesert] without any children.
///
/// This can be used for testing [DinoDesert]'s behaviors in isolation.
@visibleForTesting
DinoDesert.test();
}
class _BarrierBehindDino extends BodyComponent {

@ -3,7 +3,10 @@ import 'package:pinball/game/game.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// When all [DashNestBumper]s are hit at least once, the [GameBonus.dashNest]
/// Bonus obtained at the [FlutterForest].
///
/// When all [DashNestBumper]s are hit at least once three times, the [Signpost]
/// progresses. When the [Signpost] fully progresses, the [GameBonus.dashNest]
/// is awarded, and the [DashNestBumper.main] releases a new [Ball].
class FlutterForestBonusBehavior extends Component
with ParentIsA<FlutterForest>, HasGameRef<PinballGame> {
@ -12,28 +15,36 @@ class FlutterForestBonusBehavior extends Component
super.onMount();
final bumpers = parent.children.whereType<DashNestBumper>();
final signpost = parent.firstChild<Signpost>()!;
final animatronic = parent.firstChild<DashAnimatronic>()!;
final canvas = gameRef.firstChild<ZCanvasComponent>()!;
for (final bumper in bumpers) {
// TODO(alestiago): Refactor subscription management once the following is
// merged:
// https://github.com/flame-engine/flame/pull/1538
bumper.bloc.stream.listen((state) {
final achievedBonus = bumpers.every(
final activatedAllBumpers = bumpers.every(
(bumper) => bumper.bloc.state == DashNestBumperState.active,
);
if (achievedBonus) {
gameRef
.read<GameBloc>()
.add(const BonusActivated(GameBonus.dashNest));
gameRef.firstChild<ZCanvasComponent>()!.add(
ControlledBall.bonus(characterTheme: gameRef.characterTheme)
..initialPosition = Vector2(17.2, -52.7),
);
parent.firstChild<DashAnimatronic>()?.playing = true;
if (activatedAllBumpers) {
signpost.bloc.onProgressed();
for (final bumper in bumpers) {
bumper.bloc.onReset();
}
if (signpost.bloc.isFullyProgressed()) {
gameRef
.read<GameBloc>()
.add(const BonusActivated(GameBonus.dashNest));
canvas.add(
ControlledBall.bonus(characterTheme: gameRef.characterTheme)
..initialPosition = Vector2(29.5, -24.5),
);
animatronic.playing = true;
signpost.bloc.onProgressed();
}
}
});
}

@ -39,6 +39,7 @@ class GameFlowController extends ComponentController<PinballGame>
/// Puts the game on a playing state
void start() {
component.audio.backgroundMusic();
component.firstChild<Backboard>()?.waitingMode();
component.firstChild<CameraController>()?.focusOnGame();
component.overlays.remove(PinballGame.playButtonOverlay);

@ -1,4 +1,3 @@
export 'assets_manager/cubit/assets_manager_cubit.dart';
export 'bloc/game_bloc.dart';
export 'components/components.dart';
export 'game_assets.dart';

@ -38,6 +38,7 @@ extension PinballGameAssetsX on PinballGame {
),
images.load(components.Assets.images.dino.bottomWall.keyName),
images.load(components.Assets.images.dino.topWall.keyName),
images.load(components.Assets.images.dino.topWallTunnel.keyName),
images.load(components.Assets.images.dino.animatronic.head.keyName),
images.load(components.Assets.images.dino.animatronic.mouth.keyName),
images.load(components.Assets.images.dash.animatronic.keyName),

@ -4,10 +4,12 @@ import 'package:flame/game.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/assets_manager/assets_manager.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball/select_character/select_character.dart';
import 'package:pinball/start_game/start_game.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_ui/pinball_ui.dart';
class PinballGamePage extends StatelessWidget {
const PinballGamePage({
@ -71,32 +73,13 @@ class PinballGameView extends StatelessWidget {
final isLoading = context.select(
(AssetsManagerCubit bloc) => bloc.state.progress != 1,
);
return Scaffold(
backgroundColor: Colors.blue,
body: isLoading
? const _PinballGameLoadingView()
: 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,
),
return Container(
decoration: const CrtBackground(),
child: Scaffold(
backgroundColor: PinballColors.transparent,
body: isLoading
? const AssetsLoadingPage()
: PinballGameLoadedView(game: game),
),
);
}

@ -3,8 +3,10 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pinball/gen/gen.dart';
import 'package:pinball/l10n/l10n.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_ui/pinball_ui.dart';
import 'package:platform_helper/platform_helper.dart';
@ -50,10 +52,13 @@ extension on Control {
}
Future<void> showHowToPlayDialog(BuildContext context) {
final audio = context.read<PinballAudio>();
return showDialog<void>(
context: context,
builder: (_) => HowToPlayDialog(),
);
).then((_) {
audio.ioPinballVoiceOver();
});
}
class HowToPlayDialog extends StatefulWidget {

@ -20,7 +20,7 @@
"@flipperControls": {
"description": "Text displayed on the how to play dialog with the flipper controls"
},
"tapAndHoldRocket": "Tap & Hold Rocket",
"tapAndHoldRocket": "Tap Rocket",
"@tapAndHoldRocket": {
"description": "Text displayed on the how to launch on mobile"
},
@ -123,5 +123,13 @@
"footerGoogleIOText": "Google I/O",
"@footerGoogleIOText": {
"description": "Text shown on the footer which mentions Google I/O"
},
"loading": "Loading",
"@loading": {
"description": "Text shown to indicate loading times"
},
"ioPinball": "I/O Pinball",
"@ioPinball": {
"description": "I/O Pinball - Name of the game"
}
}

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
// ignore_for_file: public_member_api_docs
import 'package:flutter/widgets.dart';

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:async';
import 'package:authentication_repository/authentication_repository.dart';

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:async';
import 'package:authentication_repository/authentication_repository.dart';

@ -1,10 +1,3 @@
// Copyright (c) 2021, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'dart:async';
import 'package:authentication_repository/authentication_repository.dart';

@ -3,9 +3,9 @@ import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockFirebaseAuth extends Mock implements FirebaseAuth {}
class _MockFirebaseAuth extends Mock implements FirebaseAuth {}
class MockUserCredential extends Mock implements UserCredential {}
class _MockUserCredential extends Mock implements UserCredential {}
void main() {
late FirebaseAuth firebaseAuth;
@ -14,8 +14,8 @@ void main() {
group('AuthenticationRepository', () {
setUp(() {
firebaseAuth = MockFirebaseAuth();
userCredential = MockUserCredential();
firebaseAuth = _MockFirebaseAuth();
userCredential = _MockUserCredential();
authenticationRepository = AuthenticationRepository(firebaseAuth);
});

@ -5,23 +5,23 @@ import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class MockFirebaseFirestore extends Mock implements FirebaseFirestore {}
class _MockFirebaseFirestore extends Mock implements FirebaseFirestore {}
class MockCollectionReference extends Mock
class _MockCollectionReference extends Mock
implements CollectionReference<Map<String, dynamic>> {}
class MockQuery extends Mock implements Query<Map<String, dynamic>> {}
class _MockQuery extends Mock implements Query<Map<String, dynamic>> {}
class MockQuerySnapshot extends Mock
class _MockQuerySnapshot extends Mock
implements QuerySnapshot<Map<String, dynamic>> {}
class MockQueryDocumentSnapshot extends Mock
class _MockQueryDocumentSnapshot extends Mock
implements QueryDocumentSnapshot<Map<String, dynamic>> {}
class MockDocumentReference extends Mock
class _MockDocumentReference extends Mock
implements DocumentReference<Map<String, dynamic>> {}
class MockDocumentSnapshot extends Mock
class _MockDocumentSnapshot extends Mock
implements DocumentSnapshot<Map<String, dynamic>> {}
void main() {
@ -29,7 +29,7 @@ void main() {
late FirebaseFirestore firestore;
setUp(() {
firestore = MockFirebaseFirestore();
firestore = _MockFirebaseFirestore();
});
test('can be instantiated', () {
@ -70,11 +70,11 @@ void main() {
setUp(() {
leaderboardRepository = LeaderboardRepository(firestore);
collectionReference = MockCollectionReference();
query = MockQuery();
querySnapshot = MockQuerySnapshot();
collectionReference = _MockCollectionReference();
query = _MockQuery();
querySnapshot = _MockQuerySnapshot();
queryDocumentSnapshots = top10Scores.map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'user$score',
@ -119,7 +119,7 @@ void main() {
'playerInitials': 'ABC',
'score': 1500,
};
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(() => querySnapshot.docs).thenReturn([queryDocumentSnapshot]);
when(queryDocumentSnapshot.data)
.thenReturn(top10LeaderboardDataMalformed);
@ -156,12 +156,12 @@ void main() {
setUp(() {
leaderboardRepository = LeaderboardRepository(firestore);
collectionReference = MockCollectionReference();
documentReference = MockDocumentReference();
query = MockQuery();
querySnapshot = MockQuerySnapshot();
collectionReference = _MockCollectionReference();
documentReference = _MockDocumentReference();
query = _MockQuery();
querySnapshot = _MockQuerySnapshot();
queryDocumentSnapshots = leaderboardScores.map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -228,7 +228,7 @@ void main() {
5000
];
final queryDocumentSnapshots = leaderboardScores.map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -248,8 +248,8 @@ void main() {
test(
'throws DeleteLeaderboardException '
'when deleting scores outside the top 10 fails', () async {
final deleteQuery = MockQuery();
final deleteQuerySnapshot = MockQuerySnapshot();
final deleteQuery = _MockQuery();
final deleteQuerySnapshot = _MockQuerySnapshot();
final newScore = LeaderboardEntryData(
playerInitials: 'ABC',
score: 15000,
@ -269,7 +269,7 @@ void main() {
5000,
];
final deleteDocumentSnapshots = [5500, 5000].map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -284,7 +284,7 @@ void main() {
when(() => deleteQuerySnapshot.docs)
.thenReturn(deleteDocumentSnapshots);
final queryDocumentSnapshots = leaderboardScores.map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -310,8 +310,8 @@ void main() {
'saves the new score when there are more than 10 scores in the '
'leaderboard and the new score is higher than the lowest top 10, and '
'deletes the scores that are not in the top 10 anymore', () async {
final deleteQuery = MockQuery();
final deleteQuerySnapshot = MockQuerySnapshot();
final deleteQuery = _MockQuery();
final deleteQuerySnapshot = _MockQuerySnapshot();
final newScore = LeaderboardEntryData(
playerInitials: 'ABC',
score: 15000,
@ -331,7 +331,7 @@ void main() {
5000,
];
final deleteDocumentSnapshots = [5500, 5000].map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -346,7 +346,7 @@ void main() {
when(() => deleteQuerySnapshot.docs)
.thenReturn(deleteDocumentSnapshots);
final queryDocumentSnapshots = leaderboardScores.map((score) {
final queryDocumentSnapshot = MockQueryDocumentSnapshot();
final queryDocumentSnapshot = _MockQueryDocumentSnapshot();
when(queryDocumentSnapshot.data).thenReturn(<String, dynamic>{
'character': 'dash',
'playerInitials': 'AAA',
@ -376,9 +376,9 @@ void main() {
late DocumentSnapshot<Map<String, dynamic>> documentSnapshot;
setUp(() async {
collectionReference = MockCollectionReference();
documentReference = MockDocumentReference();
documentSnapshot = MockDocumentSnapshot();
collectionReference = _MockCollectionReference();
documentReference = _MockDocumentReference();
documentSnapshot = _MockDocumentSnapshot();
leaderboardRepository = LeaderboardRepository(firestore);
when(() => firestore.collection('prohibitedInitials'))

@ -5,16 +5,24 @@
import 'package:flutter/widgets.dart';
class $AssetsMusicGen {
const $AssetsMusicGen();
String get background => 'assets/music/background.mp3';
}
class $AssetsSfxGen {
const $AssetsSfxGen();
String get google => 'assets/sfx/google.ogg';
String get plim => 'assets/sfx/plim.ogg';
String get google => 'assets/sfx/google.mp3';
String get ioPinballVoiceOver => 'assets/sfx/io_pinball_voice_over.mp3';
String get plim => 'assets/sfx/plim.mp3';
}
class Assets {
Assets._();
static const $AssetsMusicGen music = $AssetsMusicGen();
static const $AssetsSfxGen sfx = $AssetsSfxGen();
}

@ -17,6 +17,14 @@ typedef CreateAudioPool = Future<AudioPool> Function(
/// audio
typedef PlaySingleAudio = Future<void> Function(String);
/// Function that defines the contract for looping a single
/// audio
typedef LoopSingleAudio = Future<void> Function(String);
/// Function that defines the contract for pre fetching an
/// audio
typedef PreCacheSingleAudio = Future<void> Function(String);
/// Function that defines the contract for configuring
/// an [AudioCache] instance
typedef ConfigureAudioCache = void Function(AudioCache);
@ -29,9 +37,14 @@ class PinballAudio {
PinballAudio({
CreateAudioPool? createAudioPool,
PlaySingleAudio? playSingleAudio,
LoopSingleAudio? loopSingleAudio,
PreCacheSingleAudio? preCacheSingleAudio,
ConfigureAudioCache? configureAudioCache,
}) : _createAudioPool = createAudioPool ?? AudioPool.create,
_playSingleAudio = playSingleAudio ?? FlameAudio.audioCache.play,
_loopSingleAudio = loopSingleAudio ?? FlameAudio.audioCache.loop,
_preCacheSingleAudio =
preCacheSingleAudio ?? FlameAudio.audioCache.load,
_configureAudioCache = configureAudioCache ??
((AudioCache a) {
a.prefix = '';
@ -41,6 +54,10 @@ class PinballAudio {
final PlaySingleAudio _playSingleAudio;
final LoopSingleAudio _loopSingleAudio;
final PreCacheSingleAudio _preCacheSingleAudio;
final ConfigureAudioCache _configureAudioCache;
late AudioPool _scorePool;
@ -48,11 +65,18 @@ class PinballAudio {
/// Loads the sounds effects into the memory
Future<void> load() async {
_configureAudioCache(FlameAudio.audioCache);
_scorePool = await _createAudioPool(
_prefixFile(Assets.sfx.plim),
maxPlayers: 4,
prefix: '',
);
await Future.wait([
_preCacheSingleAudio(_prefixFile(Assets.sfx.google)),
_preCacheSingleAudio(_prefixFile(Assets.sfx.ioPinballVoiceOver)),
_preCacheSingleAudio(_prefixFile(Assets.music.background)),
]);
}
/// Plays the basic score sound
@ -65,6 +89,16 @@ class PinballAudio {
_playSingleAudio(_prefixFile(Assets.sfx.google));
}
/// Plays the I/O Pinball voice over audio.
void ioPinballVoiceOver() {
_playSingleAudio(_prefixFile(Assets.sfx.ioPinballVoiceOver));
}
/// Plays the background music
void backgroundMusic() {
_loopSingleAudio(_prefixFile(Assets.music.background));
}
String _prefixFile(String file) {
return 'packages/pinball_audio/$file';
}

@ -26,3 +26,4 @@ flutter_gen:
flutter:
assets:
- assets/sfx/
- assets/music/

@ -1,34 +0,0 @@
// ignore_for_file: one_member_abstracts
import 'package:audioplayers/audioplayers.dart';
import 'package:flame_audio/audio_pool.dart';
import 'package:mocktail/mocktail.dart';
abstract class _CreateAudioPoolStub {
Future<AudioPool> onCall(
String sound, {
bool? repeating,
int? maxPlayers,
int? minPlayers,
String? prefix,
});
}
class CreateAudioPoolStub extends Mock implements _CreateAudioPoolStub {}
abstract class _ConfigureAudioCacheStub {
void onCall(AudioCache cache);
}
class ConfigureAudioCacheStub extends Mock implements _ConfigureAudioCacheStub {
}
abstract class _PlaySingleAudioStub {
Future<void> onCall(String url);
}
class PlaySingleAudioStub extends Mock implements _PlaySingleAudioStub {}
class MockAudioPool extends Mock implements AudioPool {}
class MockAudioCache extends Mock implements AudioCache {}

@ -1,50 +1,92 @@
// ignore_for_file: prefer_const_constructors
// ignore_for_file: prefer_const_constructors, one_member_abstracts
import 'package:audioplayers/audioplayers.dart';
import 'package:flame_audio/audio_pool.dart';
import 'package:flame_audio/flame_audio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_audio/gen/assets.gen.dart';
import 'package:pinball_audio/pinball_audio.dart';
import '../helpers/helpers.dart';
class _MockAudioPool extends Mock implements AudioPool {}
class _MockAudioCache extends Mock implements AudioCache {}
class _MockCreateAudioPool extends Mock {
Future<AudioPool> onCall(
String sound, {
bool? repeating,
int? maxPlayers,
int? minPlayers,
String? prefix,
});
}
class _MockConfigureAudioCache extends Mock {
void onCall(AudioCache cache);
}
class _MockPlaySingleAudio extends Mock {
Future<void> onCall(String url);
}
class _MockLoopSingleAudio extends Mock {
Future<void> onCall(String url);
}
abstract class _PreCacheSingleAudio {
Future<void> onCall(String url);
}
class _MockPreCacheSingleAudio extends Mock implements _PreCacheSingleAudio {}
void main() {
group('PinballAudio', () {
test('can be instantiated', () {
expect(PinballAudio(), isNotNull);
});
late CreateAudioPoolStub createAudioPool;
late ConfigureAudioCacheStub configureAudioCache;
late PlaySingleAudioStub playSingleAudio;
late _MockCreateAudioPool createAudioPool;
late _MockConfigureAudioCache configureAudioCache;
late _MockPlaySingleAudio playSingleAudio;
late _MockLoopSingleAudio loopSingleAudio;
late _PreCacheSingleAudio preCacheSingleAudio;
late PinballAudio audio;
setUpAll(() {
registerFallbackValue(MockAudioCache());
registerFallbackValue(_MockAudioCache());
});
setUp(() {
createAudioPool = CreateAudioPoolStub();
createAudioPool = _MockCreateAudioPool();
when(
() => createAudioPool.onCall(
any(),
maxPlayers: any(named: 'maxPlayers'),
prefix: any(named: 'prefix'),
),
).thenAnswer((_) async => MockAudioPool());
).thenAnswer((_) async => _MockAudioPool());
configureAudioCache = ConfigureAudioCacheStub();
configureAudioCache = _MockConfigureAudioCache();
when(() => configureAudioCache.onCall(any())).thenAnswer((_) {});
playSingleAudio = PlaySingleAudioStub();
playSingleAudio = _MockPlaySingleAudio();
when(() => playSingleAudio.onCall(any())).thenAnswer((_) async {});
loopSingleAudio = _MockLoopSingleAudio();
when(() => loopSingleAudio.onCall(any())).thenAnswer((_) async {});
preCacheSingleAudio = _MockPreCacheSingleAudio();
when(() => preCacheSingleAudio.onCall(any())).thenAnswer((_) async {});
audio = PinballAudio(
configureAudioCache: configureAudioCache.onCall,
createAudioPool: createAudioPool.onCall,
playSingleAudio: playSingleAudio.onCall,
loopSingleAudio: loopSingleAudio.onCall,
preCacheSingleAudio: preCacheSingleAudio.onCall,
);
});
test('can be instantiated', () {
expect(PinballAudio(), isNotNull);
});
group('load', () {
test('creates the score pool', () async {
await audio.load();
@ -69,16 +111,35 @@ void main() {
audio = PinballAudio(
createAudioPool: createAudioPool.onCall,
playSingleAudio: playSingleAudio.onCall,
preCacheSingleAudio: preCacheSingleAudio.onCall,
);
await audio.load();
expect(FlameAudio.audioCache.prefix, equals(''));
});
test('pre cache the assets', () async {
await audio.load();
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/sfx/google.mp3'),
).called(1);
verify(
() => preCacheSingleAudio.onCall(
'packages/pinball_audio/assets/sfx/io_pinball_voice_over.mp3',
),
).called(1);
verify(
() => preCacheSingleAudio
.onCall('packages/pinball_audio/assets/music/background.mp3'),
).called(1);
});
});
group('score', () {
test('plays the score sound pool', () async {
final audioPool = MockAudioPool();
final audioPool = _MockAudioPool();
when(audioPool.start).thenAnswer((_) async => () {});
when(
() => createAudioPool.onCall(
@ -106,5 +167,30 @@ void main() {
).called(1);
});
});
group('ioPinballVoiceOver', () {
test('plays the correct file', () async {
await audio.load();
audio.ioPinballVoiceOver();
verify(
() => playSingleAudio.onCall(
'packages/pinball_audio/${Assets.sfx.ioPinballVoiceOver}',
),
).called(1);
});
});
group('backgroundMusic', () {
test('plays the correct file', () async {
await audio.load();
audio.backgroundMusic();
verify(
() => loopSingleAudio
.onCall('packages/pinball_audio/${Assets.music.background}'),
).called(1);
});
});
});
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 588 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 45 KiB

@ -124,6 +124,10 @@ class $AssetsImagesDinoGen {
AssetGenImage get bottomWall =>
const AssetGenImage('assets/images/dino/bottom-wall.png');
/// File path: assets/images/dino/top-wall-tunnel.png
AssetGenImage get topWallTunnel =>
const AssetGenImage('assets/images/dino/top-wall-tunnel.png');
/// File path: assets/images/dino/top-wall.png
AssetGenImage get topWall =>
const AssetGenImage('assets/images/dino/top-wall.png');

@ -0,0 +1,71 @@
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
/// {@template android_animatronic}
/// Animated Android that sits on top of the [AndroidSpaceship].
/// {@endtemplate}
class AndroidAnimatronic extends BodyComponent
with InitialPosition, Layered, ZIndex {
/// {@macro android_animatronic}
AndroidAnimatronic({Iterable<Component>? children})
: super(
children: [
_AndroidAnimatronicSpriteAnimationComponent(),
...?children,
],
renderBody: false,
) {
layer = Layer.spaceship;
zIndex = ZIndexes.androidHead;
}
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: 3.1,
minorRadius: 2,
)..rotate(1.4);
final bodyDef = BodyDef(position: initialPosition);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _AndroidAnimatronicSpriteAnimationComponent
extends SpriteAnimationComponent with HasGameRef {
_AndroidAnimatronicSpriteAnimationComponent()
: super(
anchor: Anchor.center,
position: Vector2(-0.24, -2.6),
);
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.android.spaceship.animatronic.keyName,
);
const amountPerRow = 18;
const amountPerColumn = 4;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
animation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn,
amountPerRow: amountPerRow,
stepTime: 1 / 24,
textureSize: textureSize,
),
);
}
}

@ -5,17 +5,25 @@ import 'dart:math' as math;
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_spaceship/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/android_spaceship_cubit.dart';
class AndroidSpaceship extends Component {
AndroidSpaceship({required Vector2 position})
: super(
AndroidSpaceship({
required Vector2 position,
}) : bloc = AndroidSpaceshipCubit(),
super(
children: [
_SpaceshipSaucer()..initialPosition = position,
_SpaceshipSaucerSpriteAnimationComponent()..position = position,
_LightBeamSpriteComponent()..position = position + Vector2(2.5, 5),
_AndroidHead()..initialPosition = position + Vector2(0.5, 0.25),
AndroidSpaceshipEntrance(
children: [AndroidSpaceshipEntranceBallContactBehavior()],
),
_SpaceshipHole(
outsideLayer: Layer.spaceshipExitRail,
outsidePriority: ZIndexes.ballOnSpaceshipRail,
@ -26,6 +34,27 @@ class AndroidSpaceship extends Component {
)..initialPosition = position - Vector2(-7.5, -1.1),
],
);
/// Creates an [AndroidSpaceship] without any children.
///
/// This can be used for testing [AndroidSpaceship]'s behaviors in isolation.
// TODO(alestiago): Refactor injecting bloc once the following is merged:
// https://github.com/flame-engine/flame/pull/1538
@visibleForTesting
AndroidSpaceship.test({
required this.bloc,
Iterable<Component>? children,
}) : super(children: children);
// TODO(alestiago): Consider refactoring once the following is merged:
// https://github.com/flame-engine/flame/pull/1538
final AndroidSpaceshipCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
}
class _SpaceshipSaucer extends BodyComponent with InitialPosition, Layered {
@ -123,62 +152,32 @@ class _LightBeamSpriteComponent extends SpriteComponent
}
}
class _AndroidHead extends BodyComponent with InitialPosition, Layered, ZIndex {
_AndroidHead()
class AndroidSpaceshipEntrance extends BodyComponent
with ParentIsA<AndroidSpaceship>, Layered {
AndroidSpaceshipEntrance({Iterable<Component>? children})
: super(
children: [_AndroidHeadSpriteAnimationComponent()],
children: children,
renderBody: false,
) {
layer = Layer.spaceship;
zIndex = ZIndexes.androidHead;
}
@override
Body createBody() {
final shape = EllipseShape(
center: Vector2.zero(),
majorRadius: 3.1,
minorRadius: 2,
)..rotate(1.4);
final bodyDef = BodyDef(position: initialPosition);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _AndroidHeadSpriteAnimationComponent extends SpriteAnimationComponent
with HasGameRef {
_AndroidHeadSpriteAnimationComponent()
: super(
anchor: Anchor.center,
position: Vector2(-0.24, -2.6),
);
@override
Future<void> onLoad() async {
await super.onLoad();
final spriteSheet = gameRef.images.fromCache(
Assets.images.android.spaceship.animatronic.keyName,
final shape = PolygonShape()
..setAsBox(
2,
0.1,
Vector2(-27.4, -37.2),
-0.12,
);
final fixtureDef = FixtureDef(
shape,
isSensor: true,
);
final bodyDef = BodyDef();
const amountPerRow = 18;
const amountPerColumn = 4;
final textureSize = Vector2(
spriteSheet.width / amountPerRow,
spriteSheet.height / amountPerColumn,
);
size = textureSize / 10;
animation = SpriteAnimation.fromFrameData(
spriteSheet,
SpriteAnimationData.sequenced(
amount: amountPerRow * amountPerColumn,
amountPerRow: amountPerRow,
stepTime: 1 / 24,
textureSize: textureSize,
),
);
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}

@ -0,0 +1,16 @@
// ignore_for_file: public_member_api_docs
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
class AndroidSpaceshipEntranceBallContactBehavior
extends ContactBehavior<AndroidSpaceshipEntrance> {
@override
void beginContact(Object other, Contact contact) {
super.beginContact(other, contact);
if (other is! Ball) return;
parent.parent.bloc.onBallEntered();
}
}

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

@ -0,0 +1,13 @@
// ignore_for_file: public_member_api_docs
import 'package:bloc/bloc.dart';
part 'android_spaceship_state.dart';
class AndroidSpaceshipCubit extends Cubit<AndroidSpaceshipState> {
AndroidSpaceshipCubit() : super(AndroidSpaceshipState.withoutBonus);
void onBallEntered() => emit(AndroidSpaceshipState.withBonus);
void onBonusAwarded() => emit(AndroidSpaceshipState.withoutBonus);
}

@ -0,0 +1,8 @@
// ignore_for_file: public_member_api_docs
part of 'android_spaceship_cubit.dart';
enum AndroidSpaceshipState {
withoutBonus,
withBonus,
}

@ -18,10 +18,17 @@ class ChromeDinoCubit extends Cubit<ChromeDinoState> {
}
void onChomp(Ball ball) {
emit(state.copyWith(status: ChromeDinoStatus.chomping, ball: ball));
if (ball != state.ball) {
emit(state.copyWith(status: ChromeDinoStatus.chomping, ball: ball));
}
}
void onSpit() {
emit(state.copyWith(status: ChromeDinoStatus.idle));
emit(
ChromeDinoState(
status: ChromeDinoStatus.idle,
isMouthOpen: state.isMouthOpen,
),
);
}
}

@ -1,5 +1,6 @@
export 'android_animatronic.dart';
export 'android_bumper/android_bumper.dart';
export 'android_spaceship.dart';
export 'android_spaceship/android_spaceship.dart';
export 'backboard/backboard.dart';
export 'ball.dart';
export 'baseboard.dart';
@ -27,7 +28,7 @@ export 'plunger.dart';
export 'rocket.dart';
export 'score_component.dart';
export 'shapes/shapes.dart';
export 'signpost.dart';
export 'signpost/signpost.dart';
export 'slingshot.dart';
export 'spaceship_rail.dart';
export 'spaceship_ramp.dart';

@ -23,59 +23,70 @@ class DinoWalls extends Component {
/// {@template dino_top_wall}
/// Wall segment located above [ChromeDino].
/// {@endtemplate}
class _DinoTopWall extends BodyComponent with InitialPosition, ZIndex {
class _DinoTopWall extends BodyComponent with InitialPosition {
///{@macro dino_top_wall}
_DinoTopWall()
: super(
children: [_DinoTopWallSpriteComponent()],
children: [
_DinoTopWallSpriteComponent(),
_DinoTopWallTunnelSpriteComponent(),
],
renderBody: false,
) {
zIndex = ZIndexes.dinoTopWall;
}
);
List<FixtureDef> _createFixtureDefs() {
final topStraightShape = EdgeShape()
final topEdgeShape = EdgeShape()
..set(
Vector2(28.65, -34.3),
Vector2(29.5, -34.3),
Vector2(29.25, -35.27),
Vector2(28.4, -34.77),
);
final topCurveShape = BezierCurveShape(
controlPoints: [
topStraightShape.vertex1,
Vector2(18.8, -26.2),
Vector2(26.6, -20.2),
topEdgeShape.vertex2,
Vector2(21.35, -28.72),
Vector2(23.45, -24.62),
],
);
final middleCurveShape = BezierCurveShape(
controlPoints: [
final tunnelTopEdgeShape = EdgeShape()
..set(
topCurveShape.vertices.last,
Vector2(27.8, -19.3),
Vector2(26.8, -18.7),
],
);
Vector2(30.35, -27.32),
);
final bottomCurveShape = BezierCurveShape(
controlPoints: [
middleCurveShape.vertices.last,
Vector2(23, -14.2),
Vector2(27, -14.2),
],
);
final tunnelBottomEdgeShape = EdgeShape()
..set(
Vector2(30.75, -23.17),
Vector2(25.45, -21.22),
);
final bottomStraightShape = EdgeShape()
final middleEdgeShape = EdgeShape()
..set(
bottomCurveShape.vertices.last,
Vector2(31, -13.7),
tunnelBottomEdgeShape.vertex2,
Vector2(27.45, -19.32),
);
final bottomEdgeShape = EdgeShape()
..set(
middleEdgeShape.vertex2,
Vector2(24.65, -15.02),
);
final undersideEdgeShape = EdgeShape()
..set(
bottomEdgeShape.vertex2,
Vector2(31.75, -13.77),
);
return [
FixtureDef(topStraightShape),
FixtureDef(topEdgeShape),
FixtureDef(topCurveShape),
FixtureDef(middleCurveShape),
FixtureDef(bottomCurveShape),
FixtureDef(bottomStraightShape),
FixtureDef(tunnelTopEdgeShape),
FixtureDef(tunnelBottomEdgeShape),
FixtureDef(middleEdgeShape),
FixtureDef(bottomEdgeShape),
FixtureDef(undersideEdgeShape),
];
}
@ -93,7 +104,15 @@ class _DinoTopWall extends BodyComponent with InitialPosition, ZIndex {
}
}
class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef {
class _DinoTopWallSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_DinoTopWallSpriteComponent()
: super(
position: Vector2(22.75, -38.07),
) {
zIndex = ZIndexes.dinoTopWall;
}
@override
Future<void> onLoad() async {
await super.onLoad();
@ -104,7 +123,26 @@ class _DinoTopWallSpriteComponent extends SpriteComponent with HasGameRef {
);
this.sprite = sprite;
size = sprite.originalSize / 10;
position = Vector2(22.8, -38.1);
}
}
class _DinoTopWallTunnelSpriteComponent extends SpriteComponent
with HasGameRef, ZIndex {
_DinoTopWallTunnelSpriteComponent()
: super(position: Vector2(23.31, -26.01)) {
zIndex = ZIndexes.dinoTopWallTunnel;
}
@override
Future<void> onLoad() async {
await super.onLoad();
final sprite = Sprite(
gameRef.images.fromCache(
Assets.images.dino.topWallTunnel.keyName,
),
);
this.sprite = sprite;
size = sprite.originalSize / 10;
}
}
@ -122,7 +160,7 @@ class _DinoBottomWall extends BodyComponent with InitialPosition, ZIndex {
}
List<FixtureDef> _createFixtureDefs() {
final topStraightShape = EdgeShape()
final topEdgeShape = EdgeShape()
..set(
Vector2(32.4, -8.8),
Vector2(25, -7.7),
@ -130,29 +168,29 @@ class _DinoBottomWall extends BodyComponent with InitialPosition, ZIndex {
final topLeftCurveShape = BezierCurveShape(
controlPoints: [
topStraightShape.vertex2,
topEdgeShape.vertex2,
Vector2(21.8, -7),
Vector2(29.8, 13.8),
],
);
final bottomLeftStraightShape = EdgeShape()
final bottomLeftEdgeShape = EdgeShape()
..set(
topLeftCurveShape.vertices.last,
Vector2(31.9, 44.1),
);
final bottomStraightShape = EdgeShape()
final bottomEdgeShape = EdgeShape()
..set(
bottomLeftStraightShape.vertex2,
bottomLeftEdgeShape.vertex2,
Vector2(37.8, 44.1),
);
return [
FixtureDef(topStraightShape),
FixtureDef(topEdgeShape),
FixtureDef(topLeftCurveShape),
FixtureDef(bottomLeftStraightShape),
FixtureDef(bottomStraightShape),
FixtureDef(bottomLeftEdgeShape),
FixtureDef(bottomEdgeShape),
];
}

@ -1,101 +0,0 @@
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart';
import 'package:pinball_components/pinball_components.dart';
/// Represents the [Signpost]'s current [Sprite] state.
@visibleForTesting
enum SignpostSpriteState {
/// Signpost with no active dashes.
inactive,
/// Signpost with a single sign of active dashes.
active1,
/// Signpost with two signs of active dashes.
active2,
/// Signpost with all signs of active dashes.
active3,
}
extension on SignpostSpriteState {
String get path {
switch (this) {
case SignpostSpriteState.inactive:
return Assets.images.signpost.inactive.keyName;
case SignpostSpriteState.active1:
return Assets.images.signpost.active1.keyName;
case SignpostSpriteState.active2:
return Assets.images.signpost.active2.keyName;
case SignpostSpriteState.active3:
return Assets.images.signpost.active3.keyName;
}
}
SignpostSpriteState get next {
return SignpostSpriteState
.values[(index + 1) % SignpostSpriteState.values.length];
}
}
/// {@template signpost}
/// A sign, found in the Flutter Forest.
///
/// Lights up a new sign whenever all three [DashNestBumper]s are hit.
/// {@endtemplate}
class Signpost extends BodyComponent with InitialPosition {
/// {@macro signpost}
Signpost({
Iterable<Component>? children,
}) : super(
renderBody: false,
children: [
_SignpostSpriteComponent(),
...?children,
],
);
/// Forwards the sprite to the next [SignpostSpriteState].
///
/// If the current state is the last one it cycles back to the initial state.
void progress() => firstChild<_SignpostSpriteComponent>()!.progress();
@override
Body createBody() {
final shape = CircleShape()..radius = 0.25;
final fixtureDef = FixtureDef(shape);
final bodyDef = BodyDef(
position: initialPosition,
);
return world.createBody(bodyDef)..createFixture(fixtureDef);
}
}
class _SignpostSpriteComponent extends SpriteGroupComponent<SignpostSpriteState>
with HasGameRef {
_SignpostSpriteComponent()
: super(
anchor: Anchor.bottomCenter,
position: Vector2(0.65, 0.45),
);
void progress() => current = current?.next;
@override
Future<void> onLoad() async {
await super.onLoad();
final sprites = <SignpostSpriteState, Sprite>{};
this.sprites = sprites;
for (final spriteState in SignpostSpriteState.values) {
sprites[spriteState] = Sprite(
gameRef.images.fromCache(spriteState.path),
);
}
current = SignpostSpriteState.inactive;
size = sprites[current]!.originalSize / 10;
}
}

@ -0,0 +1,18 @@
// ignore_for_file: public_member_api_docs
import 'package:bloc/bloc.dart';
part 'signpost_state.dart';
class SignpostCubit extends Cubit<SignpostState> {
SignpostCubit() : super(SignpostState.inactive);
void onProgressed() {
final index = SignpostState.values.indexOf(state);
emit(
SignpostState.values[(index + 1) % SignpostState.values.length],
);
}
bool isFullyProgressed() => state == SignpostState.active3;
}

@ -0,0 +1,17 @@
// ignore_for_file: public_member_api_docs
part of 'signpost_cubit.dart';
enum SignpostState {
/// Signpost with no active eggs.
inactive,
/// Signpost with a single sign of lit up eggs.
active1,
/// Signpost with two signs of lit up eggs.
active2,
/// Signpost with all signs of lit up eggs.
active3,
}

@ -0,0 +1,109 @@
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/foundation.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
export 'cubit/signpost_cubit.dart';
/// {@template signpost}
/// A sign, found in the Flutter Forest.
///
/// Lights up a new sign whenever all three [DashNestBumper]s are hit.
/// {@endtemplate}
class Signpost extends BodyComponent with InitialPosition {
/// {@macro signpost}
Signpost({
Iterable<Component>? children,
}) : this._(
children: children,
bloc: SignpostCubit(),
);
Signpost._({
Iterable<Component>? children,
required this.bloc,
}) : super(
renderBody: false,
children: [
_SignpostSpriteComponent(
current: bloc.state,
),
...?children,
],
);
/// Creates a [Signpost] without any children.
///
/// This can be used for testing [Signpost]'s behaviors in isolation.
// TODO(alestiago): Refactor injecting bloc once the following is merged:
// https://github.com/flame-engine/flame/pull/1538
@visibleForTesting
Signpost.test({
required this.bloc,
});
// TODO(alestiago): Consider refactoring once the following is merged:
// https://github.com/flame-engine/flame/pull/1538
// ignore: public_member_api_docs
final SignpostCubit bloc;
@override
void onRemove() {
bloc.close();
super.onRemove();
}
@override
Body createBody() {
final shape = CircleShape()..radius = 0.25;
final bodyDef = BodyDef(
position: initialPosition,
);
return world.createBody(bodyDef)..createFixtureFromShape(shape);
}
}
class _SignpostSpriteComponent extends SpriteGroupComponent<SignpostState>
with HasGameRef, ParentIsA<Signpost> {
_SignpostSpriteComponent({
required SignpostState current,
}) : super(
anchor: Anchor.bottomCenter,
position: Vector2(0.65, 0.45),
current: current,
);
@override
Future<void> onLoad() async {
await super.onLoad();
parent.bloc.stream.listen((state) => current = state);
final sprites = <SignpostState, Sprite>{};
this.sprites = sprites;
for (final spriteState in SignpostState.values) {
sprites[spriteState] = Sprite(
gameRef.images.fromCache(spriteState.path),
);
}
current = SignpostState.inactive;
size = sprites[current]!.originalSize / 10;
}
}
extension on SignpostState {
String get path {
switch (this) {
case SignpostState.inactive:
return Assets.images.signpost.inactive.keyName;
case SignpostState.active1:
return Assets.images.signpost.active1.keyName;
case SignpostState.active2:
return Assets.images.signpost.active2.keyName;
case SignpostState.active3:
return Assets.images.signpost.active3.keyName;
}
}
}

@ -53,6 +53,8 @@ abstract class ZIndexes {
static const dinoTopWall = _above + ballOnBoard;
static const dinoTopWallTunnel = _below + ballOnBoard;
static const dino = _above + dinoTopWall;
static const dinoBottomWall = _above + dino;

@ -1,9 +1,3 @@
// Copyright (c) 2022, Very Good Ventures
// https://verygood.ventures
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
import 'package:dashbook/dashbook.dart';
import 'package:flutter/material.dart';
import 'package:sandbox/stories/stories.dart';
@ -14,19 +8,17 @@ void main() {
addBallStories(dashbook);
addLayerStories(dashbook);
addEffectsStories(dashbook);
addChromeDinoStories(dashbook);
addFlutterForestStories(dashbook);
addBottomGroupStories(dashbook);
addPlungerStories(dashbook);
addSlingshotStories(dashbook);
addSparkyScorchStories(dashbook);
addAndroidAcresStories(dashbook);
addDinoDesertStories(dashbook);
addBottomGroupStories(dashbook);
addPlungerStories(dashbook);
addBoundariesStories(dashbook);
addGoogleWordStories(dashbook);
addLaunchRampStories(dashbook);
addScoreStories(dashbook);
addBackboardStories(dashbook);
addDinoWallStories(dashbook);
addMultiballStories(dashbook);
addMultipliersStories(dashbook);

@ -17,7 +17,7 @@ class AndroidSpaceshipGame extends BallGame {
);
static const description = '''
Shows how the AndroidSpaceship is rendered.
Shows how the AndroidSpaceship and AndroidAnimatronic are rendered.
- Activate the "trace" parameter to overlay the body.
- Tap anywhere on the screen to spawn a Ball into the game.
@ -28,8 +28,11 @@ class AndroidSpaceshipGame extends BallGame {
await super.onLoad();
camera.followVector2(Vector2.zero());
await add(
AndroidSpaceship(position: Vector2.zero()),
await addAll(
[
AndroidSpaceship(position: Vector2.zero()),
AndroidAnimatronic(),
],
);
await traceAllBodies();

@ -1,11 +0,0 @@
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/chrome_dino/chrome_dino_game.dart';
void addChromeDinoStories(Dashbook dashbook) {
dashbook.storiesOf('Chrome Dino').addGame(
title: 'Traced',
description: ChromeDinoGame.description,
gameBuilder: (_) => ChromeDinoGame(),
);
}

@ -4,8 +4,8 @@ import 'package:flame/input.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class DinoWallGame extends BallGame {
DinoWallGame() : super();
class DinoWallsGame extends BallGame {
DinoWallsGame() : super();
static const description = '''
Shows how DinoWalls are rendered.
@ -20,6 +20,7 @@ class DinoWallGame extends BallGame {
await images.loadAll([
Assets.images.dino.topWall.keyName,
Assets.images.dino.topWallTunnel.keyName,
Assets.images.dino.bottomWall.keyName,
]);

@ -2,8 +2,8 @@ import 'package:flame/extensions.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:sandbox/stories/ball/basic_ball_game.dart';
class SlingshotGame extends BallGame {
SlingshotGame()
class SlingshotsGame extends BallGame {
SlingshotsGame()
: super(
imagesFileNames: [
Assets.images.slingshot.upper.keyName,

@ -0,0 +1,24 @@
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/dino_desert/chrome_dino_game.dart';
import 'package:sandbox/stories/dino_desert/dino_walls_game.dart';
import 'package:sandbox/stories/dino_desert/slingshots_game.dart';
void addDinoDesertStories(Dashbook dashbook) {
dashbook.storiesOf('Dino Desert')
..addGame(
title: 'Chrome Dino',
description: ChromeDinoGame.description,
gameBuilder: (_) => ChromeDinoGame(),
)
..addGame(
title: 'Dino Walls',
description: DinoWallsGame.description,
gameBuilder: (_) => DinoWallsGame(),
)
..addGame(
title: 'Slingshots',
description: SlingshotsGame.description,
gameBuilder: (_) => SlingshotsGame(),
);
}

@ -1,11 +0,0 @@
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/dino_wall/dino_wall_game.dart';
void addDinoWallStories(Dashbook dashbook) {
dashbook.storiesOf('DinoWall').addGame(
title: 'Traced',
description: DinoWallGame.description,
gameBuilder: (_) => DinoWallGame(),
);
}

@ -34,6 +34,6 @@ class SignpostGame extends BallGame {
@override
void onTap() {
super.onTap();
firstChild<Signpost>()!.progress();
firstChild<Signpost>()!.bloc.onProgressed();
}
}

@ -1,11 +0,0 @@
import 'package:dashbook/dashbook.dart';
import 'package:sandbox/common/common.dart';
import 'package:sandbox/stories/slingshot/slingshot_game.dart';
void addSlingshotStories(Dashbook dashbook) {
dashbook.storiesOf('Slingshots').addGame(
title: 'Traced',
description: SlingshotGame.description,
gameBuilder: (_) => SlingshotGame(),
);
}

@ -3,8 +3,7 @@ export 'backboard/stories.dart';
export 'ball/stories.dart';
export 'bottom_group/stories.dart';
export 'boundaries/stories.dart';
export 'chrome_dino/stories.dart';
export 'dino_wall/stories.dart';
export 'dino_desert/stories.dart';
export 'effects/stories.dart';
export 'flutter_forest/stories.dart';
export 'google_word/stories.dart';
@ -14,5 +13,4 @@ export 'multiball/stories.dart';
export 'multipliers/stories.dart';
export 'plunger/stories.dart';
export 'score/stories.dart';
export 'slingshot/stories.dart';
export 'sparky_scorch/stories.dart';

@ -1,2 +1 @@
export 'mocks.dart';
export 'test_game.dart';

@ -1,32 +0,0 @@
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
class MockFilter extends Mock implements Filter {}
class MockFixture extends Mock implements Fixture {}
class MockBody extends Mock implements Body {}
class MockBall extends Mock implements Ball {}
class MockGame extends Mock implements Forge2DGame {}
class MockContact extends Mock implements Contact {}
class MockComponent extends Mock implements Component {}
class MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
class MockGoogleLetterCubit extends Mock implements GoogleLetterCubit {}
class MockSparkyBumperCubit extends Mock implements SparkyBumperCubit {}
class MockDashNestBumperCubit extends Mock implements DashNestBumperCubit {}
class MockMultiballCubit extends Mock implements MultiballCubit {}
class MockMultiplierCubit extends Mock implements MultiplierCubit {}
class MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}

@ -0,0 +1,70 @@
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import '../../helpers/helpers.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final asset = Assets.images.android.spaceship.animatronic.keyName;
final flameTester = FlameTester(() => TestGame([asset]));
group('AndroidAnimatronic', () {
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.load(asset);
await game.ensureAdd(AndroidAnimatronic());
game.camera.followVector2(Vector2.zero());
await tester.pump();
},
verify: (game, tester) async {
final animationDuration = game
.firstChild<AndroidAnimatronic>()!
.firstChild<SpriteAnimationComponent>()!
.animation!
.totalDuration();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_animatronic/start.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_animatronic/middle.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_animatronic/end.png'),
);
},
);
flameTester.test(
'loads correctly',
(game) async {
final androidAnimatronic = AndroidAnimatronic();
await game.ensureAdd(androidAnimatronic);
expect(game.contains(androidAnimatronic), isTrue);
},
);
flameTester.test('adds new children', (game) async {
final component = Component();
final androidAnimatronic = AndroidAnimatronic(
children: [component],
);
await game.ensureAdd(androidAnimatronic);
expect(androidAnimatronic.children, contains(component));
});
});
}

@ -11,6 +11,8 @@ import 'package:pinball_components/src/components/bumping_behavior.dart';
import '../../../helpers/helpers.dart';
class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
@ -46,7 +48,7 @@ void main() {
// https://github.com/flame-engine/flame/pull/1538
// ignore: public_member_api_docs
flameTester.test('closes bloc when removed', (game) async {
final bloc = MockAndroidBumperCubit();
final bloc = _MockAndroidBumperCubit();
whenListen(
bloc,
const Stream<AndroidBumperState>.empty(),

@ -1,6 +1,7 @@
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
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';
@ -9,6 +10,12 @@ import 'package:pinball_components/src/components/android_bumper/behaviors/behav
import '../../../../helpers/helpers.dart';
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -27,7 +34,7 @@ void main() {
'beginContact emits onBallContacted when contacts with a ball',
(game) async {
final behavior = AndroidBumperBallContactBehavior();
final bloc = MockAndroidBumperCubit();
final bloc = _MockAndroidBumperCubit();
whenListen(
bloc,
const Stream<AndroidBumperState>.empty(),
@ -38,7 +45,7 @@ void main() {
await androidBumper.add(behavior);
await game.ensureAdd(androidBumper);
behavior.beginContact(MockBall(), MockContact());
behavior.beginContact(_MockBall(), _MockContact());
verify(androidBumper.bloc.onBallContacted).called(1);
},

@ -9,6 +9,8 @@ import 'package:pinball_components/src/components/android_bumper/behaviors/behav
import '../../../../helpers/helpers.dart';
class _MockAndroidBumperCubit extends Mock implements AndroidBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -20,7 +22,7 @@ void main() {
'calls onBlinked after 0.05 seconds when dimmed',
setUp: (game, tester) async {
final behavior = AndroidBumperBlinkingBehavior();
final bloc = MockAndroidBumperCubit();
final bloc = _MockAndroidBumperCubit();
final streamController = StreamController<AndroidBumperState>();
whenListen(
bloc,

@ -0,0 +1,109 @@
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_spaceship/behaviors/behaviors.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../../helpers/helpers.dart';
class _MockAndroidSpaceshipCubit extends Mock implements AndroidSpaceshipCubit {
}
void main() {
group('AndroidSpaceship', () {
final assets = [
Assets.images.android.spaceship.saucer.keyName,
Assets.images.android.spaceship.lightBeam.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
flameTester.test('loads correctly', (game) async {
final component = AndroidSpaceship(position: Vector2.zero());
await game.ensureAdd(component);
expect(game.contains(component), isTrue);
});
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.loadAll(assets);
final canvas = ZCanvasComponent(
children: [AndroidSpaceship(position: Vector2.zero())],
);
await game.ensureAdd(canvas);
game.camera.followVector2(Vector2.zero());
await game.ready();
await tester.pump();
},
verify: (game, tester) async {
const goldenFilePath = '../golden/android_spaceship/';
final animationDuration = game
.descendants()
.whereType<SpriteAnimationComponent>()
.single
.animation!
.totalDuration();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('${goldenFilePath}start.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('${goldenFilePath}middle.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('${goldenFilePath}end.png'),
);
},
);
// TODO(alestiago): Consider refactoring once the following is merged:
// https://github.com/flame-engine/flame/pull/1538
// ignore: public_member_api_docs
flameTester.test('closes bloc when removed', (game) async {
final bloc = _MockAndroidSpaceshipCubit();
whenListen(
bloc,
const Stream<AndroidSpaceshipState>.empty(),
initialState: AndroidSpaceshipState.withoutBonus,
);
when(bloc.close).thenAnswer((_) async {});
final androidSpaceship = AndroidSpaceship.test(bloc: bloc);
await game.ensureAdd(androidSpaceship);
game.remove(androidSpaceship);
await game.ready();
verify(bloc.close).called(1);
});
flameTester.test(
'AndroidSpaceshipEntrance has an '
'AndroidSpaceshipEntranceBallContactBehavior', (game) async {
final androidSpaceship = AndroidSpaceship(position: Vector2.zero());
await game.ensureAdd(androidSpaceship);
final androidSpaceshipEntrance =
androidSpaceship.firstChild<AndroidSpaceshipEntrance>();
expect(
androidSpaceshipEntrance!.children
.whereType<AndroidSpaceshipEntranceBallContactBehavior>()
.single,
isNotNull,
);
});
});
}

@ -0,0 +1,60 @@
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_components/src/components/android_spaceship/behaviors/behaviors.dart';
import '../../../../helpers/helpers.dart';
class _MockAndroidSpaceshipCubit extends Mock implements AndroidSpaceshipCubit {
}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
group(
'AndroidSpaceshipEntranceBallContactBehavior',
() {
test('can be instantiated', () {
expect(
AndroidSpaceshipEntranceBallContactBehavior(),
isA<AndroidSpaceshipEntranceBallContactBehavior>(),
);
});
flameTester.test(
'beginContact calls onBallEntered when entrance contacts with a ball',
(game) async {
final behavior = AndroidSpaceshipEntranceBallContactBehavior();
final bloc = _MockAndroidSpaceshipCubit();
whenListen(
bloc,
const Stream<AndroidSpaceshipState>.empty(),
initialState: AndroidSpaceshipState.withoutBonus,
);
final entrance = AndroidSpaceshipEntrance();
final androidSpaceship = AndroidSpaceship.test(
bloc: bloc,
children: [entrance],
);
await entrance.add(behavior);
await game.ensureAdd(androidSpaceship);
behavior.beginContact(_MockBall(), _MockContact());
verify(androidSpaceship.bloc.onBallEntered).called(1);
},
);
},
);
}

@ -0,0 +1,24 @@
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
void main() {
group(
'AndroidSpaceshipCubit',
() {
blocTest<AndroidSpaceshipCubit, AndroidSpaceshipState>(
'onBallEntered emits withBonus',
build: AndroidSpaceshipCubit.new,
act: (bloc) => bloc.onBallEntered(),
expect: () => [AndroidSpaceshipState.withBonus],
);
blocTest<AndroidSpaceshipCubit, AndroidSpaceshipState>(
'onBonusAwarded emits withoutBonus',
build: AndroidSpaceshipCubit.new,
act: (bloc) => bloc.onBonusAwarded(),
expect: () => [AndroidSpaceshipState.withoutBonus],
);
},
);
}

@ -1,67 +0,0 @@
// ignore_for_file: cascade_invocations
import 'package:flame/components.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import '../../helpers/helpers.dart';
void main() {
group('AndroidSpaceship', () {
final assets = [
Assets.images.android.spaceship.saucer.keyName,
Assets.images.android.spaceship.animatronic.keyName,
Assets.images.android.spaceship.lightBeam.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));
flameTester.test('loads correctly', (game) async {
final component = AndroidSpaceship(position: Vector2.zero());
await game.ensureAdd(component);
expect(game.contains(component), isTrue);
});
flameTester.testGameWidget(
'renders correctly',
setUp: (game, tester) async {
await game.images.loadAll(assets);
final canvas = ZCanvasComponent(
children: [AndroidSpaceship(position: Vector2.zero())],
);
await game.ensureAdd(canvas);
game.camera.followVector2(Vector2.zero());
await game.ready();
await tester.pump();
},
verify: (game, tester) async {
final animationDuration = game
.descendants()
.whereType<SpriteAnimationComponent>()
.last
.animation!
.totalDuration();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_spaceship/start.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_spaceship/middle.png'),
);
game.update(animationDuration * 0.5);
await tester.pump();
await expectLater(
find.byGame<TestGame>(),
matchesGoldenFile('golden/android_spaceship/end.png'),
);
},
);
});
}

@ -2,6 +2,7 @@
import 'package:bloc_test/bloc_test.dart';
import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
@ -11,6 +12,12 @@ import 'package:pinball_components/src/components/chrome_dino/behaviors/behavior
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
class _MockContact extends Mock implements Contact {}
class _MockFixture extends Mock implements Fixture {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -30,7 +37,7 @@ void main() {
(game) async {
final ball = Ball(baseColor: Colors.red);
final behavior = ChromeDinoChompingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -44,8 +51,8 @@ void main() {
await chromeDino.add(behavior);
await game.ensureAddAll([chromeDino, ball]);
final contact = MockContact();
final fixture = MockFixture();
final contact = _MockContact();
final fixture = _MockFixture();
when(() => contact.fixtureA).thenReturn(fixture);
when(() => fixture.userData).thenReturn('inside_mouth');

@ -10,6 +10,14 @@ import 'package:pinball_components/src/components/chrome_dino/behaviors/behavior
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
class _MockContact extends Mock implements Contact {}
class _MockFixture extends Mock implements Fixture {}
class _MockBall extends Mock implements Ball {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -29,7 +37,7 @@ void main() {
'and there is not ball in the mouth',
(game) async {
final behavior = ChromeDinoMouthOpeningBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -43,12 +51,12 @@ void main() {
await chromeDino.add(behavior);
await game.ensureAdd(chromeDino);
final contact = MockContact();
final fixture = MockFixture();
final contact = _MockContact();
final fixture = _MockFixture();
when(() => contact.fixtureA).thenReturn(fixture);
when(() => fixture.userData).thenReturn('mouth_opening');
behavior.preSolve(MockBall(), contact, Manifold());
behavior.preSolve(_MockBall(), contact, Manifold());
verify(() => contact.setEnabled(false)).called(1);
},

@ -13,6 +13,8 @@ import 'package:pinball_components/src/components/chrome_dino/behaviors/behavior
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -33,7 +35,7 @@ void main() {
(game) async {
final ball = Ball(baseColor: Colors.red);
final behavior = ChromeDinoSpittingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
final streamController = StreamController<ChromeDinoState>();
final chompingState = ChromeDinoState(
status: ChromeDinoStatus.chomping,
@ -71,7 +73,7 @@ void main() {
(game) async {
final ball = Ball(baseColor: Colors.red);
final behavior = ChromeDinoSpittingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
final streamController = StreamController<ChromeDinoState>();
final chompingState = ChromeDinoState(
status: ChromeDinoStatus.chomping,

@ -10,6 +10,8 @@ import 'package:pinball_components/src/components/chrome_dino/behaviors/behavior
import '../../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -30,7 +32,7 @@ void main() {
'creates a RevoluteJoint',
(game) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -52,7 +54,7 @@ void main() {
'reverses swivel direction on each timer tick',
(game) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -84,7 +86,7 @@ void main() {
'and mouth is open',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -113,7 +115,7 @@ void main() {
'and mouth is closed',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),
@ -141,7 +143,7 @@ void main() {
'and mouth is closed',
setUp: (game, tester) async {
final behavior = ChromeDinoSwivelingBehavior();
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),

@ -10,6 +10,8 @@ import 'package:pinball_components/src/components/chrome_dino/behaviors/behavior
import '../../../helpers/helpers.dart';
class _MockChromeDinoCubit extends Mock implements ChromeDinoCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
@ -73,7 +75,7 @@ void main() {
// https://github.com/flame-engine/flame/pull/1538
// ignore: public_member_api_docs
flameTester.test('closes bloc when removed', (game) async {
final bloc = MockChromeDinoCubit();
final bloc = _MockChromeDinoCubit();
whenListen(
bloc,
const Stream<ChromeDinoState>.empty(),

@ -36,7 +36,8 @@ void main() {
);
blocTest<ChromeDinoCubit, ChromeDinoState>(
'onChomp emits ChromeDinoStatus.chomping and chomped ball',
'onChomp emits ChromeDinoStatus.chomping and chomped ball '
'when the ball is not in the mouth',
build: ChromeDinoCubit.new,
act: (bloc) => bloc.onChomp(ball),
expect: () => [
@ -55,7 +56,15 @@ void main() {
);
blocTest<ChromeDinoCubit, ChromeDinoState>(
'onSpit emits ChromeDinoStatus.idle',
'onChomp emits nothing when the ball is already in the mouth',
build: ChromeDinoCubit.new,
seed: () => const ChromeDinoState.inital().copyWith(ball: ball),
act: (bloc) => bloc.onChomp(ball),
expect: () => <ChromeDinoState>[],
);
blocTest<ChromeDinoCubit, ChromeDinoState>(
'onSpit emits ChromeDinoStatus.idle and removes ball',
build: ChromeDinoCubit.new,
act: (bloc) => bloc.onSpit(),
expect: () => [
@ -63,7 +72,11 @@ void main() {
(state) => state.status,
'status',
ChromeDinoStatus.idle,
)
)..having(
(state) => state.ball,
'ball',
null,
)
],
);
},

@ -1,6 +1,7 @@
// ignore_for_file: cascade_invocations
import 'package:bloc_test/bloc_test.dart';
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';
@ -9,6 +10,12 @@ import 'package:pinball_components/src/components/dash_nest_bumper/behaviors/beh
import '../../../../helpers/helpers.dart';
class _MockDashNestBumperCubit extends Mock implements DashNestBumperCubit {}
class _MockBall extends Mock implements Ball {}
class _MockContact extends Mock implements Contact {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(TestGame.new);
@ -27,7 +34,7 @@ void main() {
'beginContact emits onBallContacted when contacts with a ball',
(game) async {
final behavior = DashNestBumperBallContactBehavior();
final bloc = MockDashNestBumperCubit();
final bloc = _MockDashNestBumperCubit();
whenListen(
bloc,
const Stream<DashNestBumperState>.empty(),
@ -38,7 +45,7 @@ void main() {
await dashNestBumper.add(behavior);
await game.ensureAdd(dashNestBumper);
behavior.beginContact(MockBall(), MockContact());
behavior.beginContact(_MockBall(), _MockContact());
verify(dashNestBumper.bloc.onBallContacted).called(1);
},

@ -11,6 +11,8 @@ import 'package:pinball_components/src/components/dash_nest_bumper/behaviors/beh
import '../../../helpers/helpers.dart';
class _MockDashNestBumperCubit extends Mock implements DashNestBumperCubit {}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
@ -48,7 +50,7 @@ void main() {
// https://github.com/flame-engine/flame/pull/1538
// ignore: public_member_api_docs
flameTester.test('closes bloc when removed', (game) async {
final bloc = MockDashNestBumperCubit();
final bloc = _MockDashNestBumperCubit();
whenListen(
bloc,
const Stream<DashNestBumperState>.empty(),

@ -12,6 +12,7 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final assets = [
Assets.images.dino.topWall.keyName,
Assets.images.dino.topWallTunnel.keyName,
Assets.images.dino.bottomWall.keyName,
];
final flameTester = FlameTester(() => TestGame(assets));

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 121 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 121 KiB

After

Width:  |  Height:  |  Size: 114 KiB

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save