Merge branch 'main' into fix/score-points-user-data

pull/67/head
Alejandro Santiago 4 years ago committed by GitHub
commit 6d50fb15a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -8,3 +8,4 @@ jobs:
with: with:
flutter_channel: stable flutter_channel: stable
flutter_version: 2.10.0 flutter_version: 2.10.0
coverage_excludes: "lib/gen/*.dart"

@ -1 +1,4 @@
include: package:very_good_analysis/analysis_options.2.4.0.yaml include: package:very_good_analysis/analysis_options.2.4.0.yaml
analyzer:
exclude:
- lib/**/*.gen.dart

@ -1,6 +1,7 @@
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/gen/assets.gen.dart';
/// {@template ball} /// {@template ball}
/// A solid, [BodyType.dynamic] sphere that rolls and bounces along the /// A solid, [BodyType.dynamic] sphere that rolls and bounces along the
@ -20,15 +21,10 @@ class Ball extends BodyComponent<PinballGame> with InitialPosition, Layered {
/// The size of the [Ball] /// The size of the [Ball]
final Vector2 size = Vector2.all(2); final Vector2 size = Vector2.all(2);
/// Asset location of the sprite that renders with the [Ball].
///
/// Sprite is preloaded by [PinballGameAssetsX].
static const spritePath = 'components/ball.png';
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
final sprite = await gameRef.loadSprite(spritePath); final sprite = await gameRef.loadSprite(Assets.images.components.ball.path);
final tint = gameRef.theme.characterTheme.ballColor.withOpacity(0.5); final tint = gameRef.theme.characterTheme.ballColor.withOpacity(0.5);
await add( await add(
SpriteComponent( SpriteComponent(

@ -3,29 +3,27 @@ import 'package:pinball/game/game.dart';
/// {@template board} /// {@template board}
/// The main flat surface of the [PinballGame], where the [Flipper]s, /// The main flat surface of the [PinballGame], where the [Flipper]s,
/// [RoundBumper]s, [SlingShot]s are arranged. /// [RoundBumper]s, [Kicker]s are arranged.
/// {entemplate} /// {entemplate}
class Board extends Component { class Board extends Component {
/// {@macro board} /// {@macro board}
Board({required Vector2 size}) : _size = size; Board();
final Vector2 _size;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
// TODO(alestiago): adjust positioning once sprites are added. // TODO(alestiago): adjust positioning once sprites are added.
final bottomGroup = _BottomGroup( final bottomGroup = _BottomGroup(
position: Vector2( position: Vector2(
_size.x / 2, PinballGame.boardBounds.center.dx,
_size.y / 1.25, PinballGame.boardBounds.bottom + 10,
), ),
spacing: 2, spacing: 2,
); );
final dashForest = _FlutterForest( final dashForest = _FlutterForest(
position: Vector2( position: Vector2(
_size.x / 1.25, PinballGame.boardBounds.right - 20,
_size.y / 4.25, PinballGame.boardBounds.top - 20,
), ),
); );
@ -76,7 +74,7 @@ class _FlutterForest extends Component {
/// {@template bottom_group} /// {@template bottom_group}
/// Grouping of the board's bottom [Component]s. /// Grouping of the board's bottom [Component]s.
/// ///
/// The [_BottomGroup] consists of[Flipper]s, [Baseboard]s and [SlingShot]s. /// The [_BottomGroup] consists of[Flipper]s, [Baseboard]s and [Kicker]s.
/// {@endtemplate} /// {@endtemplate}
// TODO(alestiago): Consider renaming once entire Board is defined. // TODO(alestiago): Consider renaming once entire Board is defined.
class _BottomGroup extends Component { class _BottomGroup extends Component {
@ -94,7 +92,7 @@ class _BottomGroup extends Component {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
final spacing = this.spacing + Flipper.width / 2; final spacing = this.spacing + Flipper.size.x / 2;
final rightSide = _BottomGroupSide( final rightSide = _BottomGroupSide(
side: BoardSide.right, side: BoardSide.right,
position: position + Vector2(spacing, 0), position: position + Vector2(spacing, 0),
@ -135,17 +133,17 @@ class _BottomGroupSide extends Component {
final baseboard = Baseboard(side: _side) final baseboard = Baseboard(side: _side)
..initialPosition = _position + ..initialPosition = _position +
Vector2( Vector2(
(Flipper.width * direction) - direction, (Flipper.size.x * direction) - direction,
Flipper.height, Flipper.size.y,
); );
final slingShot = SlingShot( final kicker = Kicker(
side: _side, side: _side,
)..initialPosition = _position + )..initialPosition = _position +
Vector2( Vector2(
(Flipper.width) * direction, (Flipper.size.x) * direction,
Flipper.height + SlingShot.size.y, Flipper.size.y + Kicker.size.y,
); );
await addAll([flipper, baseboard, slingShot]); await addAll([flipper, baseboard, kicker]);
} }
} }

@ -3,7 +3,7 @@ import 'package:pinball/game/game.dart';
/// Indicates a side of the board. /// Indicates a side of the board.
/// ///
/// Usually used to position or mirror elements of a [PinballGame]; such as a /// Usually used to position or mirror elements of a [PinballGame]; such as a
/// [Flipper] or [SlingShot]. /// [Flipper] or [Kicker].
enum BoardSide { enum BoardSide {
/// The left side of the board. /// The left side of the board.
left, left,

@ -36,31 +36,39 @@ class BonusWord extends Component with BlocComponent<GameBloc, GameState> {
for (var i = 0; i < letters.length; i++) { for (var i = 0; i < letters.length; i++) {
final letter = letters[i]; final letter = letters[i];
letter.add( letter
SequenceEffect( ..isEnabled = false
[ ..add(
ColorEffect( SequenceEffect(
i.isOdd ? BonusLetter._activeColor : BonusLetter._disableColor, [
const Offset(0, 1),
EffectController(duration: 0.25),
),
ColorEffect(
i.isOdd ? BonusLetter._disableColor : BonusLetter._activeColor,
const Offset(0, 1),
EffectController(duration: 0.25),
),
],
repeatCount: 4,
)..onFinishCallback = () {
letter.add(
ColorEffect( ColorEffect(
BonusLetter._disableColor, i.isOdd
? BonusLetter._activeColor
: BonusLetter._disableColor,
const Offset(0, 1), const Offset(0, 1),
EffectController(duration: 0.25), EffectController(duration: 0.25),
), ),
); ColorEffect(
}, i.isOdd
); ? BonusLetter._disableColor
: BonusLetter._activeColor,
const Offset(0, 1),
EffectController(duration: 0.25),
),
],
repeatCount: 4,
)..onFinishCallback = () {
letter
..isEnabled = true
..add(
ColorEffect(
BonusLetter._disableColor,
const Offset(0, 1),
EffectController(duration: 0.25),
),
);
},
);
} }
} }
} }
@ -107,6 +115,13 @@ class BonusLetter extends BodyComponent<PinballGame>
final String _letter; final String _letter;
final int _index; final int _index;
/// Indicates if a [BonusLetter] can be activated on [Ball] contact.
///
/// It is disabled whilst animating and enabled again once the animation
/// completes. The animation is triggered when [GameBonus.word] is
/// awarded.
bool isEnabled = true;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
@ -172,6 +187,8 @@ class BonusLetterBallContactCallback
extends ContactCallback<Ball, BonusLetter> { extends ContactCallback<Ball, BonusLetter> {
@override @override
void begin(Ball ball, BonusLetter bonusLetter, Contact contact) { void begin(Ball ball, BonusLetter bonusLetter, Contact contact) {
bonusLetter.activate(); if (bonusLetter.isEnabled) {
bonusLetter.activate();
}
} }
} }

@ -7,6 +7,7 @@ export 'flipper.dart';
export 'initial_position.dart'; export 'initial_position.dart';
export 'jetpack_ramp.dart'; export 'jetpack_ramp.dart';
export 'joint_anchor.dart'; export 'joint_anchor.dart';
export 'kicker.dart';
export 'launcher_ramp.dart'; export 'launcher_ramp.dart';
export 'layer.dart'; export 'layer.dart';
export 'pathway.dart'; export 'pathway.dart';
@ -14,6 +15,5 @@ export 'plunger.dart';
export 'ramp_opening.dart'; export 'ramp_opening.dart';
export 'round_bumper.dart'; export 'round_bumper.dart';
export 'score_points.dart'; export 'score_points.dart';
export 'sling_shot.dart';
export 'spaceship.dart'; export 'spaceship.dart';
export 'wall.dart'; export 'wall.dart';

@ -2,11 +2,11 @@ import 'dart:async';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flame/components.dart'; import 'package:flame/components.dart';
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/gen/assets.gen.dart';
/// {@template flipper} /// {@template flipper}
/// A bat, typically found in pairs at the bottom of the board. /// A bat, typically found in pairs at the bottom of the board.
@ -53,16 +53,8 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition {
} }
} }
/// Asset location of the sprite that renders with the [Flipper]. /// The size of the [Flipper].
/// static final size = Vector2(12, 2.8);
/// Sprite is preloaded by [PinballGameAssetsX].
static const spritePath = 'components/flipper.png';
/// 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 speed required to move the [Flipper] to its highest position.
/// ///
@ -94,10 +86,12 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition {
/// Loads the sprite that renders with the [Flipper]. /// Loads the sprite that renders with the [Flipper].
Future<void> _loadSprite() async { Future<void> _loadSprite() async {
final sprite = await gameRef.loadSprite(spritePath); final sprite = await gameRef.loadSprite(
Assets.images.components.flipper.path,
);
final spriteComponent = SpriteComponent( final spriteComponent = SpriteComponent(
sprite: sprite, sprite: sprite,
size: Vector2(width, height), size: size,
anchor: Anchor.center, anchor: Anchor.center,
); );
@ -134,21 +128,21 @@ class Flipper extends BodyComponent with KeyboardHandler, InitialPosition {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
final isLeft = side.isLeft; final isLeft = side.isLeft;
final bigCircleShape = CircleShape()..radius = height / 2; final bigCircleShape = CircleShape()..radius = 1.75;
bigCircleShape.position.setValues( bigCircleShape.position.setValues(
isLeft isLeft
? -(width / 2) + bigCircleShape.radius ? -(size.x / 2) + bigCircleShape.radius
: (width / 2) - bigCircleShape.radius, : (size.x / 2) - bigCircleShape.radius,
0, 0,
); );
final bigCircleFixtureDef = FixtureDef(bigCircleShape); final bigCircleFixtureDef = FixtureDef(bigCircleShape);
fixturesDef.add(bigCircleFixtureDef); fixturesDef.add(bigCircleFixtureDef);
final smallCircleShape = CircleShape()..radius = bigCircleShape.radius / 2; final smallCircleShape = CircleShape()..radius = 0.9;
smallCircleShape.position.setValues( smallCircleShape.position.setValues(
isLeft isLeft
? (width / 2) - smallCircleShape.radius ? (size.x / 2) - smallCircleShape.radius
: -(width / 2) + smallCircleShape.radius, : -(size.x / 2) + smallCircleShape.radius,
0, 0,
); );
final smallCircleFixtureDef = FixtureDef(smallCircleShape); final smallCircleFixtureDef = FixtureDef(smallCircleShape);
@ -227,8 +221,8 @@ class FlipperAnchor extends JointAnchor {
}) { }) {
initialPosition = Vector2( initialPosition = Vector2(
flipper.side.isLeft flipper.side.isLeft
? flipper.body.position.x - Flipper.width / 2 ? flipper.body.position.x - Flipper.size.x / 2
: flipper.body.position.x + Flipper.width / 2, : flipper.body.position.x + Flipper.size.x / 2,
flipper.body.position.y, flipper.body.position.y,
); );
} }

@ -30,22 +30,23 @@ class JetpackRamp extends Component with HasGameRef<PinballGame> {
// TODO(ruialonso): Use a bezier curve once control points are defined. // TODO(ruialonso): Use a bezier curve once control points are defined.
color: const Color.fromARGB(255, 8, 218, 241), color: const Color.fromARGB(255, 8, 218, 241),
center: position, center: position,
width: 80, width: 5,
radius: 200, radius: 18,
angle: 7 * math.pi / 6, angle: math.pi,
rotation: -math.pi / 18, rotation: math.pi,
) )..layer = layer;
..initialPosition = position
..layer = layer;
final leftOpening = _JetpackRampOpening( final leftOpening = _JetpackRampOpening(
rotation: 15 * math.pi / 180, outsideLayer: Layer.spaceship,
rotation: math.pi,
) )
..initialPosition = position + Vector2(-27, 21) ..initialPosition = position - Vector2(2, 22)
..layer = Layer.opening; ..layer = Layer.jetpack;
final rightOpening = _JetpackRampOpening( final rightOpening = _JetpackRampOpening(
rotation: -math.pi / 20, rotation: math.pi,
) )
..initialPosition = position + Vector2(-11.2, 22.5) ..initialPosition = position - Vector2(-13, 22)
..layer = Layer.opening; ..layer = Layer.opening;
await addAll([ await addAll([
@ -63,10 +64,12 @@ class JetpackRamp extends Component with HasGameRef<PinballGame> {
class _JetpackRampOpening extends RampOpening { class _JetpackRampOpening extends RampOpening {
/// {@macro jetpack_ramp_opening} /// {@macro jetpack_ramp_opening}
_JetpackRampOpening({ _JetpackRampOpening({
Layer? outsideLayer,
required double rotation, required double rotation,
}) : _rotation = rotation, }) : _rotation = rotation,
super( super(
pathwayLayer: Layer.jetpack, pathwayLayer: Layer.jetpack,
outsideLayer: outsideLayer,
orientation: RampOrientation.down, orientation: RampOrientation.down,
); );

@ -6,15 +6,15 @@ import 'package:flutter/material.dart';
import 'package:geometry/geometry.dart' as geometry show centroid; import 'package:geometry/geometry.dart' as geometry show centroid;
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
/// {@template sling_shot} /// {@template kicker}
/// Triangular [BodyType.static] body that propels the [Ball] towards the /// Triangular [BodyType.static] body that propels the [Ball] towards the
/// opposite side. /// opposite side.
/// ///
/// [SlingShot]s are usually positioned above each [Flipper]. /// [Kicker]s are usually positioned above each [Flipper].
/// {@endtemplate sling_shot} /// {@endtemplate kicker}
class SlingShot extends BodyComponent with InitialPosition { class Kicker extends BodyComponent with InitialPosition {
/// {@macro sling_shot} /// {@macro kicker}
SlingShot({ Kicker({
required BoardSide side, required BoardSide side,
}) : _side = side { }) : _side = side {
// TODO(alestiago): Use sprite instead of color when provided. // TODO(alestiago): Use sprite instead of color when provided.
@ -23,14 +23,14 @@ class SlingShot extends BodyComponent with InitialPosition {
..style = PaintingStyle.fill; ..style = PaintingStyle.fill;
} }
/// Whether the [SlingShot] is on the left or right side of the board. /// Whether the [Kicker] is on the left or right side of the board.
/// ///
/// A [SlingShot] with [BoardSide.left] propels the [Ball] to the right, /// A [Kicker] with [BoardSide.left] propels the [Ball] to the right,
/// whereas a [SlingShot] with [BoardSide.right] propels the [Ball] to the /// whereas a [Kicker] with [BoardSide.right] propels the [Ball] to the
/// left. /// left.
final BoardSide _side; final BoardSide _side;
/// The size of the [SlingShot] body. /// The size of the [Kicker] body.
// TODO(alestiago): Use size from PositionedBodyComponent instead, // TODO(alestiago): Use size from PositionedBodyComponent instead,
// once a sprite is given. // once a sprite is given.
static final Vector2 size = Vector2(4, 10); static final Vector2 size = Vector2(4, 10);
@ -78,7 +78,7 @@ class SlingShot extends BodyComponent with InitialPosition {
final bottomLineFixtureDef = FixtureDef(bottomEdge)..friction = 0; final bottomLineFixtureDef = FixtureDef(bottomEdge)..friction = 0;
fixturesDefs.add(bottomLineFixtureDef); fixturesDefs.add(bottomLineFixtureDef);
final kickerEdge = EdgeShape() final bouncyEdge = EdgeShape()
..set( ..set(
upperCircle.position + upperCircle.position +
Vector2( Vector2(
@ -92,11 +92,11 @@ class SlingShot extends BodyComponent with InitialPosition {
), ),
); );
final kickerFixtureDef = FixtureDef(kickerEdge) final bouncyFixtureDef = FixtureDef(bouncyEdge)
// TODO(alestiago): Play with restitution value once game is bundled. // TODO(alestiago): Play with restitution value once game is bundled.
..restitution = 10.0 ..restitution = 10.0
..friction = 0; ..friction = 0;
fixturesDefs.add(kickerFixtureDef); fixturesDefs.add(bouncyFixtureDef);
// TODO(alestiago): Evaluate if there is value on centering the fixtures. // TODO(alestiago): Evaluate if there is value on centering the fixtures.
final centroid = geometry.centroid( final centroid = geometry.centroid(

@ -28,26 +28,27 @@ class LauncherRamp extends Component with HasGameRef<PinballGame> {
final straightPath = Pathway.straight( final straightPath = Pathway.straight(
color: const Color.fromARGB(255, 34, 255, 0), color: const Color.fromARGB(255, 34, 255, 0),
start: Vector2(0, 0), start: Vector2(position.x, position.y),
end: Vector2(0, 700), end: Vector2(position.x, 74),
width: 80, width: 5,
) )
..initialPosition = position ..initialPosition = position
..layer = layer; ..layer = layer;
final curvedPath = Pathway.arc( final curvedPath = Pathway.arc(
color: const Color.fromARGB(255, 251, 255, 0), color: const Color.fromARGB(255, 251, 255, 0),
center: position + Vector2(-29, -8), center: position + Vector2(-1, 68),
radius: 300, radius: 20,
angle: 10 * math.pi / 9, angle: 8 * math.pi / 9,
width: 80, width: 5,
) rotation: math.pi,
..initialPosition = position + Vector2(-28.8, -6) )..layer = layer;
..layer = layer;
final leftOpening = _LauncherRampOpening(rotation: 13 * math.pi / 180) final leftOpening = _LauncherRampOpening(rotation: 13 * math.pi / 180)
..initialPosition = position + Vector2(-72.5, 12) ..initialPosition = position + Vector2(1, 49)
..layer = Layer.opening; ..layer = Layer.opening;
final rightOpening = _LauncherRampOpening(rotation: 0) final rightOpening = _LauncherRampOpening(rotation: 0)
..initialPosition = position + Vector2(-46.8, 17) ..initialPosition = position + Vector2(-16, 46)
..layer = Layer.opening; ..layer = Layer.opening;
await addAll([ await addAll([

@ -55,6 +55,9 @@ enum Layer {
/// Collide only with Launcher group elements. /// Collide only with Launcher group elements.
launcher, launcher,
/// Collide only with Spaceship group elements.
spaceship,
} }
/// {@template layer_mask_bits} /// {@template layer_mask_bits}
@ -81,6 +84,8 @@ extension LayerMaskBits on Layer {
return 0x0002; return 0x0002;
case Layer.launcher: case Layer.launcher:
return 0x0005; return 0x0005;
case Layer.spaceship:
return 0x000A;
} }
} }
} }

@ -150,10 +150,7 @@ class Pathway extends BodyComponent with InitialPosition, Layered {
final fixturesDef = <FixtureDef>[]; final fixturesDef = <FixtureDef>[];
for (final path in _paths) { for (final path in _paths) {
final chain = ChainShape() final chain = ChainShape()..createChain(path);
..createChain(
path.map(gameRef.screenToWorld).toList(),
);
fixturesDef.add(FixtureDef(chain)); fixturesDef.add(FixtureDef(chain));
} }

@ -1,4 +1,4 @@
import 'package:flame/input.dart'; import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/services.dart'; import 'package:flutter/services.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';

@ -27,15 +27,21 @@ abstract class RampOpening extends BodyComponent with InitialPosition, Layered {
/// {@macro ramp_opening} /// {@macro ramp_opening}
RampOpening({ RampOpening({
required Layer pathwayLayer, required Layer pathwayLayer,
Layer? outsideLayer,
required this.orientation, required this.orientation,
}) : _pathwayLayer = pathwayLayer { }) : _pathwayLayer = pathwayLayer,
_outsideLayer = outsideLayer ?? Layer.board {
layer = Layer.board; layer = Layer.board;
} }
final Layer _pathwayLayer; final Layer _pathwayLayer;
final Layer _outsideLayer;
/// Mask of category bits for collision inside [Pathway]. /// Mask of category bits for collision inside [Pathway].
Layer get pathwayLayer => _pathwayLayer; Layer get pathwayLayer => _pathwayLayer;
/// Mask of category bits for collision outside [Pathway].
Layer get outsideLayer => _outsideLayer;
/// The [Shape] of the [RampOpening]. /// The [Shape] of the [RampOpening].
Shape get shape; Shape get shape;
@ -85,7 +91,7 @@ class RampOpeningBallContactCallback<Opening extends RampOpening>
@override @override
void end(Ball ball, Opening opening, Contact _) { void end(Ball ball, Opening opening, Contact _) {
if (!_ballsInside.contains(ball)) { if (!_ballsInside.contains(ball)) {
ball.layer = Layer.board; ball.layer = opening.outsideLayer;
} else { } else {
// TODO(ruimiguel): change this code. Check what happens with ball that // TODO(ruimiguel): change this code. Check what happens with ball that
// slightly touch Opening and goes out again. With InitialPosition change // slightly touch Opening and goes out again. With InitialPosition change
@ -97,7 +103,7 @@ class RampOpeningBallContactCallback<Opening extends RampOpening>
ball.body.linearVelocity.y > 0); ball.body.linearVelocity.y > 0);
if (isBallOutsideOpening) { if (isBallOutsideOpening) {
ball.layer = Layer.board; ball.layer = opening.outsideLayer;
_ballsInside.remove(ball); _ballsInside.remove(ball);
} }
} }

@ -7,10 +7,7 @@ import 'package:flame/components.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/flame/blueprint.dart'; import 'package:pinball/flame/blueprint.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/gen/assets.gen.dart';
// TODO(erickzanardo): change this to use the layer class
// that will be introduced on the path PR
const _spaceShipBits = 0x0002;
/// A [Blueprint] which creates the spaceship feature. /// A [Blueprint] which creates the spaceship feature.
class Spaceship extends Forge2DBlueprint { class Spaceship extends Forge2DBlueprint {
@ -19,7 +16,10 @@ class Spaceship extends Forge2DBlueprint {
@override @override
void build() { void build() {
final position = Vector2(20, -24); final position = Vector2(
PinballGame.boardBounds.left + radius + 0.5,
PinballGame.boardBounds.center.dy + 34,
);
addAllContactCallback([ addAllContactCallback([
SpaceshipHoleBallContactCallback(), SpaceshipHoleBallContactCallback(),
@ -41,22 +41,18 @@ class Spaceship extends Forge2DBlueprint {
/// {@template spaceship_saucer} /// {@template spaceship_saucer}
/// A [BodyComponent] for the base, or the saucer of the spaceship /// A [BodyComponent] for the base, or the saucer of the spaceship
/// {@endtemplate} /// {@endtemplate}
class SpaceshipSaucer extends BodyComponent with InitialPosition { class SpaceshipSaucer extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_saucer} /// {@macro spaceship_saucer}
SpaceshipSaucer() : super(priority: 2); SpaceshipSaucer() : super(priority: 2) {
layer = Layer.spaceship;
/// Path for the base sprite }
static const saucerSpritePath = 'components/spaceship/saucer.png';
/// Path for the upper wall sprite
static const upperWallPath = 'components/spaceship/upper.png';
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
final sprites = await Future.wait([ final sprites = await Future.wait([
gameRef.loadSprite(saucerSpritePath), gameRef.loadSprite(Assets.images.components.spaceship.saucer.path),
gameRef.loadSprite(upperWallPath), gameRef.loadSprite(Assets.images.components.spaceship.upper.path),
]); ]);
await add( await add(
@ -90,10 +86,7 @@ class SpaceshipSaucer extends BodyComponent with InitialPosition {
return world.createBody(bodyDef) return world.createBody(bodyDef)
..createFixture( ..createFixture(
FixtureDef(circleShape) FixtureDef(circleShape)..isSensor = true,
..isSensor = true
..filter.maskBits = _spaceShipBits
..filter.categoryBits = _spaceShipBits,
); );
} }
} }
@ -106,14 +99,13 @@ class SpaceshipBridgeTop extends BodyComponent with InitialPosition {
/// {@macro spaceship_bridge_top} /// {@macro spaceship_bridge_top}
SpaceshipBridgeTop() : super(priority: 6); SpaceshipBridgeTop() : super(priority: 6);
/// Path to the top of this sprite
static const spritePath = 'components/spaceship/android-top.png';
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
final sprite = await gameRef.loadSprite(spritePath); final sprite = await gameRef.loadSprite(
Assets.images.components.spaceship.androidTop.path,
);
await add( await add(
SpriteComponent( SpriteComponent(
sprite: sprite, sprite: sprite,
@ -138,12 +130,11 @@ class SpaceshipBridgeTop extends BodyComponent with InitialPosition {
/// The main part of the [SpaceshipBridge], this [BodyComponent] /// The main part of the [SpaceshipBridge], this [BodyComponent]
/// provides both the collision and the rotation animation for the bridge. /// provides both the collision and the rotation animation for the bridge.
/// {@endtemplate} /// {@endtemplate}
class SpaceshipBridge extends BodyComponent with InitialPosition { class SpaceshipBridge extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_bridge} /// {@macro spaceship_bridge}
SpaceshipBridge() : super(priority: 3); SpaceshipBridge() : super(priority: 3) {
layer = Layer.spaceship;
/// Path to the spaceship bridge }
static const spritePath = 'components/spaceship/android-bottom.png';
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
@ -151,7 +142,9 @@ class SpaceshipBridge extends BodyComponent with InitialPosition {
renderBody = false; renderBody = false;
final sprite = await gameRef.images.load(spritePath); final sprite = await gameRef.images.load(
Assets.images.components.spaceship.androidBottom.path,
);
await add( await add(
SpriteAnimationComponent.fromFrameData( SpriteAnimationComponent.fromFrameData(
sprite, sprite,
@ -177,10 +170,7 @@ class SpaceshipBridge extends BodyComponent with InitialPosition {
return world.createBody(bodyDef) return world.createBody(bodyDef)
..createFixture( ..createFixture(
FixtureDef(circleShape) FixtureDef(circleShape)..restitution = 0.4,
..restitution = 0.4
..filter.maskBits = _spaceShipBits
..filter.categoryBits = _spaceShipBits,
); );
} }
} }
@ -190,34 +180,29 @@ class SpaceshipBridge extends BodyComponent with InitialPosition {
/// the spaceship area in order to modify its filter data so the ball /// the spaceship area in order to modify its filter data so the ball
/// can correctly collide only with the Spaceship /// can correctly collide only with the Spaceship
/// {@endtemplate} /// {@endtemplate}
// TODO(erickzanardo): Use RampOpening once provided. class SpaceshipEntrance extends RampOpening {
class SpaceshipEntrance extends BodyComponent with InitialPosition {
/// {@macro spaceship_entrance} /// {@macro spaceship_entrance}
SpaceshipEntrance(); SpaceshipEntrance()
: super(
pathwayLayer: Layer.spaceship,
orientation: RampOrientation.up,
) {
layer = Layer.spaceship;
}
@override @override
Body createBody() { Shape get shape {
final entranceShape = PolygonShape() const radius = Spaceship.radius * 2;
return PolygonShape()
..setAsEdge( ..setAsEdge(
Vector2( Vector2(
Spaceship.radius * cos(20 * pi / 180), radius * cos(20 * pi / 180),
Spaceship.radius * sin(20 * pi / 180), radius * sin(20 * pi / 180),
), )..rotate(90 * pi / 180),
Vector2( Vector2(
Spaceship.radius * cos(340 * pi / 180), radius * cos(340 * pi / 180),
Spaceship.radius * sin(340 * pi / 180), radius * sin(340 * pi / 180),
), )..rotate(90 * pi / 180),
);
final bodyDef = BodyDef()
..userData = this
..position = initialPosition
..angle = 90 * pi / 180
..type = BodyType.static;
return world.createBody(bodyDef)
..createFixture(
FixtureDef(entranceShape)..isSensor = true,
); );
} }
} }
@ -226,9 +211,11 @@ class SpaceshipEntrance extends BodyComponent with InitialPosition {
/// A sensor [BodyComponent] responsible for sending the [Ball] /// A sensor [BodyComponent] responsible for sending the [Ball]
/// back to the board. /// back to the board.
/// {@endtemplate} /// {@endtemplate}
class SpaceshipHole extends BodyComponent with InitialPosition { class SpaceshipHole extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_hole} /// {@macro spaceship_hole}
SpaceshipHole(); SpaceshipHole() {
layer = Layer.spaceship;
}
@override @override
Body createBody() { Body createBody() {
@ -242,10 +229,7 @@ class SpaceshipHole extends BodyComponent with InitialPosition {
return world.createBody(bodyDef) return world.createBody(bodyDef)
..createFixture( ..createFixture(
FixtureDef(circleShape) FixtureDef(circleShape)..isSensor = true,
..isSensor = true
..filter.maskBits = _spaceShipBits
..filter.categoryBits = _spaceShipBits,
); );
} }
} }
@ -256,18 +240,19 @@ class SpaceshipHole extends BodyComponent with InitialPosition {
/// [Ball] to get inside the spaceship saucer. /// [Ball] to get inside the spaceship saucer.
/// It also contains the [SpriteComponent] for the lower wall /// It also contains the [SpriteComponent] for the lower wall
/// {@endtemplate} /// {@endtemplate}
class SpaceshipWall extends BodyComponent with InitialPosition { class SpaceshipWall extends BodyComponent with InitialPosition, Layered {
/// {@macro spaceship_wall} /// {@macro spaceship_wall}
SpaceshipWall() : super(priority: 4); SpaceshipWall() : super(priority: 4) {
layer = Layer.spaceship;
/// Sprite path for the lower wall }
static const lowerWallPath = 'components/spaceship/lower.png';
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await super.onLoad(); await super.onLoad();
final sprite = await gameRef.loadSprite(lowerWallPath); final sprite = await gameRef.loadSprite(
Assets.images.components.spaceship.lower.path,
);
await add( await add(
SpriteComponent( SpriteComponent(
@ -303,10 +288,7 @@ class SpaceshipWall extends BodyComponent with InitialPosition {
return world.createBody(bodyDef) return world.createBody(bodyDef)
..createFixture( ..createFixture(
FixtureDef(wallShape) FixtureDef(wallShape)..restitution = 1,
..restitution = 1
..filter.maskBits = _spaceShipBits
..filter.categoryBits = _spaceShipBits,
); );
} }
} }
@ -316,19 +298,14 @@ class SpaceshipWall extends BodyComponent with InitialPosition {
/// ///
/// It modifies the [Ball] priority and filter data so it can appear on top of /// It modifies the [Ball] priority and filter data so it can appear on top of
/// the spaceship and also only collide with the spaceship. /// the spaceship and also only collide with the spaceship.
// TODO(alestiago): modify once Layer is implemented in Spaceship.
class SpaceshipEntranceBallContactCallback class SpaceshipEntranceBallContactCallback
extends ContactCallback<SpaceshipEntrance, Ball> { extends ContactCallback<SpaceshipEntrance, Ball> {
@override @override
void begin(SpaceshipEntrance entrance, Ball ball, _) { void begin(SpaceshipEntrance entrance, Ball ball, _) {
ball ball
..priority = 3 ..priority = 3
..gameRef.reorderChildren(); ..gameRef.reorderChildren()
..layer = Layer.spaceship;
for (final fixture in ball.body.fixtures) {
fixture.filterData.categoryBits = _spaceShipBits;
fixture.filterData.maskBits = _spaceShipBits;
}
} }
} }
@ -337,18 +314,13 @@ class SpaceshipEntranceBallContactCallback
/// ///
/// It resets the [Ball] priority and filter data so it will "be back" on the /// It resets the [Ball] priority and filter data so it will "be back" on the
/// board. /// board.
// TODO(alestiago): modify once Layer is implemented in Spaceship.
class SpaceshipHoleBallContactCallback class SpaceshipHoleBallContactCallback
extends ContactCallback<SpaceshipHole, Ball> { extends ContactCallback<SpaceshipHole, Ball> {
@override @override
void begin(SpaceshipHole hole, Ball ball, _) { void begin(SpaceshipHole hole, Ball ball, _) {
ball ball
..priority = 1 ..priority = 1
..gameRef.reorderChildren(); ..gameRef.reorderChildren()
..layer = Layer.board;
for (final fixture in ball.body.fixtures) {
fixture.filterData.categoryBits = 0xFFFF;
fixture.filterData.maskBits = 0x0001;
}
} }
} }

@ -1,7 +1,9 @@
// ignore_for_file: avoid_renaming_method_parameters // ignore_for_file: avoid_renaming_method_parameters
import 'package:flame/extensions.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/components/components.dart'; import 'package:pinball/game/components/components.dart';
import 'package:pinball/game/pinball_game.dart';
/// {@template wall} /// {@template wall}
/// A continuous generic and [BodyType.static] barrier that divides a game area. /// A continuous generic and [BodyType.static] barrier that divides a game area.
@ -39,15 +41,16 @@ class Wall extends BodyComponent {
/// Create top, left, and right [Wall]s for the game board. /// Create top, left, and right [Wall]s for the game board.
List<Wall> createBoundaries(Forge2DGame game) { List<Wall> createBoundaries(Forge2DGame game) {
final topLeft = Vector2.zero(); final topLeft = PinballGame.boardBounds.topLeft.toVector2();
final bottomRight = game.screenToWorld(game.camera.viewport.effectiveSize); final bottomRight = PinballGame.boardBounds.bottomRight.toVector2();
final topRight = Vector2(bottomRight.x, topLeft.y); final topRight = Vector2(bottomRight.x, topLeft.y);
final bottomLeft = Vector2(topLeft.x, bottomRight.y); final bottomLeft = Vector2(topLeft.x, bottomRight.y);
return [ return [
Wall(start: topLeft, end: topRight), Wall(start: topLeft, end: topRight),
Wall(start: topRight, end: bottomRight), Wall(start: topRight, end: bottomRight),
Wall(start: bottomLeft, end: topLeft), Wall(start: topLeft, end: bottomLeft),
]; ];
} }
@ -59,13 +62,10 @@ List<Wall> createBoundaries(Forge2DGame game) {
/// {@endtemplate} /// {@endtemplate}
class BottomWall extends Wall { class BottomWall extends Wall {
/// {@macro bottom_wall} /// {@macro bottom_wall}
BottomWall(Forge2DGame game) BottomWall()
: super( : super(
start: game.screenToWorld(game.camera.viewport.effectiveSize), start: PinballGame.boardBounds.bottomLeft.toVector2(),
end: Vector2( end: PinballGame.boardBounds.bottomRight.toVector2(),
0,
game.screenToWorld(game.camera.viewport.effectiveSize).y,
),
); );
} }

@ -1,16 +1,17 @@
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
import 'package:pinball/gen/assets.gen.dart';
/// Add methods to help loading and caching game assets. /// Add methods to help loading and caching game assets.
extension PinballGameAssetsX on PinballGame { extension PinballGameAssetsX on PinballGame {
/// Pre load the initial assets of the game. /// Pre load the initial assets of the game.
Future<void> preLoadAssets() async { Future<void> preLoadAssets() async {
await Future.wait([ await Future.wait([
images.load(Ball.spritePath), images.load(Assets.images.components.ball.path),
images.load(Flipper.spritePath), images.load(Assets.images.components.flipper.path),
images.load(SpaceshipBridge.spritePath), images.load(Assets.images.components.spaceship.androidTop.path),
images.load(SpaceshipBridgeTop.spritePath), images.load(Assets.images.components.spaceship.androidBottom.path),
images.load(SpaceshipWall.lowerWallPath), images.load(Assets.images.components.spaceship.lower.path),
images.load(SpaceshipSaucer.upperWallPath), images.load(Assets.images.components.spaceship.upper.path),
]); ]);
} }
} }

@ -1,6 +1,7 @@
// ignore_for_file: public_member_api_docs // ignore_for_file: public_member_api_docs
import 'dart:async'; import 'dart:async';
import 'package:flame/extensions.dart';
import 'package:flame/input.dart'; import 'package:flame/input.dart';
import 'package:flame_bloc/flame_bloc.dart'; import 'package:flame_bloc/flame_bloc.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
@ -10,12 +11,21 @@ import 'package:pinball_theme/pinball_theme.dart';
class PinballGame extends Forge2DGame class PinballGame extends Forge2DGame
with FlameBloc, HasKeyboardHandlerComponents { with FlameBloc, HasKeyboardHandlerComponents {
PinballGame({required this.theme}); PinballGame({required this.theme}) {
images.prefix = '';
}
final PinballTheme theme; final PinballTheme theme;
late final Plunger plunger; late final Plunger plunger;
static final boardSize = Vector2(72, 128);
static final boardBounds = Rect.fromCenter(
center: Offset.zero,
width: boardSize.x,
height: -boardSize.y,
);
@override @override
void onAttach() { void onAttach() {
super.onAttach(); super.onAttach();
@ -27,112 +37,77 @@ class PinballGame extends Forge2DGame
_addContactCallbacks(); _addContactCallbacks();
await _addGameBoundaries(); await _addGameBoundaries();
unawaited(add(Board()));
unawaited(_addPlunger()); unawaited(_addPlunger());
unawaited(_addBonusWord());
unawaited(_addPaths()); unawaited(_addPaths());
unawaited(addFromBlueprint(Spaceship())); unawaited(addFromBlueprint(Spaceship()));
// Corner wall above plunger so the ball deflects into the rest of the // Fix camera on the center of the board.
// board. camera
// TODO(allisonryan0002): remove once we have the launch track for the ball. ..followVector2(Vector2.zero())
await add( ..zoom = size.y / 14;
Wall( }
start: screenToWorld(
Vector2(
camera.viewport.effectiveSize.x,
100,
),
),
end: screenToWorld(
Vector2(
camera.viewport.effectiveSize.x - 100,
0,
),
),
),
);
unawaited(_addBonusWord()); void _addContactCallbacks() {
unawaited(_addBoard()); addContactCallback(BallScorePointsCallback());
addContactCallback(BottomWallBallContactCallback());
addContactCallback(BonusLetterBallContactCallback());
} }
Future<void> _addBoard() async { Future<void> _addGameBoundaries() async {
final board = Board( await add(BottomWall());
size: screenToWorld( createBoundaries(this).forEach(add);
}
Future<void> _addPlunger() async {
plunger = Plunger(compressionDistance: 2);
plunger.initialPosition = boardBounds.bottomRight.toVector2() -
Vector2( Vector2(
camera.viewport.effectiveSize.x, 8,
camera.viewport.effectiveSize.y, -10,
), );
), await add(plunger);
);
await add(board);
} }
Future<void> _addBonusWord() async { Future<void> _addBonusWord() async {
await add( await add(
BonusWord( BonusWord(
position: screenToWorld( position: Vector2(
Vector2( boardBounds.center.dx,
camera.viewport.effectiveSize.x / 2, boardBounds.bottom + 10,
camera.viewport.effectiveSize.y - 50,
),
), ),
), ),
); );
} }
void spawnBall() {
final ball = Ball();
add(
ball
..initialPosition = plunger.body.position + Vector2(0, ball.size.y / 2),
);
}
void _addContactCallbacks() {
addContactCallback(BallScorePointsCallback());
addContactCallback(BottomWallBallContactCallback());
addContactCallback(BonusLetterBallContactCallback());
}
Future<void> _addGameBoundaries() async {
await add(BottomWall(this));
createBoundaries(this).forEach(add);
}
Future<void> _addPaths() async { Future<void> _addPaths() async {
final jetpackRamp = JetpackRamp( final jetpackRamp = JetpackRamp(
position: screenToWorld( position: Vector2(
Vector2( PinballGame.boardBounds.left + 25,
camera.viewport.effectiveSize.x / 2 - 150, PinballGame.boardBounds.top - 20,
camera.viewport.effectiveSize.y / 2 - 250,
),
), ),
); );
final launcherRamp = LauncherRamp( final launcherRamp = LauncherRamp(
position: screenToWorld( position: Vector2(
Vector2( PinballGame.boardBounds.right - 23,
camera.viewport.effectiveSize.x / 2 + 400, PinballGame.boardBounds.bottom + 40,
camera.viewport.effectiveSize.y / 2 - 330,
),
), ),
); );
await addAll([jetpackRamp, launcherRamp]); await addAll([
jetpackRamp,
launcherRamp,
]);
} }
Future<void> _addPlunger() async { void spawnBall() {
plunger = Plunger( final ball = Ball();
compressionDistance: camera.viewport.effectiveSize.y / 12, add(
); ball
plunger.initialPosition = screenToWorld( ..initialPosition = plunger.body.position + Vector2(0, ball.size.y / 2),
Vector2(
camera.viewport.effectiveSize.x / 2 + 450,
camera.viewport.effectiveSize.y - plunger.compressionDistance,
),
); );
await add(plunger);
} }
} }

@ -0,0 +1,96 @@
/// GENERATED CODE - DO NOT MODIFY BY HAND
/// *****************************************************
/// FlutterGen
/// *****************************************************
import 'package:flutter/widgets.dart';
class $AssetsImagesGen {
const $AssetsImagesGen();
$AssetsImagesComponentsGen get components =>
const $AssetsImagesComponentsGen();
}
class $AssetsImagesComponentsGen {
const $AssetsImagesComponentsGen();
AssetGenImage get ball =>
const AssetGenImage('assets/images/components/ball.png');
AssetGenImage get flipper =>
const AssetGenImage('assets/images/components/flipper.png');
AssetGenImage get sauce =>
const AssetGenImage('assets/images/components/sauce.png');
$AssetsImagesComponentsSpaceshipGen get spaceship =>
const $AssetsImagesComponentsSpaceshipGen();
}
class $AssetsImagesComponentsSpaceshipGen {
const $AssetsImagesComponentsSpaceshipGen();
AssetGenImage get androidBottom => const AssetGenImage(
'assets/images/components/spaceship/android-bottom.png');
AssetGenImage get androidTop =>
const AssetGenImage('assets/images/components/spaceship/android-top.png');
AssetGenImage get lower =>
const AssetGenImage('assets/images/components/spaceship/lower.png');
AssetGenImage get saucer =>
const AssetGenImage('assets/images/components/spaceship/saucer.png');
AssetGenImage get upper =>
const AssetGenImage('assets/images/components/spaceship/upper.png');
}
class Assets {
Assets._();
static const $AssetsImagesGen images = $AssetsImagesGen();
}
class AssetGenImage extends AssetImage {
const AssetGenImage(String assetName) : super(assetName);
Image image({
Key? key,
ImageFrameBuilder? frameBuilder,
ImageLoadingBuilder? loadingBuilder,
ImageErrorWidgetBuilder? errorBuilder,
String? semanticLabel,
bool excludeFromSemantics = false,
double? width,
double? height,
Color? color,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
bool gaplessPlayback = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) {
return Image(
key: key,
image: this,
frameBuilder: frameBuilder,
loadingBuilder: loadingBuilder,
errorBuilder: errorBuilder,
semanticLabel: semanticLabel,
excludeFromSemantics: excludeFromSemantics,
width: width,
height: height,
color: color,
colorBlendMode: colorBlendMode,
fit: fit,
alignment: alignment,
repeat: repeat,
centerSlice: centerSlice,
matchTextDirection: matchTextDirection,
gaplessPlayback: gaplessPlayback,
isAntiAlias: isAntiAlias,
filterQuality: filterQuality,
);
}
String get path => assetName;
}

@ -0,0 +1,64 @@
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
part 'leaderboard_event.dart';
part 'leaderboard_state.dart';
/// {@template leaderboard_bloc}
/// Manages leaderboard events.
///
/// Uses a [LeaderboardRepository] to request and update players participations.
/// {@endtemplate}
class LeaderboardBloc extends Bloc<LeaderboardEvent, LeaderboardState> {
/// {@macro leaderboard_bloc}
LeaderboardBloc(this._leaderboardRepository)
: super(const LeaderboardState.initial()) {
on<Top10Fetched>(_onTop10Fetched);
on<LeaderboardEntryAdded>(_onLeaderboardEntryAdded);
}
final LeaderboardRepository _leaderboardRepository;
Future<void> _onTop10Fetched(
Top10Fetched event,
Emitter<LeaderboardState> emit,
) async {
emit(state.copyWith(status: LeaderboardStatus.loading));
try {
final top10Leaderboard =
await _leaderboardRepository.fetchTop10Leaderboard();
emit(
state.copyWith(
status: LeaderboardStatus.success,
leaderboard: top10Leaderboard,
),
);
} catch (error) {
emit(state.copyWith(status: LeaderboardStatus.error));
addError(error);
}
}
Future<void> _onLeaderboardEntryAdded(
LeaderboardEntryAdded event,
Emitter<LeaderboardState> emit,
) async {
emit(state.copyWith(status: LeaderboardStatus.loading));
try {
final ranking =
await _leaderboardRepository.addLeaderboardEntry(event.entry);
emit(
state.copyWith(
status: LeaderboardStatus.success,
ranking: ranking,
),
);
} catch (error) {
emit(state.copyWith(status: LeaderboardStatus.error));
addError(error);
}
}
}

@ -0,0 +1,36 @@
part of 'leaderboard_bloc.dart';
/// {@template leaderboard_event}
/// Represents the events available for [LeaderboardBloc].
/// {endtemplate}
abstract class LeaderboardEvent extends Equatable {
/// {@macro leaderboard_event}
const LeaderboardEvent();
}
/// {@template top_10_fetched}
/// Request the top 10 [LeaderboardEntry]s.
/// {endtemplate}
class Top10Fetched extends LeaderboardEvent {
/// {@macro top_10_fetched}
const Top10Fetched();
@override
List<Object?> get props => [];
}
/// {@template leaderboard_entry_added}
/// Writes a new [LeaderboardEntry].
///
/// Should be added when a player finishes a game.
/// {endtemplate}
class LeaderboardEntryAdded extends LeaderboardEvent {
/// {@macro leaderboard_entry_added}
const LeaderboardEntryAdded({required this.entry});
/// [LeaderboardEntry] to be written to the remote storage.
final LeaderboardEntry entry;
@override
List<Object?> get props => [entry];
}

@ -0,0 +1,59 @@
// ignore_for_file: public_member_api_docs
part of 'leaderboard_bloc.dart';
/// Defines the request status.
enum LeaderboardStatus {
/// Request is being loaded.
loading,
/// Request was processed successfully and received a valid response.
success,
/// Request was processed unsuccessfully and received an error.
error,
}
/// {@template leaderboard_state}
/// Represents the state of the leaderboard.
/// {@endtemplate}
class LeaderboardState extends Equatable {
/// {@macro leaderboard_state}
const LeaderboardState({
required this.status,
required this.ranking,
required this.leaderboard,
});
const LeaderboardState.initial()
: status = LeaderboardStatus.loading,
ranking = const LeaderboardRanking(
ranking: 0,
outOf: 0,
),
leaderboard = const [];
/// The current [LeaderboardStatus] of the state.
final LeaderboardStatus status;
/// Rank of the current player.
final LeaderboardRanking ranking;
/// List of top-ranked players.
final List<LeaderboardEntry> leaderboard;
@override
List<Object> get props => [status, ranking, leaderboard];
LeaderboardState copyWith({
LeaderboardStatus? status,
LeaderboardRanking? ranking,
List<LeaderboardEntry>? leaderboard,
}) {
return LeaderboardState(
status: status ?? this.status,
ranking: ranking ?? this.ranking,
leaderboard: leaderboard ?? this.leaderboard,
);
}
}

@ -0,0 +1 @@
export 'bloc/leaderboard_bloc.dart';

@ -182,21 +182,21 @@ packages:
name: flame name: flame
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.1.0-releasecandidate.5" version: "1.1.0-releasecandidate.6"
flame_bloc: flame_bloc:
dependency: "direct main" dependency: "direct main"
description: description:
name: flame_bloc name: flame_bloc
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "1.2.0-releasecandidate.5" version: "1.2.0-releasecandidate.6"
flame_forge2d: flame_forge2d:
dependency: "direct main" dependency: "direct main"
description: description:
name: flame_forge2d name: flame_forge2d
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.9.0-releasecandidate.5" version: "0.9.0-releasecandidate.6"
flame_test: flame_test:
dependency: "direct dev" dependency: "direct dev"
description: description:
@ -237,7 +237,7 @@ packages:
name: forge2d name: forge2d
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "0.8.2" version: "0.9.0"
frontend_server_client: frontend_server_client:
dependency: transitive dependency: transitive
description: description:

@ -10,9 +10,9 @@ dependencies:
bloc: ^8.0.2 bloc: ^8.0.2
cloud_firestore: ^3.1.10 cloud_firestore: ^3.1.10
equatable: ^2.0.3 equatable: ^2.0.3
flame: ^1.1.0-releasecandidate.5 flame: ^1.1.0-releasecandidate.6
flame_bloc: ^1.2.0-releasecandidate.5 flame_bloc: ^1.2.0-releasecandidate.6
flame_forge2d: ^0.9.0-releasecandidate.5 flame_forge2d: ^0.9.0-releasecandidate.6
flutter: flutter:
sdk: flutter sdk: flutter
flutter_bloc: ^8.0.1 flutter_bloc: ^8.0.1
@ -42,3 +42,6 @@ flutter:
assets: assets:
- assets/images/components/ - assets/images/components/
- assets/images/components/spaceship/ - assets/images/components/spaceship/
flutter_gen:
line_length: 80

@ -1,6 +1,5 @@
// ignore_for_file: cascade_invocations // ignore_for_file: cascade_invocations
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
@ -9,13 +8,13 @@ import '../../helpers/helpers.dart';
void main() { void main() {
TestWidgetsFlutterBinding.ensureInitialized(); TestWidgetsFlutterBinding.ensureInitialized();
final flameTester = FlameTester(Forge2DGame.new); final flameTester = FlameTester(PinballGameTest.create);
group('Board', () { group('Board', () {
flameTester.test( flameTester.test(
'loads correctly', 'loads correctly',
(game) async { (game) async {
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);
@ -27,7 +26,7 @@ void main() {
flameTester.test( flameTester.test(
'has one left flipper', 'has one left flipper',
(game) async { (game) async {
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);
@ -41,7 +40,7 @@ void main() {
flameTester.test( flameTester.test(
'has one right flipper', 'has one right flipper',
(game) async { (game) async {
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);
@ -55,7 +54,7 @@ void main() {
flameTester.test( flameTester.test(
'has two Baseboards', 'has two Baseboards',
(game) async { (game) async {
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);
@ -65,14 +64,14 @@ void main() {
); );
flameTester.test( flameTester.test(
'has two SlingShots', 'has two Kickers',
(game) async { (game) async {
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);
final slingShots = board.findNestedChildren<SlingShot>(); final kickers = board.findNestedChildren<Kicker>();
expect(slingShots.length, equals(2)); expect(kickers.length, equals(2));
}, },
); );
@ -80,7 +79,7 @@ void main() {
'has three RoundBumpers', 'has three RoundBumpers',
(game) async { (game) async {
// TODO(alestiago): change to [NestBumpers] once provided. // TODO(alestiago): change to [NestBumpers] once provided.
final board = Board(size: Vector2.all(500)); final board = Board();
await game.ready(); await game.ready();
await game.ensureAdd(board); await game.ensureAdd(board);

@ -300,12 +300,26 @@ void main() {
test('calls ball.activate', () { test('calls ball.activate', () {
final ball = MockBall(); final ball = MockBall();
final bonusLetter = MockBonusLetter(); final bonusLetter = MockBonusLetter();
final contactCallback = BonusLetterBallContactCallback(); final contactCallback = BonusLetterBallContactCallback();
when(() => bonusLetter.isEnabled).thenReturn(true);
contactCallback.begin(ball, bonusLetter, MockContact()); contactCallback.begin(ball, bonusLetter, MockContact());
verify(bonusLetter.activate).called(1); verify(bonusLetter.activate).called(1);
}); });
test("doesn't call ball.activate when letter is disabled", () {
final ball = MockBall();
final bonusLetter = MockBonusLetter();
final contactCallback = BonusLetterBallContactCallback();
when(() => bonusLetter.isEnabled).thenReturn(false);
contactCallback.begin(ball, bonusLetter, MockContact());
verifyNever(bonusLetter.activate);
});
}); });
}); });
} }

@ -282,7 +282,7 @@ void main() {
final flipperAnchor = FlipperAnchor(flipper: flipper); final flipperAnchor = FlipperAnchor(flipper: flipper);
await game.ensureAdd(flipperAnchor); await game.ensureAdd(flipperAnchor);
expect(flipperAnchor.body.position.x, equals(-Flipper.width / 2)); expect(flipperAnchor.body.position.x, equals(-Flipper.size.x / 2));
}, },
); );
@ -297,7 +297,7 @@ void main() {
final flipperAnchor = FlipperAnchor(flipper: flipper); final flipperAnchor = FlipperAnchor(flipper: flipper);
await game.ensureAdd(flipperAnchor); await game.ensureAdd(flipperAnchor);
expect(flipperAnchor.body.position.x, equals(Flipper.width / 2)); expect(flipperAnchor.body.position.x, equals(Flipper.size.x / 2));
}, },
); );
}); });

@ -6,43 +6,43 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:pinball/game/game.dart'; import 'package:pinball/game/game.dart';
void main() { void main() {
group('SlingShot', () { group('Kicker', () {
// TODO(alestiago): Include golden tests for left and right. // TODO(alestiago): Include golden tests for left and right.
final flameTester = FlameTester(Forge2DGame.new); final flameTester = FlameTester(Forge2DGame.new);
flameTester.test( flameTester.test(
'loads correctly', 'loads correctly',
(game) async { (game) async {
final slingShot = SlingShot( final kicker = Kicker(
side: BoardSide.left, side: BoardSide.left,
); );
await game.ensureAdd(slingShot); await game.ensureAdd(kicker);
expect(game.contains(slingShot), isTrue); expect(game.contains(kicker), isTrue);
}, },
); );
flameTester.test( flameTester.test(
'body is static', 'body is static',
(game) async { (game) async {
final slingShot = SlingShot( final kicker = Kicker(
side: BoardSide.left, side: BoardSide.left,
); );
await game.ensureAdd(slingShot); await game.ensureAdd(kicker);
expect(slingShot.body.bodyType, equals(BodyType.static)); expect(kicker.body.bodyType, equals(BodyType.static));
}, },
); );
flameTester.test( flameTester.test(
'has restitution', 'has restitution',
(game) async { (game) async {
final slingShot = SlingShot( final kicker = Kicker(
side: BoardSide.left, side: BoardSide.left,
); );
await game.ensureAdd(slingShot); await game.ensureAdd(kicker);
final totalRestitution = slingShot.body.fixtures.fold<double>( final totalRestitution = kicker.body.fixtures.fold<double>(
0, 0,
(total, fixture) => total + fixture.restitution, (total, fixture) => total + fixture.restitution,
); );
@ -53,12 +53,12 @@ void main() {
flameTester.test( flameTester.test(
'has no friction', 'has no friction',
(game) async { (game) async {
final slingShot = SlingShot( final kicker = Kicker(
side: BoardSide.left, side: BoardSide.left,
); );
await game.ensureAdd(slingShot); await game.ensureAdd(kicker);
final totalFriction = slingShot.body.fixtures.fold<double>( final totalFriction = kicker.body.fixtures.fold<double>(
0, 0,
(total, fixture) => total + fixture.friction, (total, fixture) => total + fixture.friction,
); );

@ -54,17 +54,6 @@ void main() {
verify(game.reorderChildren).called(1); verify(game.reorderChildren).called(1);
}); });
test('changes the filter data from the ball fixtures', () {
SpaceshipEntranceBallContactCallback().begin(
entrance,
ball,
MockContact(),
);
verify(() => filterData.maskBits = 0x0002).called(1);
verify(() => filterData.categoryBits = 0x0002).called(1);
});
}); });
group('SpaceshipHoleBallContactCallback', () { group('SpaceshipHoleBallContactCallback', () {
@ -87,17 +76,6 @@ void main() {
verify(game.reorderChildren).called(1); verify(game.reorderChildren).called(1);
}); });
test('changes the filter data from the ball fixtures', () {
SpaceshipHoleBallContactCallback().begin(
hole,
ball,
MockContact(),
);
verify(() => filterData.categoryBits = 0xFFFF).called(1);
verify(() => filterData.maskBits = 0x0001).called(1);
});
}); });
}); });
} }

@ -25,9 +25,7 @@ void main() {
final walls = game.children.where( final walls = game.children.where(
(component) => component is Wall && component is! BottomWall, (component) => component is Wall && component is! BottomWall,
); );
// TODO(allisonryan0002): expect 3 when launch track is added and expect(walls.length, 3);
// temporary wall is removed.
expect(walls.length, 4);
}, },
); );

@ -9,7 +9,7 @@ extension PinballGameTest on PinballGame {
theme: const PinballTheme( theme: const PinballTheme(
characterTheme: DashTheme(), characterTheme: DashTheme(),
), ),
); )..images.prefix = '';
} }
/// [DebugPinballGame] extension to reduce boilerplate in tests. /// [DebugPinballGame] extension to reduce boilerplate in tests.

@ -0,0 +1,166 @@
// ignore_for_file: prefer_const_constructors
import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:mocktail/mocktail.dart';
import 'package:pinball/leaderboard/leaderboard.dart';
class MockLeaderboardRepository extends Mock implements LeaderboardRepository {}
void main() {
group('LeaderboardBloc', () {
late LeaderboardRepository leaderboardRepository;
setUp(() {
leaderboardRepository = MockLeaderboardRepository();
});
test('initial state has state loading no ranking and empty leaderboard',
() {
final bloc = LeaderboardBloc(leaderboardRepository);
expect(bloc.state.status, equals(LeaderboardStatus.loading));
expect(bloc.state.ranking.ranking, equals(0));
expect(bloc.state.ranking.outOf, equals(0));
expect(bloc.state.leaderboard.isEmpty, isTrue);
});
group('Top10Fetched', () {
const top10Scores = [
2500,
2200,
2200,
2000,
1800,
1400,
1300,
1000,
600,
300,
100,
];
final top10Leaderboard = top10Scores
.map(
(score) => LeaderboardEntry(
playerInitials: 'user$score',
score: score,
character: CharacterType.dash,
),
)
.toList();
blocTest<LeaderboardBloc, LeaderboardState>(
'emits [loading, success] statuses '
'when fetchTop10Leaderboard succeeds',
setUp: () {
when(() => leaderboardRepository.fetchTop10Leaderboard()).thenAnswer(
(_) async => top10Leaderboard,
);
},
build: () => LeaderboardBloc(leaderboardRepository),
act: (bloc) => bloc.add(Top10Fetched()),
expect: () => [
LeaderboardState.initial(),
isA<LeaderboardState>()
..having(
(element) => element.status,
'status',
equals(LeaderboardStatus.success),
)
..having(
(element) => element.leaderboard.length,
'leaderboard',
equals(top10Leaderboard.length),
)
],
verify: (_) =>
verify(() => leaderboardRepository.fetchTop10Leaderboard())
.called(1),
);
blocTest<LeaderboardBloc, LeaderboardState>(
'emits [loading, error] statuses '
'when fetchTop10Leaderboard fails',
setUp: () {
when(() => leaderboardRepository.fetchTop10Leaderboard()).thenThrow(
Exception(),
);
},
build: () => LeaderboardBloc(leaderboardRepository),
act: (bloc) => bloc.add(Top10Fetched()),
expect: () => <LeaderboardState>[
LeaderboardState.initial(),
LeaderboardState.initial().copyWith(status: LeaderboardStatus.error),
],
verify: (_) =>
verify(() => leaderboardRepository.fetchTop10Leaderboard())
.called(1),
errors: () => [isA<Exception>()],
);
});
group('LeaderboardEntryAdded', () {
final leaderboardEntry = LeaderboardEntry(
playerInitials: 'ABC',
score: 1500,
character: CharacterType.dash,
);
final ranking = LeaderboardRanking(ranking: 3, outOf: 4);
blocTest<LeaderboardBloc, LeaderboardState>(
'emits [loading, success] statuses '
'when addLeaderboardEntry succeeds',
setUp: () {
when(
() => leaderboardRepository.addLeaderboardEntry(leaderboardEntry),
).thenAnswer(
(_) async => ranking,
);
},
build: () => LeaderboardBloc(leaderboardRepository),
act: (bloc) => bloc.add(LeaderboardEntryAdded(entry: leaderboardEntry)),
expect: () => [
LeaderboardState.initial(),
isA<LeaderboardState>()
..having(
(element) => element.status,
'status',
equals(LeaderboardStatus.success),
)
..having(
(element) => element.ranking,
'ranking',
equals(ranking),
)
],
verify: (_) => verify(
() => leaderboardRepository.addLeaderboardEntry(leaderboardEntry),
).called(1),
);
blocTest<LeaderboardBloc, LeaderboardState>(
'emits [loading, error] statuses '
'when addLeaderboardEntry fails',
setUp: () {
when(
() => leaderboardRepository.addLeaderboardEntry(leaderboardEntry),
).thenThrow(
Exception(),
);
},
build: () => LeaderboardBloc(leaderboardRepository),
act: (bloc) => bloc.add(LeaderboardEntryAdded(entry: leaderboardEntry)),
expect: () => <LeaderboardState>[
LeaderboardState.initial(),
LeaderboardState.initial().copyWith(status: LeaderboardStatus.error),
],
verify: (_) => verify(
() => leaderboardRepository.addLeaderboardEntry(leaderboardEntry),
).called(1),
errors: () => [isA<Exception>()],
);
});
});
}

@ -0,0 +1,41 @@
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/leaderboard/leaderboard.dart';
void main() {
group('GameEvent', () {
group('Top10Fetched', () {
test('can be instantiated', () {
expect(const Top10Fetched(), isNotNull);
});
test('supports value equality', () {
expect(
Top10Fetched(),
equals(const Top10Fetched()),
);
});
});
group('LeaderboardEntryAdded', () {
const leaderboardEntry = LeaderboardEntry(
playerInitials: 'ABC',
score: 1500,
character: CharacterType.dash,
);
test('can be instantiated', () {
expect(const LeaderboardEntryAdded(entry: leaderboardEntry), isNotNull);
});
test('supports value equality', () {
expect(
LeaderboardEntryAdded(entry: leaderboardEntry),
equals(const LeaderboardEntryAdded(entry: leaderboardEntry)),
);
});
});
});
}

@ -0,0 +1,70 @@
// ignore_for_file: prefer_const_constructors
import 'package:flutter_test/flutter_test.dart';
import 'package:leaderboard_repository/leaderboard_repository.dart';
import 'package:pinball/leaderboard/leaderboard.dart';
void main() {
group('LeaderboardState', () {
test('supports value equality', () {
expect(
LeaderboardState.initial(),
equals(
LeaderboardState.initial(),
),
);
});
group('constructor', () {
test('can be instantiated', () {
expect(
LeaderboardState.initial(),
isNotNull,
);
});
});
group('copyWith', () {
const leaderboardEntry = LeaderboardEntry(
playerInitials: 'ABC',
score: 1500,
character: CharacterType.dash,
);
test(
'copies correctly '
'when no argument specified',
() {
const leaderboardState = LeaderboardState.initial();
expect(
leaderboardState.copyWith(),
equals(leaderboardState),
);
},
);
test(
'copies correctly '
'when all arguments specified',
() {
const leaderboardState = LeaderboardState.initial();
final otherLeaderboardState = LeaderboardState(
status: LeaderboardStatus.success,
ranking: LeaderboardRanking(ranking: 0, outOf: 0),
leaderboard: const [leaderboardEntry],
);
expect(leaderboardState, isNot(equals(otherLeaderboardState)));
expect(
leaderboardState.copyWith(
status: otherLeaderboardState.status,
ranking: otherLeaderboardState.ranking,
leaderboard: otherLeaderboardState.leaderboard,
),
equals(otherLeaderboardState),
);
},
);
});
});
}
Loading…
Cancel
Save