You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
pinball/lib/game/pinball_game.dart

256 lines
7.2 KiB

// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'package:flame/components.dart';
import 'package:flame/game.dart';
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 <erickzanardoo@gmail.com> * 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 <erickzanardoo@gmail.com> Co-authored-by: Allison Ryan <allisonryan0002@gmail.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
3 years ago
import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:pinball/game/game.dart';
import 'package:pinball_audio/pinball_audio.dart';
import 'package:pinball_components/pinball_components.dart';
import 'package:pinball_flame/pinball_flame.dart';
import 'package:pinball_theme/pinball_theme.dart';
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 <erickzanardoo@gmail.com> * 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 <erickzanardoo@gmail.com> Co-authored-by: Allison Ryan <allisonryan0002@gmail.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
3 years ago
class PinballGame extends Forge2DGame
with
FlameBloc,
HasKeyboardHandlerComponents,
Controls<_GameBallsController>,
TapDetector {
PinballGame({
required this.characterTheme,
required this.audio,
}) {
images.prefix = '';
controller = _GameBallsController(this);
}
/// Identifier of the play button overlay
static const playButtonOverlay = 'play_button';
@override
Color backgroundColor() => Colors.transparent;
final CharacterTheme characterTheme;
final PinballAudio audio;
late final GameFlowController gameFlowController;
@override
Future<void> onLoad() async {
unawaited(add(gameFlowController = GameFlowController(this)));
unawaited(add(CameraController(this)));
unawaited(add(Backboard.waiting(position: Vector2(0, -88))));
await add(BoardBackgroundSpriteComponent());
await add(Drain());
await add(BottomGroup());
unawaited(addFromBlueprint(Boundaries()));
final launcher = Launcher();
unawaited(addFromBlueprint(launcher));
feat: implemented `Multipliers` (#231) * feat: added multipliers * feat: added multipliers to sandbox * test: tests and golden tests for multipliers * feat: multipliers controller * fix: missed assets load * refactor: multiplier refactored and tested * refactor: changed sandbox for multipliers * feat: multiplier controller * refactor: moved assets to constructor at sandbox * test: coverage for multipliers * test: removed test * refactor: coverage for multiplier * test: coverage for multiplier * chore: multiplier doc * Update packages/pinball_components/sandbox/lib/stories/multipliers/multipliers_game.dart Co-authored-by: Alejandro Santiago <dev@alestiago.com> * chore: little code refactor, doc * refactor: multiplier creation refactored * test: fixed tests for multipliers * refactor: changed properties names * refactor: multipliers cubit * test: refactored tests for multipliers * refactored: sandbow for multipliers * refactor: multipliers controller * test: tests for multiplier behavior * chore: analysis errors * feat: multipliers behavior with multiplier from gamebloc * refactor: changed toggle to next at multipliers * test: coverage for cubit * refactor: refactored multipliers and coverage * refactor: sandbox * test: flamebloctester * Update lib/game/components/multipliers/multipliers.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * Update packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_cubit.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * Update lib/game/components/multipliers/multipliers.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * Update packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_state.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * Update packages/pinball_components/lib/src/components/multiplier/cubit/multiplier_state.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * Update test/game/components/multipliers/behaviors/multipliers_behavior_test.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * test: fixed test names and golden files * test: golden tests * fix: fixed bloc bug for tests on multiplier behavior * chore: renamed rotation * chore: doc ignore * test: grouped * test: golden tests dir * Update packages/pinball_components/sandbox/lib/stories/multipliers/stories.dart Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com> * refactor: moved extension for multiplier value * chore: multiplier extension equalsTo name * fixed: missed method rename Co-authored-by: Alejandro Santiago <dev@alestiago.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
await add(Multipliers());
await add(FlutterForest());
await addFromBlueprint(SparkyScorch());
await addFromBlueprint(AndroidAcres());
await addFromBlueprint(DinoDesert());
unawaited(addFromBlueprint(Slingshots()));
await add(
GoogleWord(
position: Vector2(
BoardDimensions.bounds.center.dx - 4.1,
BoardDimensions.bounds.center.dy + 1.8,
),
),
);
feat: migration to new `ContactCallbacks` (#234) * feat: migrated to new ContactCallbacks * refactor: moved renderBody to super call * feat: defined AlienBumper behaviours * feat: included ParentIsA mixin * refactor: modified ContactCallbacksGroup * feat: resolved missing ContactCallbacks with Behaviors * refactor: removed unused ParentIsA * refactor: moved tests * fix: invalid export * refactor: renamed behaviours * test: tested pinball_components * refactor: removed "Behaviour" typo * docs: included TODO comment for generics * docs: included flame_bloc TODO comments * refactor: renamed ContacCallbacksGroup variable * docs: included doc comments where possible * docs: rephrased ContactBehaviour doc comment * test: included ContactBehavior tests * feat: implemented FlutterForestBonusBehavior * refactor: fixed analyser warnings * test: tested DashNestBumper * refactor: moved children to last arguement * test: included closing test * refactor: used barrel files as imports * docs: included flutter_bloc TODO * test: correctly tested GoogleWordBonusBehavior * refactor: moved flutter_forest_test.dart * test: fixed AlienZone typo * feat: removed FlutterForestCubit * test: closed streams * refactor: removed optional bloc parameter * refactor: added flame_bloc TODO comment * docs: included .test constructor docs * feat: included GoogleLetter.test * test: made blink test pass * fix: renamed theme to CharacterTheme * refactor: moved timer.stop(); * refactor: renamed hasBonus to achievedBonus * refactor: ignore public_member_api_docs for cubits * test: removed beginContact group * refactor: typos correction * docs: used correct AlienBumper reference * docs: removed TODO comment from ContactBehavior subclasses * docs: includes ScoringBehavior doc * feat: adjusted FlutterForest priorities Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
controller.attachTo(launcher.components.whereType<Plunger>().single);
feat: migration to new `ContactCallbacks` (#234) * feat: migrated to new ContactCallbacks * refactor: moved renderBody to super call * feat: defined AlienBumper behaviours * feat: included ParentIsA mixin * refactor: modified ContactCallbacksGroup * feat: resolved missing ContactCallbacks with Behaviors * refactor: removed unused ParentIsA * refactor: moved tests * fix: invalid export * refactor: renamed behaviours * test: tested pinball_components * refactor: removed "Behaviour" typo * docs: included TODO comment for generics * docs: included flame_bloc TODO comments * refactor: renamed ContacCallbacksGroup variable * docs: included doc comments where possible * docs: rephrased ContactBehaviour doc comment * test: included ContactBehavior tests * feat: implemented FlutterForestBonusBehavior * refactor: fixed analyser warnings * test: tested DashNestBumper * refactor: moved children to last arguement * test: included closing test * refactor: used barrel files as imports * docs: included flutter_bloc TODO * test: correctly tested GoogleWordBonusBehavior * refactor: moved flutter_forest_test.dart * test: fixed AlienZone typo * feat: removed FlutterForestCubit * test: closed streams * refactor: removed optional bloc parameter * refactor: added flame_bloc TODO comment * docs: included .test constructor docs * feat: included GoogleLetter.test * test: made blink test pass * fix: renamed theme to CharacterTheme * refactor: moved timer.stop(); * refactor: renamed hasBonus to achievedBonus * refactor: ignore public_member_api_docs for cubits * test: removed beginContact group * refactor: typos correction * docs: used correct AlienBumper reference * docs: removed TODO comment from ContactBehavior subclasses * docs: includes ScoringBehavior doc * feat: adjusted FlutterForest priorities Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
await super.onLoad();
}
BoardSide? focusedBoardSide;
@override
void onTapDown(TapDownInfo info) {
if (info.raw.kind == PointerDeviceKind.touch) {
final rocket = children.whereType<RocketSpriteComponent>().first;
final bounds = rocket.topLeftPosition & rocket.size;
// NOTE(wolfen): As long as Flame does not have https://github.com/flame-engine/flame/issues/1586 we need to check it at the highest level manually.
if (bounds.contains(info.eventPosition.game.toOffset())) {
children.whereType<Plunger>().first.pull();
} else {
final leftSide = info.eventPosition.widget.x < canvasSize.x / 2;
focusedBoardSide = leftSide ? BoardSide.left : BoardSide.right;
final flippers = descendants().whereType<Flipper>().where((flipper) {
return flipper.side == focusedBoardSide;
});
flippers.first.moveUp();
}
}
super.onTapDown(info);
}
@override
void onTapUp(TapUpInfo info) {
final rocket = descendants().whereType<RocketSpriteComponent>().first;
final bounds = rocket.topLeftPosition & rocket.size;
if (bounds.contains(info.eventPosition.game.toOffset())) {
children.whereType<Plunger>().first.release();
} else {
_moveFlippersDown();
}
super.onTapUp(info);
}
@override
void onTapCancel() {
children.whereType<Plunger>().first.release();
_moveFlippersDown();
super.onTapCancel();
}
void _moveFlippersDown() {
if (focusedBoardSide != null) {
final flippers = descendants().whereType<Flipper>().where((flipper) {
return flipper.side == focusedBoardSide;
});
flippers.first.moveDown();
focusedBoardSide = null;
}
}
}
class _GameBallsController extends ComponentController<PinballGame>
feat: game bloc multiplier (#213) * feat: added events for multiplier * feat: added events for increment, apply and reset multiplier * feat: added multiplier to game bloc state * test: test for multiplier at game bloc * test: added multiplier to game state * refactor: multiplier always increased by 1 * refactor: add multiplier state on BallLost * refactor: added round to game state and changed gameover and ball lost logic * test: fixed tests for game bloc * refactor: multiplier max value 6 at game bloc * test: fixed tests with new game over logic * chore: properties renamed and removed unused * Update lib/game/bloc/game_event.dart Co-authored-by: Alejandro Santiago <dev@alestiago.com> * fix: pubspec from main * refactor: pubspec from main * chore: removed unused import * feat: ball added event to game bloc * test: fixed test for ball added * feat: added BallAdded event on ball mounted * test: fixing tests for BallAdded * test: flamebloctester for ball added * test: refactored tests for pinballgame * refactor: BallAdded event on ball mounted * chore: removed unnecessary imports * test: refactor tests for pinball_game * refactor: use rounds instead of balls * refactor: changed BallLost event with RoundLost, and moved part of the logic to controlled_ball * test: tests for RoundLost * fix: fixed wrong tests for pinball_game * test: remove deleted balls property from GameState * chore: doc Co-authored-by: Alejandro Santiago <dev@alestiago.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
with BlocComponent<GameBloc, GameState> {
_GameBallsController(PinballGame game) : super(game);
late final Plunger _plunger;
@override
bool listenWhen(GameState? previousState, GameState newState) {
final noBallsLeft = component.descendants().whereType<Ball>().isEmpty;
feat: game bloc multiplier (#213) * feat: added events for multiplier * feat: added events for increment, apply and reset multiplier * feat: added multiplier to game bloc state * test: test for multiplier at game bloc * test: added multiplier to game state * refactor: multiplier always increased by 1 * refactor: add multiplier state on BallLost * refactor: added round to game state and changed gameover and ball lost logic * test: fixed tests for game bloc * refactor: multiplier max value 6 at game bloc * test: fixed tests with new game over logic * chore: properties renamed and removed unused * Update lib/game/bloc/game_event.dart Co-authored-by: Alejandro Santiago <dev@alestiago.com> * fix: pubspec from main * refactor: pubspec from main * chore: removed unused import * feat: ball added event to game bloc * test: fixed test for ball added * feat: added BallAdded event on ball mounted * test: fixing tests for BallAdded * test: flamebloctester for ball added * test: refactored tests for pinballgame * refactor: BallAdded event on ball mounted * chore: removed unnecessary imports * test: refactor tests for pinball_game * refactor: use rounds instead of balls * refactor: changed BallLost event with RoundLost, and moved part of the logic to controlled_ball * test: tests for RoundLost * fix: fixed wrong tests for pinball_game * test: remove deleted balls property from GameState * chore: doc Co-authored-by: Alejandro Santiago <dev@alestiago.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
final notGameOver = !newState.isGameOver;
feat: game bloc multiplier (#213) * feat: added events for multiplier * feat: added events for increment, apply and reset multiplier * feat: added multiplier to game bloc state * test: test for multiplier at game bloc * test: added multiplier to game state * refactor: multiplier always increased by 1 * refactor: add multiplier state on BallLost * refactor: added round to game state and changed gameover and ball lost logic * test: fixed tests for game bloc * refactor: multiplier max value 6 at game bloc * test: fixed tests with new game over logic * chore: properties renamed and removed unused * Update lib/game/bloc/game_event.dart Co-authored-by: Alejandro Santiago <dev@alestiago.com> * fix: pubspec from main * refactor: pubspec from main * chore: removed unused import * feat: ball added event to game bloc * test: fixed test for ball added * feat: added BallAdded event on ball mounted * test: fixing tests for BallAdded * test: flamebloctester for ball added * test: refactored tests for pinballgame * refactor: BallAdded event on ball mounted * chore: removed unnecessary imports * test: refactor tests for pinball_game * refactor: use rounds instead of balls * refactor: changed BallLost event with RoundLost, and moved part of the logic to controlled_ball * test: tests for RoundLost * fix: fixed wrong tests for pinball_game * test: remove deleted balls property from GameState * chore: doc Co-authored-by: Alejandro Santiago <dev@alestiago.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
return noBallsLeft && notGameOver;
}
@override
void onNewState(GameState state) {
super.onNewState(state);
_spawnBall();
}
@override
Future<void> onLoad() async {
await super.onLoad();
_spawnBall();
}
void _spawnBall() {
final ball = ControlledBall.launch(
feat: game bloc multiplier (#213) * feat: added events for multiplier * feat: added events for increment, apply and reset multiplier * feat: added multiplier to game bloc state * test: test for multiplier at game bloc * test: added multiplier to game state * refactor: multiplier always increased by 1 * refactor: add multiplier state on BallLost * refactor: added round to game state and changed gameover and ball lost logic * test: fixed tests for game bloc * refactor: multiplier max value 6 at game bloc * test: fixed tests with new game over logic * chore: properties renamed and removed unused * Update lib/game/bloc/game_event.dart Co-authored-by: Alejandro Santiago <dev@alestiago.com> * fix: pubspec from main * refactor: pubspec from main * chore: removed unused import * feat: ball added event to game bloc * test: fixed test for ball added * feat: added BallAdded event on ball mounted * test: fixing tests for BallAdded * test: flamebloctester for ball added * test: refactored tests for pinballgame * refactor: BallAdded event on ball mounted * chore: removed unnecessary imports * test: refactor tests for pinball_game * refactor: use rounds instead of balls * refactor: changed BallLost event with RoundLost, and moved part of the logic to controlled_ball * test: tests for RoundLost * fix: fixed wrong tests for pinball_game * test: remove deleted balls property from GameState * chore: doc Co-authored-by: Alejandro Santiago <dev@alestiago.com> Co-authored-by: Allison Ryan <77211884+allisonryan0002@users.noreply.github.com>
2 years ago
characterTheme: component.characterTheme,
)..initialPosition = Vector2(
_plunger.body.position.x,
_plunger.body.position.y - Ball.size.y,
);
component.add(ball);
}
/// Attaches the controller to the plunger.
// TODO(alestiago): Remove this method and use onLoad instead.
// ignore: use_setters_to_change_properties
void attachTo(Plunger plunger) {
_plunger = plunger;
}
}
class DebugPinballGame extends PinballGame with FPSCounter {
DebugPinballGame({
required CharacterTheme characterTheme,
required PinballAudio audio,
}) : super(
characterTheme: characterTheme,
audio: audio,
) {
controller = _DebugGameBallsController(this);
}
@override
Future<void> onLoad() async {
await super.onLoad();
await add(_DebugInformation());
}
// TODO(allisonryan0002): Remove after google letters have been correctly
// placed.
// Future<void> _loadBackground() async {
// final sprite = await loadSprite(
// Assets.images.components.background.path,
// );
// final spriteComponent = SpriteComponent(
// sprite: sprite,
// size: Vector2(120, 160),
// anchor: Anchor.center,
// )
// ..position = Vector2(0, -7.8)
// ..priority = RenderPriority.boardBackground;
// await add(spriteComponent);
// }
@override
void onTapUp(TapUpInfo info) {
super.onTapUp(info);
if (info.raw.kind == PointerDeviceKind.mouse) {
add(ControlledBall.debug()..initialPosition = info.eventPosition.game);
}
}
}
class _DebugGameBallsController extends _GameBallsController {
_DebugGameBallsController(PinballGame game) : super(game);
}
// TODO(wolfenrain): investigate this CI failure.
// coverage:ignore-start
class _DebugInformation extends Component with HasGameRef<DebugPinballGame> {
_DebugInformation() : super(priority: RenderPriority.debugInfo);
@override
PositionType get positionType => PositionType.widget;
final _debugTextPaint = TextPaint(
style: const TextStyle(
color: Colors.green,
fontSize: 10,
),
);
final _debugBackgroundPaint = Paint()..color = Colors.white;
@override
void render(Canvas canvas) {
final debugText = [
'FPS: ${gameRef.fps().toStringAsFixed(1)}',
'BALLS: ${gameRef.descendants().whereType<ControlledBall>().length}',
].join(' | ');
final height = _debugTextPaint.measureTextHeight(debugText);
final position = Vector2(0, gameRef.camera.canvasSize.y - height);
canvas.drawRect(
position & Vector2(gameRef.camera.canvasSize.x, height),
_debugBackgroundPaint,
);
_debugTextPaint.render(canvas, debugText, position);
}
}
// coverage:ignore-end