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()
..userData = this
..position = _position
..position = Vector2(_position.x, _position.y + size.y)
..type = BodyType.dynamic;
return world.createBody(bodyDef)..createFixture(fixtureDef);

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

@ -1,23 +1,32 @@
import 'package:flame/input.dart';
import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:flutter/services.dart';
import 'package:pinball/game/game.dart' show Anchor;
/// {@template plunger}
/// [Plunger] serves as a spring, that shoots the ball on the right side of the
/// playfield.
///
/// [Plunger] ignores gravity so the player controls its downward [pull].
/// [Plunger] ignores gravity so the player controls its downward [_pull].
/// {@endtemplate}
class Plunger extends BodyComponent {
class Plunger extends BodyComponent with KeyboardHandler {
/// {@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;
/// Distance the plunger can lower.
final double compressionDistance;
@override
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()
..userData = this
@ -29,18 +38,57 @@ class Plunger extends BodyComponent {
}
/// Set a constant downward velocity on the [Plunger].
void pull() {
body.linearVelocity = Vector2(0, -7);
void _pull() {
body.linearVelocity = Vector2(0, -3);
}
/// Set an upward velocity on the [Plunger].
///
/// The velocity's magnitude depends on how far the [Plunger] has been pulled
/// from its original [_position].
void release() {
void _release() {
final velocity = (_position.y - body.position.y) * 9;
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}
@ -54,11 +102,8 @@ class PlungerAnchorPrismaticJointDef extends PrismaticJointDef {
/// {@macro plunger_anchor_prismatic_joint_def}
PlungerAnchorPrismaticJointDef({
required Plunger plunger,
required Anchor anchor,
}) : assert(
anchor.body.position.y < plunger.body.position.y,
'Anchor must be below the Plunger',
) {
required PlungerAnchor anchor,
}) {
initialize(
plunger.body,
anchor.body,
@ -67,6 +112,9 @@ class PlungerAnchorPrismaticJointDef extends PrismaticJointDef {
);
enableLimit = true;
lowerTranslation = double.negativeInfinity;
enableMotor = true;
motorSpeed = 50;
maxMotorForce = motorSpeed;
collideConnected = true;
}
}

@ -4,7 +4,7 @@ import 'package:flame_forge2d/flame_forge2d.dart';
import 'package:pinball/game/components/components.dart';
/// {@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}
// TODO(alestiago): Remove [Wall] for [Pathway.straight].
class Wall extends BodyComponent {
@ -25,7 +25,7 @@ class Wall extends BodyComponent {
final shape = EdgeShape()..set(start, end);
final fixtureDef = FixtureDef(shape)
..restitution = 0.0
..restitution = 0.1
..friction = 0.3;
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}
/// [Wall] located at the bottom of the board.
///

@ -13,17 +13,7 @@ class PinballGame extends Forge2DGame
final PinballTheme theme;
// TODO(erickzanardo): Change to the plumber position
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);
late final Plunger plunger;
@override
void onAttach() {
@ -31,21 +21,56 @@ class PinballGame extends Forge2DGame
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() {
add(Ball(position: ballStartingPosition));
add(Ball(position: plunger.body.position));
}
@override
Future<void> onLoad() async {
void _addContactCallbacks() {
addContactCallback(BallScorePointsCallback());
await add(BottomWall(this));
addContactCallback(BottomWallBallContactCallback());
}
unawaited(_addFlippers());
Future<void> _addGameBoundaries() async {
await add(BottomWall(this));
createBoundaries(this).forEach(add);
}
Future<void> _addFlippers() async {
final flippersPosition = screenToWorld(
Vector2(
camera.viewport.effectiveSize.x / 2,
camera.viewport.effectiveSize.y / 1.1,
),
);
const spaceBetweenFlippers = 2;
final leftFlipper = Flipper.left(
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 {

@ -34,7 +34,11 @@ void main() {
await game.ensureAdd(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(
'exists',
(game) async {

@ -255,9 +255,7 @@ void main() {
},
);
group(
'FlipperAnchor',
() {
group('FlipperAnchor', () {
flameTester.test(
'position is at the left of the left Flipper',
(game) async {
@ -283,8 +281,7 @@ void main() {
expect(flipperAnchor.body.position.x, equals(Flipper.width / 2));
},
);
},
);
});
group('FlipperAnchorRevoluteJointDef', () {
group('initializes with', () {

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

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

@ -17,9 +17,38 @@ void main() {
// TODO(alestiago): test if [PinballGame] registers
// [BallScorePointsCallback] once the following issue is resolved:
// https://github.com/flame-engine/flame/issues/1416
group(
'components',
() {
group('components', () {
group('Walls', () {
flameTester.test(
'has three Walls',
(game) async {
await game.ready();
final walls = game.children
.where(
(component) => component is Wall && component is! BottomWall,
)
.toList();
// TODO(allisonryan0002): expect 3 when launch track is added and
// temporary wall is removed.
expect(walls.length, 4);
},
);
flameTester.test(
'has only one BottomWall',
(game) async {
await game.ready();
expect(
() => game.children.singleWhere(
(component) => component is BottomWall,
),
returnsNormally,
);
},
);
});
group('Flippers', () {
bool Function(Component) flipperSelector(BoardSide side) =>
(component) => component is Flipper && component.side == side;
@ -51,6 +80,22 @@ void main() {
);
},
);
});
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();
@ -70,7 +115,4 @@ void main() {
);
});
});
},
);
});
}

Loading…
Cancel
Save