feat: add plunger to board (#25)

* feat: add plunger to board

* refactor: leave spawn ball synchronous

* fix: ball test

* refactor: position ball internally

* fix: ball position test

* refactor: use joint specific anchor

* refactor: remove ballSize

* fix: plunger position

* refactor: use relative positioning

Co-authored-by: Alejandro Santiago <dev@alestiago.com>
pull/41/head
Allison Ryan 4 years ago committed by GitHub
parent 07d16fbac0
commit 19c0172cac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -37,7 +37,7 @@ class Ball extends PositionBodyComponent<PinballGame, SpriteComponent> {
final bodyDef = BodyDef() final bodyDef = BodyDef()
..userData = this ..userData = this
..position = _position ..position = Vector2(_position.x, _position.y + size.y)
..type = BodyType.dynamic; ..type = BodyType.dynamic;
return world.createBody(bodyDef)..createFixture(fixtureDef); return world.createBody(bodyDef)..createFixture(fixtureDef);

@ -218,7 +218,7 @@ class FlipperAnchorRevoluteJointDef extends RevoluteJointDef {
/// {@macro flipper_anchor_revolute_joint_def} /// {@macro flipper_anchor_revolute_joint_def}
FlipperAnchorRevoluteJointDef({ FlipperAnchorRevoluteJointDef({
required Flipper flipper, required Flipper flipper,
required Anchor anchor, required FlipperAnchor anchor,
}) { }) {
initialize( initialize(
flipper.body, flipper.body,

@ -1,23 +1,32 @@
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/services.dart';
import 'package:pinball/game/game.dart' show Anchor; import 'package:pinball/game/game.dart' show Anchor;
/// {@template plunger} /// {@template plunger}
/// [Plunger] serves as a spring, that shoots the ball on the right side of the /// [Plunger] serves as a spring, that shoots the ball on the right side of the
/// playfield. /// playfield.
/// ///
/// [Plunger] ignores gravity so the player controls its downward [pull]. /// [Plunger] ignores gravity so the player controls its downward [_pull].
/// {@endtemplate} /// {@endtemplate}
class Plunger extends BodyComponent { class Plunger extends BodyComponent with KeyboardHandler {
/// {@macro plunger} /// {@macro plunger}
Plunger({required Vector2 position}) : _position = position; Plunger({
required Vector2 position,
required this.compressionDistance,
}) : _position = position;
/// The initial position of the [Plunger] body.
final Vector2 _position; final Vector2 _position;
/// Distance the plunger can lower.
final double compressionDistance;
@override @override
Body createBody() { Body createBody() {
final shape = PolygonShape()..setAsBoxXY(2.5, 1.5); final shape = PolygonShape()..setAsBoxXY(2, 0.75);
final fixtureDef = FixtureDef(shape); final fixtureDef = FixtureDef(shape)..density = 5;
final bodyDef = BodyDef() final bodyDef = BodyDef()
..userData = this ..userData = this
@ -29,18 +38,57 @@ class Plunger extends BodyComponent {
} }
/// Set a constant downward velocity on the [Plunger]. /// Set a constant downward velocity on the [Plunger].
void pull() { void _pull() {
body.linearVelocity = Vector2(0, -7); body.linearVelocity = Vector2(0, -3);
} }
/// Set an upward velocity on the [Plunger]. /// Set an upward velocity on the [Plunger].
/// ///
/// The velocity's magnitude depends on how far the [Plunger] has been pulled /// The velocity's magnitude depends on how far the [Plunger] has been pulled
/// from its original [_position]. /// from its original [_position].
void release() { void _release() {
final velocity = (_position.y - body.position.y) * 9; final velocity = (_position.y - body.position.y) * 9;
body.linearVelocity = Vector2(0, velocity); body.linearVelocity = Vector2(0, velocity);
} }
@override
bool onKeyEvent(
RawKeyEvent event,
Set<LogicalKeyboardKey> keysPressed,
) {
final keys = [
LogicalKeyboardKey.space,
LogicalKeyboardKey.arrowDown,
LogicalKeyboardKey.keyS,
];
// 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) {
_pull();
} else if (event is RawKeyUpEvent) {
_release();
}
return true;
}
}
/// {@template plunger_anchor}
/// [Anchor] positioned below a [Plunger].
/// {@endtemplate}
class PlungerAnchor extends Anchor {
/// {@macro plunger_anchor}
PlungerAnchor({
required Plunger plunger,
}) : super(
position: Vector2(
plunger.body.position.x,
plunger.body.position.y - plunger.compressionDistance,
),
);
} }
/// {@template plunger_anchor_prismatic_joint_def} /// {@template plunger_anchor_prismatic_joint_def}
@ -54,11 +102,8 @@ class PlungerAnchorPrismaticJointDef extends PrismaticJointDef {
/// {@macro plunger_anchor_prismatic_joint_def} /// {@macro plunger_anchor_prismatic_joint_def}
PlungerAnchorPrismaticJointDef({ PlungerAnchorPrismaticJointDef({
required Plunger plunger, required Plunger plunger,
required Anchor anchor, required PlungerAnchor anchor,
}) : assert( }) {
anchor.body.position.y < plunger.body.position.y,
'Anchor must be below the Plunger',
) {
initialize( initialize(
plunger.body, plunger.body,
anchor.body, anchor.body,
@ -67,6 +112,9 @@ class PlungerAnchorPrismaticJointDef extends PrismaticJointDef {
); );
enableLimit = true; enableLimit = true;
lowerTranslation = double.negativeInfinity; lowerTranslation = double.negativeInfinity;
enableMotor = true;
motorSpeed = 50;
maxMotorForce = motorSpeed;
collideConnected = true; collideConnected = true;
} }
} }

@ -4,7 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/components/components.dart'; import 'package:pinball/game/components/components.dart';
/// {@template wall} /// {@template wall}
/// A continuos generic and [BodyType.static] barrier that divides a game area. /// A continuous generic and [BodyType.static] barrier that divides a game area.
/// {@endtemplate} /// {@endtemplate}
// TODO(alestiago): Remove [Wall] for [Pathway.straight]. // TODO(alestiago): Remove [Wall] for [Pathway.straight].
class Wall extends BodyComponent { class Wall extends BodyComponent {
@ -25,7 +25,7 @@ class Wall extends BodyComponent {
final shape = EdgeShape()..set(start, end); final shape = EdgeShape()..set(start, end);
final fixtureDef = FixtureDef(shape) final fixtureDef = FixtureDef(shape)
..restitution = 0.0 ..restitution = 0.1
..friction = 0.3; ..friction = 0.3;
final bodyDef = BodyDef() final bodyDef = BodyDef()
@ -37,6 +37,20 @@ class Wall extends BodyComponent {
} }
} }
/// Create top, left, and right [Wall]s for the game board.
List<Wall> createBoundaries(Forge2DGame game) {
final topLeft = Vector2.zero();
final bottomRight = game.screenToWorld(game.camera.viewport.effectiveSize);
final topRight = Vector2(bottomRight.x, topLeft.y);
final bottomLeft = Vector2(topLeft.x, bottomRight.y);
return [
Wall(start: topLeft, end: topRight),
Wall(start: topRight, end: bottomRight),
Wall(start: bottomLeft, end: topLeft),
];
}
/// {@template bottom_wall} /// {@template bottom_wall}
/// [Wall] located at the bottom of the board. /// [Wall] located at the bottom of the board.
/// ///

@ -13,17 +13,7 @@ class PinballGame extends Forge2DGame
final PinballTheme theme; final PinballTheme theme;
// TODO(erickzanardo): Change to the plumber position late final Plunger plunger;
late final ballStartingPosition = screenToWorld(
Vector2(
camera.viewport.effectiveSize.x / 2,
camera.viewport.effectiveSize.y - 20,
),
) -
Vector2(0, -20);
// TODO(alestiago): Change to the design position.
late final flippersPosition = ballStartingPosition - Vector2(0, 5);
@override @override
void onAttach() { void onAttach() {
@ -31,21 +21,56 @@ class PinballGame extends Forge2DGame
spawnBall(); spawnBall();
} }
@override
Future<void> onLoad() async {
_addContactCallbacks();
await _addGameBoundaries();
unawaited(_addFlippers());
unawaited(_addPlunger());
// Corner wall above plunger so the ball deflects into the rest of the
// board.
// TODO(allisonryan0002): remove once we have the launch track for the ball.
await add(
Wall(
start: screenToWorld(
Vector2(
camera.viewport.effectiveSize.x,
100,
),
),
end: screenToWorld(
Vector2(
camera.viewport.effectiveSize.x - 100,
0,
),
),
),
);
}
void spawnBall() { void spawnBall() {
add(Ball(position: ballStartingPosition)); add(Ball(position: plunger.body.position));
} }
@override void _addContactCallbacks() {
Future<void> onLoad() async {
addContactCallback(BallScorePointsCallback()); addContactCallback(BallScorePointsCallback());
await add(BottomWall(this));
addContactCallback(BottomWallBallContactCallback()); addContactCallback(BottomWallBallContactCallback());
}
unawaited(_addFlippers()); Future<void> _addGameBoundaries() async {
await add(BottomWall(this));
createBoundaries(this).forEach(add);
} }
Future<void> _addFlippers() async { Future<void> _addFlippers() async {
final flippersPosition = screenToWorld(
Vector2(
camera.viewport.effectiveSize.x / 2,
camera.viewport.effectiveSize.y / 1.1,
),
);
const spaceBetweenFlippers = 2; const spaceBetweenFlippers = 2;
final leftFlipper = Flipper.left( final leftFlipper = Flipper.left(
position: Vector2( position: Vector2(
@ -104,6 +129,31 @@ class PinballGame extends Forge2DGame
), ),
); );
} }
Future<void> _addPlunger() async {
late PlungerAnchor plungerAnchor;
final compressionDistance = camera.viewport.effectiveSize.y / 12;
await add(
plunger = Plunger(
position: screenToWorld(
Vector2(
camera.viewport.effectiveSize.x / 1.035,
camera.viewport.effectiveSize.y - compressionDistance,
),
),
compressionDistance: compressionDistance,
),
);
await add(plungerAnchor = PlungerAnchor(plunger: plunger));
world.createJoint(
PlungerAnchorPrismaticJointDef(
plunger: plunger,
anchor: plungerAnchor,
),
);
}
} }
class DebugPinballGame extends PinballGame with TapDetector { class DebugPinballGame extends PinballGame with TapDetector {

@ -34,7 +34,11 @@ void main() {
await game.ensureAdd(ball); await game.ensureAdd(ball);
game.contains(ball); game.contains(ball);
expect(ball.body.position, position); final expectedPosition = Vector2(
position.x,
position.y + ball.size.y,
);
expect(ball.body.position, equals(expectedPosition));
}, },
); );
@ -49,7 +53,7 @@ void main() {
); );
}); });
group('first fixture', () { group('fixture', () {
flameTester.test( flameTester.test(
'exists', 'exists',
(game) async { (game) async {

@ -255,36 +255,33 @@ void main() {
}, },
); );
group( group('FlipperAnchor', () {
'FlipperAnchor', flameTester.test(
() { 'position is at the left of the left Flipper',
flameTester.test( (game) async {
'position is at the left of the left Flipper', final flipper = Flipper.left(position: Vector2.zero());
(game) async { await game.ensureAdd(flipper);
final flipper = Flipper.left(position: Vector2.zero());
await game.ensureAdd(flipper);
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.width / 2));
}, },
); );
flameTester.test( flameTester.test(
'position is at the right of the right Flipper', 'position is at the right of the right Flipper',
(game) async { (game) async {
final flipper = Flipper.right(position: Vector2.zero()); final flipper = Flipper.right(position: Vector2.zero());
await game.ensureAdd(flipper); await game.ensureAdd(flipper);
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.width / 2));
}, },
); );
}, });
);
group('FlipperAnchorRevoluteJointDef', () { group('FlipperAnchorRevoluteJointDef', () {
group('initializes with', () { group('initializes with', () {

@ -1,8 +1,11 @@
// ignore_for_file: cascade_invocations // ignore_for_file: cascade_invocations
import 'dart:collection';
import 'package:bloc_test/bloc_test.dart'; import 'package:bloc_test/bloc_test.dart';
import 'package:flame_forge2d/flame_forge2d.dart'; import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flame_test/flame_test.dart'; import 'package:flame_test/flame_test.dart';
import 'package:flutter/services.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';
@ -13,11 +16,16 @@ void main() {
final flameTester = FlameTester(PinballGameTest.create); final flameTester = FlameTester(PinballGameTest.create);
group('Plunger', () { group('Plunger', () {
const compressionDistance = 0.0;
flameTester.test( flameTester.test(
'loads correctly', 'loads correctly',
(game) async { (game) async {
await game.ready(); await game.ready();
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
expect(game.contains(plunger), isTrue); expect(game.contains(plunger), isTrue);
@ -29,7 +37,10 @@ void main() {
'positions correctly', 'positions correctly',
(game) async { (game) async {
final position = Vector2.all(10); final position = Vector2.all(10);
final plunger = Plunger(position: position); final plunger = Plunger(
position: position,
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
game.contains(plunger); game.contains(plunger);
@ -40,7 +51,10 @@ void main() {
flameTester.test( flameTester.test(
'is dynamic', 'is dynamic',
(game) async { (game) async {
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
expect(plunger.body.bodyType, equals(BodyType.dynamic)); expect(plunger.body.bodyType, equals(BodyType.dynamic));
@ -50,7 +64,10 @@ void main() {
flameTester.test( flameTester.test(
'ignores gravity', 'ignores gravity',
(game) async { (game) async {
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
expect(plunger.body.gravityScale, isZero); expect(plunger.body.gravityScale, isZero);
@ -58,11 +75,14 @@ void main() {
); );
}); });
group('first fixture', () { group('fixture', () {
flameTester.test( flameTester.test(
'exists', 'exists',
(game) async { (game) async {
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
expect(plunger.body.fixtures[0], isA<Fixture>()); expect(plunger.body.fixtures[0], isA<Fixture>());
@ -72,65 +92,128 @@ void main() {
flameTester.test( flameTester.test(
'shape is a polygon', 'shape is a polygon',
(game) async { (game) async {
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
final fixture = plunger.body.fixtures[0]; final fixture = plunger.body.fixtures[0];
expect(fixture.shape.shapeType, equals(ShapeType.polygon)); expect(fixture.shape.shapeType, equals(ShapeType.polygon));
}, },
); );
});
flameTester.test(
'pull sets a negative linear velocity',
(game) async {
final plunger = Plunger(position: Vector2.zero());
await game.ensureAdd(plunger);
plunger.pull();
expect(plunger.body.linearVelocity.y, isNegative);
expect(plunger.body.linearVelocity.x, isZero);
},
);
group('release', () {
flameTester.test( flameTester.test(
'does not set a linear velocity ' 'has density',
'when plunger is in starting position',
(game) async { (game) async {
final plunger = Plunger(position: Vector2.zero()); final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger); await game.ensureAdd(plunger);
plunger.release(); final fixture = plunger.body.fixtures[0];
expect(fixture.density, greaterThan(0));
expect(plunger.body.linearVelocity.y, isZero);
expect(plunger.body.linearVelocity.x, isZero);
}, },
); );
});
flameTester.test( group('onKeyEvent', () {
'sets a positive linear velocity ' final keys = UnmodifiableListView([
'when plunger is below starting position', LogicalKeyboardKey.space,
(game) async { LogicalKeyboardKey.arrowDown,
final plunger = Plunger(position: Vector2.zero()); LogicalKeyboardKey.keyS,
await game.ensureAdd(plunger); ]);
plunger.body.setTransform(Vector2(0, -1), 0); late Plunger plunger;
plunger.release();
expect(plunger.body.linearVelocity.y, isPositive); setUp(() {
expect(plunger.body.linearVelocity.x, isZero); plunger = Plunger(
}, position: Vector2.zero(),
); compressionDistance: compressionDistance,
);
});
testRawKeyUpEvents(keys, (event) {
final keyLabel = (event.logicalKey != LogicalKeyboardKey.space)
? event.logicalKey.keyLabel
: 'Space';
flameTester.test(
'moves upwards when $keyLabel is released '
'and plunger is below its starting position',
(game) async {
await game.ensureAdd(plunger);
plunger.body.setTransform(Vector2(0, -1), 0);
plunger.onKeyEvent(event, {});
expect(plunger.body.linearVelocity.y, isPositive);
expect(plunger.body.linearVelocity.x, isZero);
},
);
});
testRawKeyUpEvents(keys, (event) {
final keyLabel = (event.logicalKey != LogicalKeyboardKey.space)
? event.logicalKey.keyLabel
: 'Space';
flameTester.test(
'does not move when $keyLabel is released '
'and plunger is in its starting position',
(game) async {
await game.ensureAdd(plunger);
plunger.onKeyEvent(event, {});
expect(plunger.body.linearVelocity.y, isZero);
expect(plunger.body.linearVelocity.x, isZero);
},
);
});
testRawKeyDownEvents(keys, (event) {
final keyLabel = (event.logicalKey != LogicalKeyboardKey.space)
? event.logicalKey.keyLabel
: 'Space';
flameTester.test(
'moves downwards when $keyLabel is pressed',
(game) async {
await game.ensureAdd(plunger);
plunger.onKeyEvent(event, {});
expect(plunger.body.linearVelocity.y, isNegative);
expect(plunger.body.linearVelocity.x, isZero);
},
);
});
}); });
}); });
group('PlungerAnchorPrismaticJointDef', () { group('PlungerAnchor', () {
late Plunger plunger; const compressionDistance = 10.0;
late Anchor anchor;
flameTester.test(
'position is a compression distance below the Plunger',
(game) async {
final plunger = Plunger(
position: Vector2.zero(),
compressionDistance: compressionDistance,
);
await game.ensureAdd(plunger);
final plungerAnchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(plungerAnchor);
expect(
plungerAnchor.body.position.y,
equals(plunger.body.position.y - compressionDistance),
);
},
);
});
group('PlungerAnchorPrismaticJointDef', () {
const compressionDistance = 10.0;
final gameBloc = MockGameBloc(); final gameBloc = MockGameBloc();
late Plunger plunger;
setUp(() { setUp(() {
whenListen( whenListen(
@ -138,51 +221,21 @@ void main() {
const Stream<GameState>.empty(), const Stream<GameState>.empty(),
initialState: const GameState.initial(), initialState: const GameState.initial(),
); );
plunger = Plunger(position: Vector2.zero()); plunger = Plunger(
anchor = Anchor(position: Vector2(0, -1)); position: Vector2.zero(),
compressionDistance: compressionDistance,
);
}); });
final flameTester = flameBlocTester(gameBloc: gameBloc); final flameTester = flameBlocTester(gameBloc: gameBloc);
flameTester.test(
'throws AssertionError '
'when anchor is above plunger',
(game) async {
final anchor = Anchor(position: Vector2(0, 1));
await game.ensureAddAll([plunger, anchor]);
expect(
() => PlungerAnchorPrismaticJointDef(
plunger: plunger,
anchor: anchor,
),
throwsAssertionError,
);
},
);
flameTester.test(
'throws AssertionError '
'when anchor is in same position as plunger',
(game) async {
final anchor = Anchor(position: Vector2.zero());
await game.ensureAddAll([plunger, anchor]);
expect(
() => PlungerAnchorPrismaticJointDef(
plunger: plunger,
anchor: anchor,
),
throwsAssertionError,
);
},
);
group('initializes with', () { group('initializes with', () {
flameTester.test( flameTester.test(
'plunger body as bodyA', 'plunger body as bodyA',
(game) async { (game) async {
await game.ensureAddAll([plunger, anchor]); await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
@ -196,7 +249,9 @@ void main() {
flameTester.test( flameTester.test(
'anchor body as bodyB', 'anchor body as bodyB',
(game) async { (game) async {
await game.ensureAddAll([plunger, anchor]); await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
@ -211,7 +266,9 @@ void main() {
flameTester.test( flameTester.test(
'limits enabled', 'limits enabled',
(game) async { (game) async {
await game.ensureAddAll([plunger, anchor]); await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
@ -226,7 +283,9 @@ void main() {
flameTester.test( flameTester.test(
'lower translation limit as negative infinity', 'lower translation limit as negative infinity',
(game) async { (game) async {
await game.ensureAddAll([plunger, anchor]); await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
@ -241,7 +300,9 @@ void main() {
flameTester.test( flameTester.test(
'connected body collison enabled', 'connected body collison enabled',
(game) async { (game) async {
await game.ensureAddAll([plunger, anchor]); await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
@ -254,46 +315,51 @@ void main() {
); );
}); });
flameTester.widgetTest( testRawKeyUpEvents([LogicalKeyboardKey.space], (event) {
'plunger cannot go below anchor', flameTester.widgetTest(
(game, tester) async { 'plunger cannot go below anchor',
await game.ensureAddAll([plunger, anchor]); (game, tester) async {
await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
// Giving anchor a shape for the plunger to collide with. // Giving anchor a shape for the plunger to collide with.
anchor.body.createFixtureFromShape(PolygonShape()..setAsBoxXY(2, 1)); anchor.body.createFixtureFromShape(PolygonShape()..setAsBoxXY(2, 1));
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
anchor: anchor, anchor: anchor,
); );
game.world.createJoint(jointDef); game.world.createJoint(jointDef);
plunger.pull(); await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(plunger.body.position.y > anchor.body.position.y, isTrue); expect(plunger.body.position.y > anchor.body.position.y, isTrue);
}, },
); );
});
flameTester.widgetTest( testRawKeyUpEvents([LogicalKeyboardKey.space], (event) {
'plunger cannot excessively exceed starting position', flameTester.widgetTest(
(game, tester) async { 'plunger cannot excessively exceed starting position',
await game.ensureAddAll([plunger, anchor]); (game, tester) async {
await game.ensureAdd(plunger);
final anchor = PlungerAnchor(plunger: plunger);
await game.ensureAdd(anchor);
final jointDef = PlungerAnchorPrismaticJointDef( final jointDef = PlungerAnchorPrismaticJointDef(
plunger: plunger, plunger: plunger,
anchor: anchor, anchor: anchor,
); );
game.world.createJoint(jointDef); game.world.createJoint(jointDef);
plunger.pull(); plunger.body.setTransform(Vector2(0, -1), 0);
await tester.pump(const Duration(seconds: 1));
plunger.release(); await tester.pump(const Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(plunger.body.position.y < 1, isTrue); expect(plunger.body.position.y < 1, isTrue);
}, },
); );
});
}); });
} }

@ -77,7 +77,7 @@ void main() {
); );
}); });
group('first fixture', () { group('fixture', () {
flameTester.test( flameTester.test(
'exists', 'exists',
(game) async { (game) async {
@ -92,7 +92,7 @@ void main() {
); );
flameTester.test( flameTester.test(
'has restitution equals 0', 'has restitution',
(game) async { (game) async {
final wall = Wall( final wall = Wall(
start: Vector2.zero(), start: Vector2.zero(),
@ -101,7 +101,7 @@ void main() {
await game.ensureAdd(wall); await game.ensureAdd(wall);
final fixture = wall.body.fixtures[0]; final fixture = wall.body.fixtures[0];
expect(fixture.restitution, equals(0)); expect(fixture.restitution, greaterThan(0));
}, },
); );

@ -17,60 +17,102 @@ void main() {
// TODO(alestiago): test if [PinballGame] registers // TODO(alestiago): test if [PinballGame] registers
// [BallScorePointsCallback] once the following issue is resolved: // [BallScorePointsCallback] once the following issue is resolved:
// https://github.com/flame-engine/flame/issues/1416 // https://github.com/flame-engine/flame/issues/1416
group( group('components', () {
'components', group('Walls', () {
() { flameTester.test(
group('Flippers', () { 'has three Walls',
bool Function(Component) flipperSelector(BoardSide side) => (game) async {
(component) => component is Flipper && component.side == side; await game.ready();
final walls = game.children
flameTester.test( .where(
'has only one left Flipper', (component) => component is Wall && component is! BottomWall,
(game) async { )
await game.ready(); .toList();
// TODO(allisonryan0002): expect 3 when launch track is added and
expect( // temporary wall is removed.
() => game.children.singleWhere( expect(walls.length, 4);
flipperSelector(BoardSide.left), },
), );
returnsNormally,
);
},
);
flameTester.test(
'has only one right Flipper',
(game) async {
await game.ready();
expect(
() => game.children.singleWhere(
flipperSelector(BoardSide.right),
),
returnsNormally,
);
},
);
debugModeFlameTester.test('adds a ball on tap up', (game) async { flameTester.test(
'has only one BottomWall',
(game) async {
await game.ready(); await game.ready();
final eventPosition = MockEventPosition(); expect(
when(() => eventPosition.game).thenReturn(Vector2.all(10)); () => game.children.singleWhere(
(component) => component is BottomWall,
),
returnsNormally,
);
},
);
});
final tapUpEvent = MockTapUpInfo(); group('Flippers', () {
when(() => tapUpEvent.eventPosition).thenReturn(eventPosition); bool Function(Component) flipperSelector(BoardSide side) =>
(component) => component is Flipper && component.side == side;
game.onTapUp(tapUpEvent); flameTester.test(
'has only one left Flipper',
(game) async {
await game.ready(); await game.ready();
expect( expect(
game.children.whereType<Ball>().length, () => game.children.singleWhere(
equals(1), flipperSelector(BoardSide.left),
),
returnsNormally,
); );
}); },
}); );
},
); flameTester.test(
'has only one right Flipper',
(game) async {
await game.ready();
expect(
() => game.children.singleWhere(
flipperSelector(BoardSide.right),
),
returnsNormally,
);
},
);
});
flameTester.test(
'Plunger has only one Plunger',
(game) async {
await game.ready();
expect(
() => game.children.singleWhere(
(component) => component is Plunger,
),
returnsNormally,
);
},
);
});
debugModeFlameTester.test('adds a ball on tap up', (game) async {
await game.ready();
final eventPosition = MockEventPosition();
when(() => eventPosition.game).thenReturn(Vector2.all(10));
final tapUpEvent = MockTapUpInfo();
when(() => tapUpEvent.eventPosition).thenReturn(eventPosition);
game.onTapUp(tapUpEvent);
await game.ready();
expect(
game.children.whereType<Ball>().length,
equals(1),
);
});
}); });
} }

Loading…
Cancel
Save