From df2ce91b063daab7cad9ec75fd726626372de4ff Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Tue, 8 Mar 2022 19:23:10 -0300 Subject: [PATCH 1/9] feat: adding bonus letter feature state management --- lib/game/bloc/game_bloc.dart | 12 +++++ lib/game/bloc/game_event.dart | 9 ++++ lib/game/bloc/game_state.dart | 10 +++- test/game/bloc/game_bloc_test.dart | 62 +++++++++++++++++++--- test/game/bloc/game_event_test.dart | 17 ++++++ test/game/bloc/game_state_test.dart | 29 ++++++++-- test/game/components/ball_test.dart | 2 +- test/game/view/pinball_game_page_test.dart | 2 +- 8 files changed, 127 insertions(+), 16 deletions(-) diff --git a/lib/game/bloc/game_bloc.dart b/lib/game/bloc/game_bloc.dart index 71c527a8..3cfc521f 100644 --- a/lib/game/bloc/game_bloc.dart +++ b/lib/game/bloc/game_bloc.dart @@ -9,6 +9,7 @@ class GameBloc extends Bloc { GameBloc() : super(const GameState.initial()) { on(_onBallLost); on(_onScored); + on(_onBonusLetterActivated); } void _onBallLost(BallLost event, Emitter emit) { @@ -22,4 +23,15 @@ class GameBloc extends Bloc { emit(state.copyWith(score: state.score + event.points)); } } + + void _onBonusLetterActivated(BonusLetterActivated event, Emitter emit) { + emit( + state.copyWith( + bonusLetter: [ + ...state.bonusLetter, + event.letter, + ], + ), + ); + } } diff --git a/lib/game/bloc/game_event.dart b/lib/game/bloc/game_event.dart index 88ef265b..417f6322 100644 --- a/lib/game/bloc/game_event.dart +++ b/lib/game/bloc/game_event.dart @@ -24,3 +24,12 @@ class Scored extends GameEvent { @override List get props => [points]; } + +class BonusLetterActivated extends GameEvent { + const BonusLetterActivated(this.letter); + + final String letter; + + @override + List get props => [letter]; +} diff --git a/lib/game/bloc/game_state.dart b/lib/game/bloc/game_state.dart index 1a0568f7..8454bab7 100644 --- a/lib/game/bloc/game_state.dart +++ b/lib/game/bloc/game_state.dart @@ -8,12 +8,14 @@ class GameState extends Equatable { const GameState({ required this.score, required this.balls, + required this.bonusLetter, }) : assert(score >= 0, "Score can't be negative"), assert(balls >= 0, "Number of balls can't be negative"); const GameState.initial() : score = 0, - balls = 3; + balls = 3, + bonusLetter = const []; /// The current score of the game. final int score; @@ -23,6 +25,9 @@ class GameState extends Equatable { /// When the number of balls is 0, the game is over. final int balls; + /// Active bonus letters + final List bonusLetter; + /// Determines when the game is over. bool get isGameOver => balls == 0; @@ -32,6 +37,7 @@ class GameState extends Equatable { GameState copyWith({ int? score, int? balls, + List? bonusLetter, }) { assert( score == null || score >= this.score, @@ -41,6 +47,7 @@ class GameState extends Equatable { return GameState( score: score ?? this.score, balls: balls ?? this.balls, + bonusLetter: bonusLetter ?? this.bonusLetter, ); } @@ -48,5 +55,6 @@ class GameState extends Equatable { List get props => [ score, balls, + bonusLetter, ]; } diff --git a/test/game/bloc/game_bloc_test.dart b/test/game/bloc/game_bloc_test.dart index 2676a286..3dc5dda7 100644 --- a/test/game/bloc/game_bloc_test.dart +++ b/test/game/bloc/game_bloc_test.dart @@ -21,9 +21,9 @@ void main() { } }, expect: () => [ - const GameState(score: 0, balls: 2), - const GameState(score: 0, balls: 1), - const GameState(score: 0, balls: 0), + const GameState(score: 0, balls: 2, bonusLetter: []), + const GameState(score: 0, balls: 1, bonusLetter: []), + const GameState(score: 0, balls: 0, bonusLetter: []), ], ); }); @@ -37,8 +37,8 @@ void main() { ..add(const Scored(points: 2)) ..add(const Scored(points: 3)), expect: () => [ - const GameState(score: 2, balls: 3), - const GameState(score: 5, balls: 3), + const GameState(score: 2, balls: 3, bonusLetter: []), + const GameState(score: 5, balls: 3, bonusLetter: []), ], ); @@ -53,9 +53,55 @@ void main() { bloc.add(const Scored(points: 2)); }, expect: () => [ - const GameState(score: 0, balls: 2), - const GameState(score: 0, balls: 1), - const GameState(score: 0, balls: 0), + const GameState(score: 0, balls: 2, bonusLetter: []), + const GameState(score: 0, balls: 1, bonusLetter: []), + const GameState(score: 0, balls: 0, bonusLetter: []), + ], + ); + }); + + group('BonusLetterActivated', () { + blocTest( + 'adds the letter to the state', + build: GameBloc.new, + act: (bloc) => bloc + ..add(const BonusLetterActivated('G')) + ..add(const BonusLetterActivated('O')) + ..add(const BonusLetterActivated('O')) + ..add(const BonusLetterActivated('G')) + ..add(const BonusLetterActivated('L')) + ..add(const BonusLetterActivated('E')), + expect: () => [ + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G'], + ), + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G', 'O'], + ), + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G', 'O', 'O'], + ), + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G', 'O', 'O', 'G'], + ), + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G', 'O', 'O', 'G', 'L'], + ), + const GameState( + score: 0, + balls: 3, + bonusLetter: ['G', 'O', 'O', 'G', 'L', 'E'], + ), ], ); }); diff --git a/test/game/bloc/game_event_test.dart b/test/game/bloc/game_event_test.dart index e839ab56..0e7a0f71 100644 --- a/test/game/bloc/game_event_test.dart +++ b/test/game/bloc/game_event_test.dart @@ -40,5 +40,22 @@ void main() { expect(() => Scored(points: 0), throwsAssertionError); }); }); + + group('BonusLetterActivated', () { + test('can be instantiated', () { + expect(const BonusLetterActivated('A'), isNotNull); + }); + + test('supports value equality', () { + expect( + BonusLetterActivated('A'), + equals(BonusLetterActivated('A')), + ); + expect( + BonusLetterActivated('B'), + isNot(equals(BonusLetterActivated('A'))), + ); + }); + }); }); } diff --git a/test/game/bloc/game_state_test.dart b/test/game/bloc/game_state_test.dart index 59cc0d1d..e50acbcd 100644 --- a/test/game/bloc/game_state_test.dart +++ b/test/game/bloc/game_state_test.dart @@ -7,14 +7,24 @@ void main() { group('GameState', () { test('supports value equality', () { expect( - GameState(score: 0, balls: 0), - equals(const GameState(score: 0, balls: 0)), + GameState( + score: 0, + balls: 0, + bonusLetter: const [], + ), + equals( + const GameState( + score: 0, + balls: 0, + bonusLetter: [], + ), + ), ); }); group('constructor', () { test('can be instantiated', () { - expect(const GameState(score: 0, balls: 0), isNotNull); + expect(const GameState(score: 0, balls: 0, bonusLetter: []), isNotNull); }); }); @@ -23,7 +33,7 @@ void main() { 'when balls are negative', () { expect( - () => GameState(balls: -1, score: 0), + () => GameState(balls: -1, score: 0, bonusLetter: const []), throwsAssertionError, ); }, @@ -34,7 +44,7 @@ void main() { 'when score is negative', () { expect( - () => GameState(balls: 0, score: -1), + () => GameState(balls: 0, score: -1, bonusLetter: const []), throwsAssertionError, ); }, @@ -47,6 +57,7 @@ void main() { const gameState = GameState( balls: 0, score: 0, + bonusLetter: [], ); expect(gameState.isGameOver, isTrue); }); @@ -57,6 +68,7 @@ void main() { const gameState = GameState( balls: 1, score: 0, + bonusLetter: [], ); expect(gameState.isGameOver, isFalse); }); @@ -70,6 +82,7 @@ void main() { const gameState = GameState( balls: 1, score: 0, + bonusLetter: [], ); expect(gameState.isLastBall, isTrue); }, @@ -82,6 +95,7 @@ void main() { const gameState = GameState( balls: 2, score: 0, + bonusLetter: [], ); expect(gameState.isLastBall, isFalse); }, @@ -96,6 +110,7 @@ void main() { const gameState = GameState( balls: 0, score: 2, + bonusLetter: [], ); expect( () => gameState.copyWith(score: gameState.score - 1), @@ -111,6 +126,7 @@ void main() { const gameState = GameState( balls: 0, score: 2, + bonusLetter: [], ); expect( gameState.copyWith(), @@ -126,10 +142,12 @@ void main() { const gameState = GameState( score: 2, balls: 0, + bonusLetter: [], ); final otherGameState = GameState( score: gameState.score + 1, balls: gameState.balls + 1, + bonusLetter: const ['A'], ); expect(gameState, isNot(equals(otherGameState))); @@ -137,6 +155,7 @@ void main() { gameState.copyWith( score: otherGameState.score, balls: otherGameState.balls, + bonusLetter: otherGameState.bonusLetter, ), equals(otherGameState), ); diff --git a/test/game/components/ball_test.dart b/test/game/components/ball_test.dart index 7ac3ceff..9885b310 100644 --- a/test/game/components/ball_test.dart +++ b/test/game/components/ball_test.dart @@ -135,7 +135,7 @@ void main() { whenListen( gameBloc, const Stream.empty(), - initialState: const GameState(score: 10, balls: 1), + initialState: const GameState(score: 10, balls: 1, bonusLetter: []), ); await game.ready(); diff --git a/test/game/view/pinball_game_page_test.dart b/test/game/view/pinball_game_page_test.dart index be418c1d..eacee734 100644 --- a/test/game/view/pinball_game_page_test.dart +++ b/test/game/view/pinball_game_page_test.dart @@ -67,7 +67,7 @@ void main() { 'renders a game over dialog when the user has lost', (tester) async { final gameBloc = MockGameBloc(); - const state = GameState(score: 0, balls: 0); + const state = GameState(score: 0, balls: 0, bonusLetter: []); whenListen( gameBloc, Stream.value(state), From de25974f8c9b50bc31fd416f28a08bab0445a98a Mon Sep 17 00:00:00 2001 From: Erick Date: Wed, 9 Mar 2022 09:48:09 -0300 Subject: [PATCH 2/9] Update lib/game/bloc/game_state.dart Co-authored-by: Alejandro Santiago --- lib/game/bloc/game_state.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/game/bloc/game_state.dart b/lib/game/bloc/game_state.dart index 8454bab7..09207b86 100644 --- a/lib/game/bloc/game_state.dart +++ b/lib/game/bloc/game_state.dart @@ -25,7 +25,7 @@ class GameState extends Equatable { /// When the number of balls is 0, the game is over. final int balls; - /// Active bonus letters + /// Active bonus letters. final List bonusLetter; /// Determines when the game is over. From e4cd4342c0c2bc40724cfed8deac93caf3abffa0 Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Wed, 9 Mar 2022 09:53:52 -0300 Subject: [PATCH 3/9] feat: pr suggestions --- lib/game/bloc/game_bloc.dart | 4 +-- lib/game/bloc/game_state.dart | 12 ++++----- test/game/bloc/game_bloc_test.dart | 28 +++++++++---------- test/game/bloc/game_state_test.dart | 31 ++++++++++++---------- test/game/components/ball_test.dart | 6 ++++- test/game/view/pinball_game_page_test.dart | 2 +- 6 files changed, 45 insertions(+), 38 deletions(-) diff --git a/lib/game/bloc/game_bloc.dart b/lib/game/bloc/game_bloc.dart index 3cfc521f..3b5c16b0 100644 --- a/lib/game/bloc/game_bloc.dart +++ b/lib/game/bloc/game_bloc.dart @@ -27,8 +27,8 @@ class GameBloc extends Bloc { void _onBonusLetterActivated(BonusLetterActivated event, Emitter emit) { emit( state.copyWith( - bonusLetter: [ - ...state.bonusLetter, + bonusLetters: [ + ...state.bonusLetters, event.letter, ], ), diff --git a/lib/game/bloc/game_state.dart b/lib/game/bloc/game_state.dart index 09207b86..8a5ab298 100644 --- a/lib/game/bloc/game_state.dart +++ b/lib/game/bloc/game_state.dart @@ -8,14 +8,14 @@ class GameState extends Equatable { const GameState({ required this.score, required this.balls, - required this.bonusLetter, + required this.bonusLetters, }) : assert(score >= 0, "Score can't be negative"), assert(balls >= 0, "Number of balls can't be negative"); const GameState.initial() : score = 0, balls = 3, - bonusLetter = const []; + bonusLetters = const []; /// The current score of the game. final int score; @@ -26,7 +26,7 @@ class GameState extends Equatable { final int balls; /// Active bonus letters. - final List bonusLetter; + final List bonusLetters; /// Determines when the game is over. bool get isGameOver => balls == 0; @@ -37,7 +37,7 @@ class GameState extends Equatable { GameState copyWith({ int? score, int? balls, - List? bonusLetter, + List? bonusLetters, }) { assert( score == null || score >= this.score, @@ -47,7 +47,7 @@ class GameState extends Equatable { return GameState( score: score ?? this.score, balls: balls ?? this.balls, - bonusLetter: bonusLetter ?? this.bonusLetter, + bonusLetters: bonusLetters ?? this.bonusLetters, ); } @@ -55,6 +55,6 @@ class GameState extends Equatable { List get props => [ score, balls, - bonusLetter, + bonusLetters, ]; } diff --git a/test/game/bloc/game_bloc_test.dart b/test/game/bloc/game_bloc_test.dart index 3dc5dda7..bd669397 100644 --- a/test/game/bloc/game_bloc_test.dart +++ b/test/game/bloc/game_bloc_test.dart @@ -21,9 +21,9 @@ void main() { } }, expect: () => [ - const GameState(score: 0, balls: 2, bonusLetter: []), - const GameState(score: 0, balls: 1, bonusLetter: []), - const GameState(score: 0, balls: 0, bonusLetter: []), + const GameState(score: 0, balls: 2, bonusLetters: []), + const GameState(score: 0, balls: 1, bonusLetters: []), + const GameState(score: 0, balls: 0, bonusLetters: []), ], ); }); @@ -37,8 +37,8 @@ void main() { ..add(const Scored(points: 2)) ..add(const Scored(points: 3)), expect: () => [ - const GameState(score: 2, balls: 3, bonusLetter: []), - const GameState(score: 5, balls: 3, bonusLetter: []), + const GameState(score: 2, balls: 3, bonusLetters: []), + const GameState(score: 5, balls: 3, bonusLetters: []), ], ); @@ -53,9 +53,9 @@ void main() { bloc.add(const Scored(points: 2)); }, expect: () => [ - const GameState(score: 0, balls: 2, bonusLetter: []), - const GameState(score: 0, balls: 1, bonusLetter: []), - const GameState(score: 0, balls: 0, bonusLetter: []), + const GameState(score: 0, balls: 2, bonusLetters: []), + const GameState(score: 0, balls: 1, bonusLetters: []), + const GameState(score: 0, balls: 0, bonusLetters: []), ], ); }); @@ -75,32 +75,32 @@ void main() { const GameState( score: 0, balls: 3, - bonusLetter: ['G'], + bonusLetters: ['G'], ), const GameState( score: 0, balls: 3, - bonusLetter: ['G', 'O'], + bonusLetters: ['G', 'O'], ), const GameState( score: 0, balls: 3, - bonusLetter: ['G', 'O', 'O'], + bonusLetters: ['G', 'O', 'O'], ), const GameState( score: 0, balls: 3, - bonusLetter: ['G', 'O', 'O', 'G'], + bonusLetters: ['G', 'O', 'O', 'G'], ), const GameState( score: 0, balls: 3, - bonusLetter: ['G', 'O', 'O', 'G', 'L'], + bonusLetters: ['G', 'O', 'O', 'G', 'L'], ), const GameState( score: 0, balls: 3, - bonusLetter: ['G', 'O', 'O', 'G', 'L', 'E'], + bonusLetters: ['G', 'O', 'O', 'G', 'L', 'E'], ), ], ); diff --git a/test/game/bloc/game_state_test.dart b/test/game/bloc/game_state_test.dart index e50acbcd..7345d3bd 100644 --- a/test/game/bloc/game_state_test.dart +++ b/test/game/bloc/game_state_test.dart @@ -10,13 +10,13 @@ void main() { GameState( score: 0, balls: 0, - bonusLetter: const [], + bonusLetters: const [], ), equals( const GameState( score: 0, balls: 0, - bonusLetter: [], + bonusLetters: [], ), ), ); @@ -24,7 +24,10 @@ void main() { group('constructor', () { test('can be instantiated', () { - expect(const GameState(score: 0, balls: 0, bonusLetter: []), isNotNull); + expect( + const GameState(score: 0, balls: 0, bonusLetters: []), + isNotNull, + ); }); }); @@ -33,7 +36,7 @@ void main() { 'when balls are negative', () { expect( - () => GameState(balls: -1, score: 0, bonusLetter: const []), + () => GameState(balls: -1, score: 0, bonusLetters: const []), throwsAssertionError, ); }, @@ -44,7 +47,7 @@ void main() { 'when score is negative', () { expect( - () => GameState(balls: 0, score: -1, bonusLetter: const []), + () => GameState(balls: 0, score: -1, bonusLetters: const []), throwsAssertionError, ); }, @@ -57,7 +60,7 @@ void main() { const gameState = GameState( balls: 0, score: 0, - bonusLetter: [], + bonusLetters: [], ); expect(gameState.isGameOver, isTrue); }); @@ -68,7 +71,7 @@ void main() { const gameState = GameState( balls: 1, score: 0, - bonusLetter: [], + bonusLetters: [], ); expect(gameState.isGameOver, isFalse); }); @@ -82,7 +85,7 @@ void main() { const gameState = GameState( balls: 1, score: 0, - bonusLetter: [], + bonusLetters: [], ); expect(gameState.isLastBall, isTrue); }, @@ -95,7 +98,7 @@ void main() { const gameState = GameState( balls: 2, score: 0, - bonusLetter: [], + bonusLetters: [], ); expect(gameState.isLastBall, isFalse); }, @@ -110,7 +113,7 @@ void main() { const gameState = GameState( balls: 0, score: 2, - bonusLetter: [], + bonusLetters: [], ); expect( () => gameState.copyWith(score: gameState.score - 1), @@ -126,7 +129,7 @@ void main() { const gameState = GameState( balls: 0, score: 2, - bonusLetter: [], + bonusLetters: [], ); expect( gameState.copyWith(), @@ -142,12 +145,12 @@ void main() { const gameState = GameState( score: 2, balls: 0, - bonusLetter: [], + bonusLetters: [], ); final otherGameState = GameState( score: gameState.score + 1, balls: gameState.balls + 1, - bonusLetter: const ['A'], + bonusLetters: const ['A'], ); expect(gameState, isNot(equals(otherGameState))); @@ -155,7 +158,7 @@ void main() { gameState.copyWith( score: otherGameState.score, balls: otherGameState.balls, - bonusLetter: otherGameState.bonusLetter, + bonusLetters: otherGameState.bonusLetters, ), equals(otherGameState), ); diff --git a/test/game/components/ball_test.dart b/test/game/components/ball_test.dart index 9885b310..bd2cbcfc 100644 --- a/test/game/components/ball_test.dart +++ b/test/game/components/ball_test.dart @@ -135,7 +135,11 @@ void main() { whenListen( gameBloc, const Stream.empty(), - initialState: const GameState(score: 10, balls: 1, bonusLetter: []), + initialState: const GameState( + score: 10, + balls: 1, + bonusLetters: [], + ), ); await game.ready(); diff --git a/test/game/view/pinball_game_page_test.dart b/test/game/view/pinball_game_page_test.dart index eacee734..d578a1db 100644 --- a/test/game/view/pinball_game_page_test.dart +++ b/test/game/view/pinball_game_page_test.dart @@ -67,7 +67,7 @@ void main() { 'renders a game over dialog when the user has lost', (tester) async { final gameBloc = MockGameBloc(); - const state = GameState(score: 0, balls: 0, bonusLetter: []); + const state = GameState(score: 0, balls: 0, bonusLetters: []); whenListen( gameBloc, Stream.value(state), From a3dc9d09cff15dfb97409f099981eca355585c5d Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Tue, 8 Mar 2022 18:45:51 -0300 Subject: [PATCH 4/9] feat: adding game hud --- lib/game/view/game_hud.dart | 40 ++++++++++++++++++++++ lib/game/view/pinball_game_page.dart | 13 ++++++- lib/game/view/view.dart | 1 + test/game/view/game_hud_test.dart | 32 +++++++++++++++++ test/game/view/pinball_game_page_test.dart | 6 +++- 5 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 lib/game/view/game_hud.dart create mode 100644 test/game/view/game_hud_test.dart diff --git a/lib/game/view/game_hud.dart b/lib/game/view/game_hud.dart new file mode 100644 index 00000000..b694e812 --- /dev/null +++ b/lib/game/view/game_hud.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:pinball/game/game.dart'; + +class GameHud extends StatelessWidget { + const GameHud({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + final state = context.watch().state; + + return Container( + color: Colors.redAccent, + width: 200, + height: 100, + padding: const EdgeInsets.all(16), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + '${state.score}', + style: Theme.of(context).textTheme.headline3, + ), + Column( + children: [ + for (var i = 0; i < state.balls; i++) + const Padding( + padding: EdgeInsets.only(top: 6), + child: CircleAvatar( + radius: 8, + backgroundColor: Colors.black, + ), + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/game/view/pinball_game_page.dart b/lib/game/view/pinball_game_page.dart index 02f5b34c..8a9a981c 100644 --- a/lib/game/view/pinball_game_page.dart +++ b/lib/game/view/pinball_game_page.dart @@ -56,7 +56,18 @@ class _PinballGameViewState extends State { ); } }, - child: GameWidget(game: _game), + child: Stack( + children: [ + Positioned.fill( + child: GameWidget(game: _game), + ), + const Positioned( + top: 8, + left: 8, + child: GameHud(), + ), + ], + ), ); } } diff --git a/lib/game/view/view.dart b/lib/game/view/view.dart index 53d3813a..26b700d3 100644 --- a/lib/game/view/view.dart +++ b/lib/game/view/view.dart @@ -1,2 +1,3 @@ +export 'game_hud.dart'; export 'pinball_game_page.dart'; export 'widgets/widgets.dart'; diff --git a/test/game/view/game_hud_test.dart b/test/game/view/game_hud_test.dart new file mode 100644 index 00000000..40079a2f --- /dev/null +++ b/test/game/view/game_hud_test.dart @@ -0,0 +1,32 @@ +// ignore_for_file: prefer_const_constructors + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pinball/game/game.dart'; +import '../../helpers/helpers.dart'; + +void main() { + group('GameHud', () { + testWidgets( + 'renders the current score and balls', + (tester) async { + final state = GameState(score: 10, balls: 2); + final gameBloc = MockGameBloc(); + whenListen( + gameBloc, + Stream.value(state), + initialState: state, + ); + + await tester.pumpApp( + GameHud(), + gameBloc: gameBloc, + ); + + expect(find.text('10'), findsOneWidget); + expect(find.byType(CircleAvatar), findsNWidgets(2)); + }, + ); + }); +} diff --git a/test/game/view/pinball_game_page_test.dart b/test/game/view/pinball_game_page_test.dart index d578a1db..746dc2c7 100644 --- a/test/game/view/pinball_game_page_test.dart +++ b/test/game/view/pinball_game_page_test.dart @@ -48,7 +48,7 @@ void main() { }); group('PinballGameView', () { - testWidgets('renders game', (tester) async { + testWidgets('renders game and a hud', (tester) async { final gameBloc = MockGameBloc(); whenListen( gameBloc, @@ -61,6 +61,10 @@ void main() { find.byWidgetPredicate((w) => w is GameWidget), findsOneWidget, ); + expect( + find.byType(GameHud), + findsOneWidget, + ); }); testWidgets( From f9f109ba5aeadfd8618439187b8ea3bad8a88b5f Mon Sep 17 00:00:00 2001 From: Erick Date: Wed, 9 Mar 2022 10:02:50 -0300 Subject: [PATCH 5/9] Apply suggestions from code review Co-authored-by: Alejandro Santiago --- lib/game/view/game_hud.dart | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/lib/game/view/game_hud.dart b/lib/game/view/game_hud.dart index b694e812..beff3391 100644 --- a/lib/game/view/game_hud.dart +++ b/lib/game/view/game_hud.dart @@ -2,7 +2,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/game/game.dart'; +/// {@template game_hud} +/// Overlay of a [PinballGame] that displays the current [GameState.score] and +/// [GameState.balls]. +/// {@endtemplate} class GameHud extends StatelessWidget { + /// {@macro game_hud} const GameHud({Key? key}) : super(key: key); @override From 38b8a28ffc661563374f37f64e6dc0012475304f Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Wed, 9 Mar 2022 10:18:54 -0300 Subject: [PATCH 6/9] feat: pr suggestions --- lib/game/view/game_hud.dart | 5 ++- test/game/view/game_hud_test.dart | 75 +++++++++++++++++++++++++------ 2 files changed, 64 insertions(+), 16 deletions(-) diff --git a/lib/game/view/game_hud.dart b/lib/game/view/game_hud.dart index beff3391..7bf1e8c3 100644 --- a/lib/game/view/game_hud.dart +++ b/lib/game/view/game_hud.dart @@ -26,11 +26,12 @@ class GameHud extends StatelessWidget { '${state.score}', style: Theme.of(context).textTheme.headline3, ), - Column( + Wrap( + direction: Axis.vertical, children: [ for (var i = 0; i < state.balls; i++) const Padding( - padding: EdgeInsets.only(top: 6), + padding: EdgeInsets.only(top: 6, right: 6), child: CircleAvatar( radius: 8, backgroundColor: Colors.black, diff --git a/test/game/view/game_hud_test.dart b/test/game/view/game_hud_test.dart index 40079a2f..27a423ed 100644 --- a/test/game/view/game_hud_test.dart +++ b/test/game/view/game_hud_test.dart @@ -8,25 +8,72 @@ import '../../helpers/helpers.dart'; void main() { group('GameHud', () { + late GameBloc gameBloc; + const initialState = GameState(score: 10, balls: 2); + + void _mockState(GameState state) { + whenListen( + gameBloc, + Stream.value(state), + initialState: state, + ); + } + + Future _pumpHud(WidgetTester tester) async { + await tester.pumpApp( + GameHud(), + gameBloc: gameBloc, + ); + } + + setUp(() { + gameBloc = MockGameBloc(); + _mockState(initialState); + }); + testWidgets( - 'renders the current score and balls', + 'renders the current score', (tester) async { - final state = GameState(score: 10, balls: 2); - final gameBloc = MockGameBloc(); - whenListen( - gameBloc, - Stream.value(state), - initialState: state, - ); + await _pumpHud(tester); + expect(find.text(initialState.score.toString()), findsOneWidget); + }, + ); - await tester.pumpApp( - GameHud(), - gameBloc: gameBloc, + testWidgets( + 'renders the current ball number', + (tester) async { + await _pumpHud(tester); + expect( + find.byType(CircleAvatar), + findsNWidgets(initialState.balls), ); - - expect(find.text('10'), findsOneWidget); - expect(find.byType(CircleAvatar), findsNWidgets(2)); }, ); + + testWidgets('updates the score', (tester) async { + await _pumpHud(tester); + expect(find.text(initialState.score.toString()), findsOneWidget); + + _mockState(initialState.copyWith(score: 20)); + + await tester.pump(); + expect(find.text('20'), findsOneWidget); + }); + + testWidgets('updates the ball number', (tester) async { + await _pumpHud(tester); + expect( + find.byType(CircleAvatar), + findsNWidgets(initialState.balls), + ); + + _mockState(initialState.copyWith(balls: 1)); + + await tester.pump(); + expect( + find.byType(CircleAvatar), + findsNWidgets(1), + ); + }); }); } From 884d8b36b07974dff833f37cc669721d58a26671 Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Wed, 9 Mar 2022 10:22:17 -0300 Subject: [PATCH 7/9] fix: lint --- lib/game/view/game_hud.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/game/view/game_hud.dart b/lib/game/view/game_hud.dart index 7bf1e8c3..00eedd2b 100644 --- a/lib/game/view/game_hud.dart +++ b/lib/game/view/game_hud.dart @@ -3,7 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pinball/game/game.dart'; /// {@template game_hud} -/// Overlay of a [PinballGame] that displays the current [GameState.score] and +/// Overlay of a [PinballGame] that displays the current [GameState.score] and /// [GameState.balls]. /// {@endtemplate} class GameHud extends StatelessWidget { From 84282fe83a67e95eaf5a3b3cb4a66d14192bc7c1 Mon Sep 17 00:00:00 2001 From: Erick Zanardo Date: Wed, 9 Mar 2022 10:51:25 -0300 Subject: [PATCH 8/9] fix: test from rebase --- test/game/view/game_hud_test.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/game/view/game_hud_test.dart b/test/game/view/game_hud_test.dart index 27a423ed..e7334e41 100644 --- a/test/game/view/game_hud_test.dart +++ b/test/game/view/game_hud_test.dart @@ -9,7 +9,7 @@ import '../../helpers/helpers.dart'; void main() { group('GameHud', () { late GameBloc gameBloc; - const initialState = GameState(score: 10, balls: 2); + const initialState = GameState(score: 10, balls: 2, bonusLetters: []); void _mockState(GameState state) { whenListen( From 360b5876cf02fd74974538b4af4033c24b50986a Mon Sep 17 00:00:00 2001 From: Alejandro Santiago Date: Wed, 9 Mar 2022 17:10:32 +0000 Subject: [PATCH 9/9] feat: Flipper (#15) * feat: explicitely imported Anchor * feat: implemented Flipper * feat: implemented Flipper in PinballGame * feat: implemented calculateRequiredSpeed * feat: included right and left constructors * feat: used right and left constructors * refactor: cleaned calcualteSpeed method * refactor: used width and height instead of size * feat: implemented FlipperAnchor * feat: implemented BoardSide enum * docs: used prose in doc comment * feat: implemented BoardSideX * refactor: used isLeft instead of isRight * refactor: implemented unlock method * refactor: same line assignment Co-authored-by: Erick * feat: add themes * feat: add theme cubit * test: character themes * test: remove grouping * refactor: move themes to package * chore: add workflow * fix: workflow * docs: character themes update * refactor: one theme for entire game * chore: add to props * fix: changing ball spawning point to avoid context errors * refactor: modified unlock method due to invalid cast * feat: included test for BoardSide * refactor: removed sweepingAnimationDuration * feat: tested flipper.dart * refactor: included flippersPosition * refactor: implemented _addFlippers method * feat: centered vertices * feat: modified test to match new center * refactor: removed unecessary parenthesis * refactor: removed unecessary calculation * fix: changing ball spawning point to avoid context errors * chore: rebasing * docs: included FIXME comment * feat: moved key listening to Flipper * docs: include TOOD comment * feat: including test and refactor * docs: fixed doc comment typo Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * docs: fixed do comment template name Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * refactor: removed unnecessary verbose multiplication Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * refactor: removed unnecessary verbose multiplication * refactor: used ensureAddAll instead of ensureAdd Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * docs: fixed doc comment typo * refactor: used bigCircleShape.radius * refactor: reorganized methods * docs: improved doc comment * refactor: removed unecessary class variables * docs: fix doc comment typo * refactor: removed unused helper * fix: simplified keyEvents * fix: corrected erroneous key tests * refactor: modified component tests * refactor: capitalized Flipper test description * refactor: changed angle calculations * fix: tests * refactor: removed exta line Co-authored-by: Erick Co-authored-by: Allison Ryan Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> --- lib/game/components/board_side.dart | 22 ++ lib/game/components/components.dart | 2 + lib/game/components/flipper.dart | 241 +++++++++++++ lib/game/components/plunger.dart | 2 +- lib/game/pinball_game.dart | 87 ++++- test/game/components/board_side_test.dart | 27 ++ test/game/components/flipper_test.dart | 401 ++++++++++++++++++++++ test/game/pinball_game_test.dart | 45 +++ test/helpers/helpers.dart | 1 + test/helpers/key_testers.dart | 37 ++ test/helpers/mocks.dart | 16 + 11 files changed, 869 insertions(+), 12 deletions(-) create mode 100644 lib/game/components/board_side.dart create mode 100644 lib/game/components/flipper.dart create mode 100644 test/game/components/board_side_test.dart create mode 100644 test/game/components/flipper_test.dart create mode 100644 test/helpers/key_testers.dart diff --git a/lib/game/components/board_side.dart b/lib/game/components/board_side.dart new file mode 100644 index 00000000..611f70b8 --- /dev/null +++ b/lib/game/components/board_side.dart @@ -0,0 +1,22 @@ +import 'package:pinball/game/game.dart'; + +/// Indicates a side of the board. +/// +/// Usually used to position or mirror elements of a [PinballGame]; such as a +/// [Flipper]. +enum BoardSide { + /// The left side of the board. + left, + + /// The right side of the board. + right, +} + +/// Utility methods for [BoardSide]. +extension BoardSideX on BoardSide { + /// Whether this side is [BoardSide.left]. + bool get isLeft => this == BoardSide.left; + + /// Whether this side is [BoardSide.right]. + bool get isRight => this == BoardSide.right; +} diff --git a/lib/game/components/components.dart b/lib/game/components/components.dart index 95134ec2..bd5f5437 100644 --- a/lib/game/components/components.dart +++ b/lib/game/components/components.dart @@ -1,5 +1,7 @@ export 'anchor.dart'; export 'ball.dart'; +export 'board_side.dart'; +export 'flipper.dart'; export 'plunger.dart'; export 'score_points.dart'; export 'wall.dart'; diff --git a/lib/game/components/flipper.dart b/lib/game/components/flipper.dart new file mode 100644 index 00000000..bd071b93 --- /dev/null +++ b/lib/game/components/flipper.dart @@ -0,0 +1,241 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flame/input.dart'; +import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:pinball/game/game.dart'; + +/// {@template flipper} +/// A bat, typically found in pairs at the bottom of the board. +/// +/// [Flipper] can be controlled by the player in an arc motion. +/// {@endtemplate flipper} +class Flipper extends BodyComponent with KeyboardHandler { + /// {@macro flipper} + Flipper._({ + required Vector2 position, + required this.side, + required List keys, + }) : _position = position, + _keys = keys { + // TODO(alestiago): Use sprite instead of color when provided. + paint = Paint() + ..color = const Color(0xFF00FF00) + ..style = PaintingStyle.fill; + } + + /// A left positioned [Flipper]. + Flipper.left({ + required Vector2 position, + }) : this._( + position: position, + side: BoardSide.left, + keys: [ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.keyA, + ], + ); + + /// A right positioned [Flipper]. + Flipper.right({ + required Vector2 position, + }) : this._( + position: position, + side: BoardSide.right, + keys: [ + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.keyD, + ], + ); + + /// The width of the [Flipper]. + static const width = 12.0; + + /// The height of the [Flipper]. + static const height = 2.8; + + /// The speed required to move the [Flipper] to its highest position. + /// + /// The higher the value, the faster the [Flipper] will move. + static const double _speed = 60; + + /// Whether the [Flipper] is on the left or right side of the board. + /// + /// A [Flipper] with [BoardSide.left] has a counter-clockwise arc motion, + /// whereas a [Flipper] with [BoardSide.right] has a clockwise arc motion. + final BoardSide side; + + /// The initial position of the [Flipper] body. + final Vector2 _position; + + /// The [LogicalKeyboardKey]s that will control the [Flipper]. + /// + /// [onKeyEvent] method listens to when one of these keys is pressed. + final List _keys; + + /// Applies downward linear velocity to the [Flipper], moving it to its + /// resting position. + void _moveDown() { + body.linearVelocity = Vector2(0, -_speed); + } + + /// Applies upward linear velocity to the [Flipper], moving it to its highest + /// position. + void _moveUp() { + body.linearVelocity = Vector2(0, _speed); + } + + List _createFixtureDefs() { + final fixtures = []; + final isLeft = side.isLeft; + + final bigCircleShape = CircleShape()..radius = height / 2; + bigCircleShape.position.setValues( + isLeft + ? -(width / 2) + bigCircleShape.radius + : (width / 2) - bigCircleShape.radius, + 0, + ); + final bigCircleFixtureDef = FixtureDef(bigCircleShape); + fixtures.add(bigCircleFixtureDef); + + final smallCircleShape = CircleShape()..radius = bigCircleShape.radius / 2; + smallCircleShape.position.setValues( + isLeft + ? (width / 2) - smallCircleShape.radius + : -(width / 2) + smallCircleShape.radius, + 0, + ); + final smallCircleFixtureDef = FixtureDef(smallCircleShape); + fixtures.add(smallCircleFixtureDef); + + final trapeziumVertices = isLeft + ? [ + Vector2(bigCircleShape.position.x, bigCircleShape.radius), + Vector2(smallCircleShape.position.x, smallCircleShape.radius), + Vector2(smallCircleShape.position.x, -smallCircleShape.radius), + Vector2(bigCircleShape.position.x, -bigCircleShape.radius), + ] + : [ + Vector2(smallCircleShape.position.x, smallCircleShape.radius), + Vector2(bigCircleShape.position.x, bigCircleShape.radius), + Vector2(bigCircleShape.position.x, -bigCircleShape.radius), + Vector2(smallCircleShape.position.x, -smallCircleShape.radius), + ]; + final trapezium = PolygonShape()..set(trapeziumVertices); + final trapeziumFixtureDef = FixtureDef(trapezium) + ..density = 50.0 // TODO(alestiago): Use a proper density. + ..friction = .1; // TODO(alestiago): Use a proper friction. + fixtures.add(trapeziumFixtureDef); + + return fixtures; + } + + @override + Body createBody() { + final bodyDef = BodyDef() + ..gravityScale = 0 + ..type = BodyType.dynamic + ..position = _position; + + final body = world.createBody(bodyDef); + _createFixtureDefs().forEach(body.createFixture); + + return body; + } + + // TODO(erickzanardo): Remove this once the issue is solved: + // https://github.com/flame-engine/flame/issues/1417 + final Completer hasMounted = Completer(); + + @override + void onMount() { + super.onMount(); + hasMounted.complete(); + } + + @override + bool onKeyEvent( + RawKeyEvent event, + Set keysPressed, + ) { + // TODO(alestiago): Check why false cancels the event for other components. + // Investigate why return is of type [bool] expected instead of a type + // [KeyEventResult]. + if (!_keys.contains(event.logicalKey)) return true; + + if (event is RawKeyDownEvent) { + _moveUp(); + } else if (event is RawKeyUpEvent) { + _moveDown(); + } + + return true; + } +} + +/// {@template flipper_anchor} +/// [Anchor] positioned at the end of a [Flipper]. +/// +/// The end of a [Flipper] depends on its [Flipper.side]. +/// {@endtemplate} +class FlipperAnchor extends Anchor { + /// {@macro flipper_anchor} + FlipperAnchor({ + required Flipper flipper, + }) : super( + position: Vector2( + flipper.side.isLeft + ? flipper.body.position.x - Flipper.width / 2 + : flipper.body.position.x + Flipper.width / 2, + flipper.body.position.y, + ), + ); +} + +/// {@template flipper_anchor_revolute_joint_def} +/// Hinges one end of [Flipper] to a [Anchor] to achieve an arc motion. +/// {@endtemplate} +class FlipperAnchorRevoluteJointDef extends RevoluteJointDef { + /// {@macro flipper_anchor_revolute_joint_def} + FlipperAnchorRevoluteJointDef({ + required Flipper flipper, + required Anchor anchor, + }) { + initialize( + flipper.body, + anchor.body, + anchor.body.position, + ); + enableLimit = true; + + final angle = (flipper.side.isLeft ? _sweepingAngle : -_sweepingAngle) / 2; + lowerAngle = upperAngle = angle; + } + + /// The total angle of the arc motion. + static const _sweepingAngle = math.pi / 3.5; + + /// Unlocks the [Flipper] from its resting position. + /// + /// The [Flipper] is locked when initialized in order to force it to be at + /// its resting position. + // TODO(alestiago): consider refactor once the issue is solved: + // https://github.com/flame-engine/forge2d/issues/36 + static void unlock(RevoluteJoint joint, BoardSide side) { + late final double upperLimit, lowerLimit; + switch (side) { + case BoardSide.left: + lowerLimit = -joint.lowerLimit; + upperLimit = joint.upperLimit; + break; + case BoardSide.right: + lowerLimit = joint.lowerLimit; + upperLimit = -joint.upperLimit; + } + + joint.setLimits(lowerLimit, upperLimit); + } +} diff --git a/lib/game/components/plunger.dart b/lib/game/components/plunger.dart index ed1ef36f..364fc35e 100644 --- a/lib/game/components/plunger.dart +++ b/lib/game/components/plunger.dart @@ -1,5 +1,5 @@ import 'package:flame_forge2d/flame_forge2d.dart'; -import 'package:pinball/game/game.dart'; +import 'package:pinball/game/game.dart' show Anchor; /// {@template plunger} /// [Plunger] serves as a spring, that shoots the ball on the right side of the diff --git a/lib/game/pinball_game.dart b/lib/game/pinball_game.dart index 7c701c09..308d8faf 100644 --- a/lib/game/pinball_game.dart +++ b/lib/game/pinball_game.dart @@ -1,16 +1,12 @@ import 'dart:async'; +import 'package:flame/input.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:pinball/game/game.dart'; -class PinballGame extends Forge2DGame with FlameBloc { - void spawnBall() { - add( - Ball(position: ballStartingPosition), - ); - } - +class PinballGame extends Forge2DGame + with FlameBloc, HasKeyboardHandlerComponents { // TODO(erickzanardo): Change to the plumber position late final ballStartingPosition = screenToWorld( Vector2( @@ -20,17 +16,86 @@ class PinballGame extends Forge2DGame with FlameBloc { ) - Vector2(0, -20); + // TODO(alestiago): Change to the design position. + late final flippersPosition = ballStartingPosition - Vector2(0, 5); + + @override + void onAttach() { + super.onAttach(); + spawnBall(); + } + + void spawnBall() { + add(Ball(position: ballStartingPosition)); + } + @override Future onLoad() async { addContactCallback(BallScorePointsCallback()); await add(BottomWall(this)); addContactCallback(BottomWallBallContactCallback()); + + unawaited(_addFlippers()); } - @override - void onAttach() { - super.onAttach(); - spawnBall(); + Future _addFlippers() async { + const spaceBetweenFlippers = 2; + final leftFlipper = Flipper.left( + position: Vector2( + flippersPosition.x - (Flipper.width / 2) - (spaceBetweenFlippers / 2), + flippersPosition.y, + ), + ); + await add(leftFlipper); + final leftFlipperAnchor = FlipperAnchor(flipper: leftFlipper); + await add(leftFlipperAnchor); + final leftFlipperRevoluteJointDef = FlipperAnchorRevoluteJointDef( + flipper: leftFlipper, + anchor: leftFlipperAnchor, + ); + // TODO(alestiago): Remove casting once the following is closed: + // https://github.com/flame-engine/forge2d/issues/36 + final leftFlipperRevoluteJoint = + world.createJoint(leftFlipperRevoluteJointDef) as RevoluteJoint; + + final rightFlipper = Flipper.right( + position: Vector2( + flippersPosition.x + (Flipper.width / 2) + (spaceBetweenFlippers / 2), + flippersPosition.y, + ), + ); + await add(rightFlipper); + final rightFlipperAnchor = FlipperAnchor(flipper: rightFlipper); + await add(rightFlipperAnchor); + final rightFlipperRevoluteJointDef = FlipperAnchorRevoluteJointDef( + flipper: rightFlipper, + anchor: rightFlipperAnchor, + ); + // TODO(alestiago): Remove casting once the following is closed: + // https://github.com/flame-engine/forge2d/issues/36 + final rightFlipperRevoluteJoint = + world.createJoint(rightFlipperRevoluteJointDef) as RevoluteJoint; + + // TODO(erickzanardo): Clean this once the issue is solved: + // https://github.com/flame-engine/flame/issues/1417 + // FIXME(erickzanardo): when mounted the initial position is not fully + // reached. + unawaited( + leftFlipper.hasMounted.future.whenComplete( + () => FlipperAnchorRevoluteJointDef.unlock( + leftFlipperRevoluteJoint, + leftFlipper.side, + ), + ), + ); + unawaited( + rightFlipper.hasMounted.future.whenComplete( + () => FlipperAnchorRevoluteJointDef.unlock( + rightFlipperRevoluteJoint, + rightFlipper.side, + ), + ), + ); } } diff --git a/test/game/components/board_side_test.dart b/test/game/components/board_side_test.dart new file mode 100644 index 00000000..3d6d3fa1 --- /dev/null +++ b/test/game/components/board_side_test.dart @@ -0,0 +1,27 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pinball/game/game.dart'; + +void main() { + group( + 'BoardSide', + () { + test('has two values', () { + expect(BoardSide.values.length, equals(2)); + }); + }, + ); + + group('BoardSideX', () { + test('isLeft is correct', () { + const side = BoardSide.left; + expect(side.isLeft, isTrue); + expect(side.isRight, isFalse); + }); + + test('isRight is correct', () { + const side = BoardSide.right; + expect(side.isLeft, isFalse); + expect(side.isRight, isTrue); + }); + }); +} diff --git a/test/game/components/flipper_test.dart b/test/game/components/flipper_test.dart new file mode 100644 index 00000000..b9894d9a --- /dev/null +++ b/test/game/components/flipper_test.dart @@ -0,0 +1,401 @@ +// ignore_for_file: cascade_invocations + +import 'dart:collection'; + +import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:flame_test/flame_test.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pinball/game/game.dart'; + +import '../../helpers/helpers.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final flameTester = FlameTester(PinballGame.new); + group( + 'Flipper', + () { + flameTester.test( + 'loads correctly', + (game) async { + final leftFlipper = Flipper.left(position: Vector2.zero()); + final rightFlipper = Flipper.right(position: Vector2.zero()); + await game.ensureAddAll([leftFlipper, rightFlipper]); + + expect(game.contains(leftFlipper), isTrue); + }, + ); + + group('constructor', () { + test('sets BoardSide', () { + final leftFlipper = Flipper.left(position: Vector2.zero()); + expect(leftFlipper.side, equals(leftFlipper.side)); + + final rightFlipper = Flipper.right(position: Vector2.zero()); + expect(rightFlipper.side, equals(rightFlipper.side)); + }); + }); + + group('body', () { + flameTester.test( + 'positions correctly', + (game) async { + final position = Vector2.all(10); + final flipper = Flipper.left(position: position); + await game.ensureAdd(flipper); + game.contains(flipper); + + expect(flipper.body.position, position); + }, + ); + + flameTester.test( + 'is dynamic', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + expect(flipper.body.bodyType, equals(BodyType.dynamic)); + }, + ); + + flameTester.test( + 'ignores gravity', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + expect(flipper.body.gravityScale, isZero); + }, + ); + + flameTester.test( + 'has greater mass than Ball', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + final ball = Ball(position: Vector2.zero()); + + await game.ensureAddAll([flipper, ball]); + + expect( + flipper.body.getMassData().mass, + greaterThan(ball.body.getMassData().mass), + ); + }, + ); + }); + + group('fixtures', () { + flameTester.test( + 'has three', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + expect(flipper.body.fixtures.length, equals(3)); + }, + ); + + flameTester.test( + 'has density', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final fixtures = flipper.body.fixtures; + final density = fixtures.fold( + 0, + (sum, fixture) => sum + fixture.density, + ); + + expect(density, greaterThan(0)); + }, + ); + }); + + group('onKeyEvent', () { + final leftKeys = UnmodifiableListView([ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.keyA, + ]); + final rightKeys = UnmodifiableListView([ + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.keyD, + ]); + + group('and Flipper is left', () { + late Flipper flipper; + + setUp(() { + flipper = Flipper.left(position: Vector2.zero()); + }); + + testRawKeyDownEvents(leftKeys, (event) { + flameTester.test( + 'moves upwards ' + 'when ${event.logicalKey.keyLabel} is pressed', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isPositive); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyUpEvents(leftKeys, (event) { + flameTester.test( + 'moves downwards ' + 'when ${event.logicalKey.keyLabel} is released', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isNegative); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyUpEvents(rightKeys, (event) { + flameTester.test( + 'does nothing ' + 'when ${event.logicalKey.keyLabel} is released', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isZero); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyDownEvents(rightKeys, (event) { + flameTester.test( + 'does nothing ' + 'when ${event.logicalKey.keyLabel} is pressed', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isZero); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + }); + + group('and Flipper is right', () { + late Flipper flipper; + + setUp(() { + flipper = Flipper.right(position: Vector2.zero()); + }); + + testRawKeyDownEvents(rightKeys, (event) { + flameTester.test( + 'moves upwards ' + 'when ${event.logicalKey.keyLabel} is pressed', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isPositive); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyUpEvents(rightKeys, (event) { + flameTester.test( + 'moves downwards ' + 'when ${event.logicalKey.keyLabel} is released', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isNegative); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyUpEvents(leftKeys, (event) { + flameTester.test( + 'does nothing ' + 'when ${event.logicalKey.keyLabel} is released', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isZero); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + + testRawKeyDownEvents(leftKeys, (event) { + flameTester.test( + 'does nothing ' + 'when ${event.logicalKey.keyLabel} is pressed', + (game) async { + await game.ensureAdd(flipper); + flipper.onKeyEvent(event, {}); + + expect(flipper.body.linearVelocity.y, isZero); + expect(flipper.body.linearVelocity.x, isZero); + }, + ); + }); + }); + }); + }, + ); + + group( + 'FlipperAnchor', + () { + flameTester.test( + 'position is at the left of the left Flipper', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + expect(flipperAnchor.body.position.x, equals(-Flipper.width / 2)); + }, + ); + + flameTester.test( + 'position is at the right of the right Flipper', + (game) async { + final flipper = Flipper.right(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + expect(flipperAnchor.body.position.x, equals(Flipper.width / 2)); + }, + ); + }, + ); + + group('FlipperAnchorRevoluteJointDef', () { + group('initializes with', () { + flameTester.test( + 'limits enabled', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + final jointDef = FlipperAnchorRevoluteJointDef( + flipper: flipper, + anchor: flipperAnchor, + ); + + expect(jointDef.enableLimit, isTrue); + }, + ); + + group('equal upper and lower limits', () { + flameTester.test( + 'when Flipper is left', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + final jointDef = FlipperAnchorRevoluteJointDef( + flipper: flipper, + anchor: flipperAnchor, + ); + + expect(jointDef.lowerAngle, equals(jointDef.upperAngle)); + }, + ); + + flameTester.test( + 'when Flipper is right', + (game) async { + final flipper = Flipper.right(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + final jointDef = FlipperAnchorRevoluteJointDef( + flipper: flipper, + anchor: flipperAnchor, + ); + + expect(jointDef.lowerAngle, equals(jointDef.upperAngle)); + }, + ); + }); + }); + + group( + 'unlocks', + () { + flameTester.test( + 'when Flipper is left', + (game) async { + final flipper = Flipper.left(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + final jointDef = FlipperAnchorRevoluteJointDef( + flipper: flipper, + anchor: flipperAnchor, + ); + final joint = game.world.createJoint(jointDef) as RevoluteJoint; + + FlipperAnchorRevoluteJointDef.unlock(joint, flipper.side); + + expect( + joint.upperLimit, + isNot(equals(joint.lowerLimit)), + ); + }, + ); + + flameTester.test( + 'when Flipper is right', + (game) async { + final flipper = Flipper.right(position: Vector2.zero()); + await game.ensureAdd(flipper); + + final flipperAnchor = FlipperAnchor(flipper: flipper); + await game.ensureAdd(flipperAnchor); + + final jointDef = FlipperAnchorRevoluteJointDef( + flipper: flipper, + anchor: flipperAnchor, + ); + final joint = game.world.createJoint(jointDef) as RevoluteJoint; + + FlipperAnchorRevoluteJointDef.unlock(joint, flipper.side); + + expect( + joint.upperLimit, + isNot(equals(joint.lowerLimit)), + ); + }, + ); + }, + ); + }); +} diff --git a/test/game/pinball_game_test.dart b/test/game/pinball_game_test.dart index 75a77aa9..4dc93b7f 100644 --- a/test/game/pinball_game_test.dart +++ b/test/game/pinball_game_test.dart @@ -1,9 +1,54 @@ +// 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/game/game.dart'; void main() { group('PinballGame', () { + TestWidgetsFlutterBinding.ensureInitialized(); + final flameTester = FlameTester(PinballGame.new); + // TODO(alestiago): test if [PinballGame] registers // [BallScorePointsCallback] once the following issue is resolved: // https://github.com/flame-engine/flame/issues/1416 + group( + 'components', + () { + group('Flippers', () { + bool Function(Component) flipperSelector(BoardSide side) => + (component) => component is Flipper && component.side == side; + + flameTester.test( + 'has only one left Flipper', + (game) async { + await game.ready(); + + expect( + () => game.children.singleWhere( + flipperSelector(BoardSide.left), + ), + returnsNormally, + ); + }, + ); + + flameTester.test( + 'has only one right Flipper', + (game) async { + await game.ready(); + + expect( + () => game.children.singleWhere( + flipperSelector(BoardSide.right), + ), + returnsNormally, + ); + }, + ); + }); + }, + ); }); } diff --git a/test/helpers/helpers.dart b/test/helpers/helpers.dart index 97bc22be..c2c1cd36 100644 --- a/test/helpers/helpers.dart +++ b/test/helpers/helpers.dart @@ -6,5 +6,6 @@ // https://opensource.org/licenses/MIT. export 'builders.dart'; +export 'key_testers.dart'; export 'mocks.dart'; export 'pump_app.dart'; diff --git a/test/helpers/key_testers.dart b/test/helpers/key_testers.dart new file mode 100644 index 00000000..04fed1da --- /dev/null +++ b/test/helpers/key_testers.dart @@ -0,0 +1,37 @@ +import 'package:flutter/services.dart'; +import 'package:meta/meta.dart'; +import 'package:mocktail/mocktail.dart'; + +import 'helpers.dart'; + +@isTest +void testRawKeyUpEvents( + List keys, + Function(RawKeyUpEvent) test, +) { + for (final key in keys) { + test(_mockKeyUpEvent(key)); + } +} + +RawKeyUpEvent _mockKeyUpEvent(LogicalKeyboardKey key) { + final event = MockRawKeyUpEvent(); + when(() => event.logicalKey).thenReturn(key); + return event; +} + +@isTest +void testRawKeyDownEvents( + List keys, + Function(RawKeyDownEvent) test, +) { + for (final key in keys) { + test(_mockKeyDownEvent(key)); + } +} + +RawKeyDownEvent _mockKeyDownEvent(LogicalKeyboardKey key) { + final event = MockRawKeyDownEvent(); + when(() => event.logicalKey).thenReturn(key); + return event; +} diff --git a/test/helpers/mocks.dart b/test/helpers/mocks.dart index b46e2c5c..da9fd537 100644 --- a/test/helpers/mocks.dart +++ b/test/helpers/mocks.dart @@ -1,4 +1,6 @@ import 'package:flame_forge2d/flame_forge2d.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; import 'package:mocktail/mocktail.dart'; import 'package:pinball/game/game.dart'; @@ -13,3 +15,17 @@ class MockBall extends Mock implements Ball {} class MockContact extends Mock implements Contact {} class MockGameBloc extends Mock implements GameBloc {} + +class MockRawKeyDownEvent extends Mock implements RawKeyDownEvent { + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return super.toString(); + } +} + +class MockRawKeyUpEvent extends Mock implements RawKeyUpEvent { + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return super.toString(); + } +}