Migrate examples to null-safety (#707)

This commit is contained in:
Luan Nico
2021-03-24 19:04:33 -04:00
committed by GitHub
parent 98e8515518
commit 640bfea941
34 changed files with 146 additions and 145 deletions

View File

@ -134,7 +134,7 @@ linter:
dart_code_metrics: dart_code_metrics:
rules: rules:
- prefer-trailing-comma #- prefer-trailing-comma TODO(luan) this is broken on NS
- prefer-trailing-comma-for-collection - prefer-trailing-comma-for-collection
- no-equal-then-else - no-equal-then-else
- no-object-declaration - no-object-declaration
@ -143,7 +143,7 @@ dart_code_metrics:
- test/** - test/**
metrics: metrics:
number-of-arguments: 8 number-of-arguments: 8
number-of-methods: 28 number-of-methods: 32
lines-of-executable-code: 200 lines-of-executable-code: 200
cyclomatic-complexity: 36 cyclomatic-complexity: 36

View File

@ -6,9 +6,9 @@ import 'package:flame/gestures.dart';
import 'package:flutter/gestures.dart' show TapDownDetails; import 'package:flutter/gestures.dart' show TapDownDetails;
class BasicAnimations extends BaseGame with TapDetector { class BasicAnimations extends BaseGame with TapDetector {
Image chopper; late Image chopper;
Image creature; late Image creature;
SpriteAnimation animation; late SpriteAnimation animation;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -32,14 +32,15 @@ class ParentSquare extends Square {
} }
class Composability extends BaseGame { class Composability extends BaseGame {
ParentSquare _parent; late ParentSquare _parent;
@override @override
bool debugMode = true; bool debugMode = true;
Composability() { @override
_parent = ParentSquare(Vector2.all(200), Vector2.all(300)); Future<void> onLoad() async {
_parent.anchor = Anchor.center; _parent = ParentSquare(Vector2.all(200), Vector2.all(300))
..anchor = Anchor.center;
add(_parent); add(_parent);
} }

View File

@ -20,14 +20,14 @@ class LogoCompomnent extends SpriteComponent with HasGameRef<DebugGame> {
final rect = toRect(); final rect = toRect();
if ((x <= 0 && xDirection == -1) || if ((x <= 0 && xDirection == -1) ||
(rect.right >= gameRef.size.x && xDirection == 1)) { (rect.right >= gameRef!.size.x && xDirection == 1)) {
xDirection = xDirection * -1; xDirection = xDirection * -1;
} }
y += yDirection * speed * dt; y += yDirection * speed * dt;
if ((y <= 0 && yDirection == -1) || if ((y <= 0 && yDirection == -1) ||
(rect.bottom >= gameRef.size.y && yDirection == 1)) { (rect.bottom >= gameRef!.size.y && yDirection == 1)) {
yDirection = yDirection * -1; yDirection = yDirection * -1;
} }
} }

View File

@ -11,13 +11,13 @@ class DraggableSquare extends PositionComponent
@override @override
bool debugMode = true; bool debugMode = true;
DraggableSquare({Vector2 position}) DraggableSquare({Vector2? position})
: super( : super(
position: position ?? Vector2.all(100), position: position ?? Vector2.all(100),
size: Vector2.all(100), size: Vector2.all(100),
); );
Vector2 dragDeltaPosition; Vector2? dragDeltaPosition;
bool get isDragging => dragDeltaPosition != null; bool get isDragging => dragDeltaPosition != null;
@override @override
@ -34,7 +34,12 @@ class DraggableSquare extends PositionComponent
@override @override
bool onDragUpdate(int pointerId, DragUpdateDetails details) { bool onDragUpdate(int pointerId, DragUpdateDetails details) {
final localCoords = gameRef.convertGlobalToLocalCoordinate( final dragDeltaPosition = this.dragDeltaPosition;
if (dragDeltaPosition == null) {
return false;
}
final localCoords = gameRef!.convertGlobalToLocalCoordinate(
details.globalPosition.toVector2(), details.globalPosition.toVector2(),
); );
position = localCoords - dragDeltaPosition; position = localCoords - dragDeltaPosition;

View File

@ -17,29 +17,24 @@ class JoystickPlayer extends Component implements JoystickListener {
double currentSpeed = 0; double currentSpeed = 0;
double angle = 0; double angle = 0;
bool _move = false; bool move = false;
Paint _paint; Paint paint;
Rect _rect; late Rect rect;
JoystickPlayer() { JoystickPlayer() : paint = _whitePaint;
_paint = _whitePaint;
}
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {
if (_rect == null) { canvas.translate(rect.center.dx, rect.center.dy);
return;
}
canvas.translate(_rect.center.dx, _rect.center.dy);
canvas.rotate(angle == 0.0 ? 0.0 : angle + (pi / 2)); canvas.rotate(angle == 0.0 ? 0.0 : angle + (pi / 2));
canvas.translate(-_rect.center.dx, -_rect.center.dy); canvas.translate(-rect.center.dx, -rect.center.dy);
canvas.drawRect(_rect, _paint); canvas.drawRect(rect, paint);
} }
@override @override
void update(double dt) { void update(double dt) {
super.update(dt); super.update(dt);
if (_move) { if (move) {
moveFromAngle(dt); moveFromAngle(dt);
} }
} }
@ -47,7 +42,7 @@ class JoystickPlayer extends Component implements JoystickListener {
@override @override
void onGameResize(Vector2 gameSize) { void onGameResize(Vector2 gameSize) {
final offset = (gameSize - size) / 2; final offset = (gameSize - size) / 2;
_rect = offset & size; rect = offset & size;
super.onGameResize(gameSize); super.onGameResize(gameSize);
} }
@ -55,33 +50,29 @@ class JoystickPlayer extends Component implements JoystickListener {
void joystickAction(JoystickActionEvent event) { void joystickAction(JoystickActionEvent event) {
if (event.event == ActionEvent.down) { if (event.event == ActionEvent.down) {
if (event.id == 1) { if (event.id == 1) {
_paint = _paint == _whitePaint ? _bluePaint : _whitePaint; paint = paint == _whitePaint ? _bluePaint : _whitePaint;
} }
if (event.id == 2) { if (event.id == 2) {
_paint = _paint == _whitePaint ? _greenPaint : _whitePaint; paint = paint == _whitePaint ? _greenPaint : _whitePaint;
} }
} else if (event.event == ActionEvent.move) { } else if (event.event == ActionEvent.move) {
if (event.id == 3) { if (event.id == 3) {
angle = event.angle ?? angle; angle = event.angle;
} }
} }
} }
@override @override
void joystickChangeDirectional(JoystickDirectionalEvent event) { void joystickChangeDirectional(JoystickDirectionalEvent event) {
_move = event.directional != JoystickMoveDirectional.idle; move = event.directional != JoystickMoveDirectional.idle;
if (_move) { if (move) {
angle = event.angle; angle = event.angle;
currentSpeed = speed * event.intensity; currentSpeed = speed * event.intensity;
} }
} }
void moveFromAngle(double dtUpdate) { void moveFromAngle(double dtUpdate) {
if (_rect == null) {
return;
}
final next = Vector2(cos(angle), sin(angle)) * (currentSpeed * dtUpdate); final next = Vector2(cos(angle), sin(angle)) * (currentSpeed * dtUpdate);
_rect = _rect.shift(next.toOffset()); rect = rect.shift(next.toOffset());
} }
} }

View File

@ -6,21 +6,21 @@ import 'package:flame/palette.dart';
import 'package:flutter/services.dart' show RawKeyDownEvent, RawKeyEvent; import 'package:flutter/services.dart' show RawKeyDownEvent, RawKeyEvent;
class KeyboardGame extends Game with KeyboardEvents { class KeyboardGame extends Game with KeyboardEvents {
static final Paint _white = BasicPalette.white.paint; static final Paint white = BasicPalette.white.paint;
static const int speed = 200; static const int speed = 200;
Rect _rect = const Rect.fromLTWH(0, 100, 100, 100); Rect rect = const Rect.fromLTWH(0, 100, 100, 100);
final Vector2 velocity = Vector2(0, 0); final Vector2 velocity = Vector2(0, 0);
@override @override
void update(double dt) { void update(double dt) {
final displacement = velocity * (speed * dt); final displacement = velocity * (speed * dt);
_rect = _rect.translate(displacement.x, displacement.y); rect = rect.translate(displacement.x, displacement.y);
} }
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {
canvas.drawRect(_rect, _white); canvas.drawRect(rect, white);
} }
@override @override

View File

@ -7,37 +7,39 @@ import 'package:flutter/material.dart';
class MouseMovementGame extends BaseGame with MouseMovementDetector { class MouseMovementGame extends BaseGame with MouseMovementDetector {
static const speed = 200; static const speed = 200;
static final Paint _blue = Paint()..color = const Color(0xFF0000FF); static final Paint blue = Paint()..color = const Color(0xFF0000FF);
static final Vector2 _size = Vector2.all(50); static final Paint white = BasicPalette.white.paint;
static final Vector2 objSize = Vector2.all(50);
Vector2 position = Vector2(0, 0); Vector2 position = Vector2(0, 0);
Vector2 target; Vector2? target;
bool _onTarget = false; bool onTarget = false;
@override @override
void onMouseMove(PointerHoverEvent event) { void onMouseMove(PointerHoverEvent event) {
target = event.localPosition.toVector2(); target = event.localPosition.toVector2();
} }
Rect _toRect() => position.toPositionedRect(_size); Rect _toRect() => position.toPositionedRect(objSize);
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {
super.render(canvas); super.render(canvas);
canvas.drawRect( canvas.drawRect(
_toRect(), _toRect(),
_onTarget ? _blue : BasicPalette.white.paint, onTarget ? blue : white,
); );
} }
@override @override
void update(double dt) { void update(double dt) {
final target = this.target;
super.update(dt); super.update(dt);
if (target != null) { if (target != null) {
_onTarget = _toRect().contains(target.toOffset()); onTarget = _toRect().contains(target.toOffset());
if (!_onTarget) { if (!onTarget) {
final dir = (target - position).normalized(); final dir = (target - position).normalized();
position += dir * (speed * dt); position += dir * (speed * dt);
} }

View File

@ -6,32 +6,32 @@ import 'package:flutter/material.dart';
/// Includes an example including advanced detectors /// Includes an example including advanced detectors
class MultitapGame extends BaseGame with MultiTouchTapDetector { class MultitapGame extends BaseGame with MultiTouchTapDetector {
static final _whitePaint = BasicPalette.white.paint; static final whitePaint = BasicPalette.white.paint;
static final _size = Vector2.all(50); static final tapSize = Vector2.all(50);
final Map<int, Rect> _taps = {}; final Map<int, Rect> taps = {};
@override @override
void onTapDown(int pointerId, TapDownDetails details) { void onTapDown(int pointerId, TapDownDetails details) {
_taps[pointerId] = taps[pointerId] =
details.globalPosition.toVector2().toPositionedRect(_size); details.globalPosition.toVector2().toPositionedRect(tapSize);
} }
@override @override
void onTapUp(int pointerId, _) { void onTapUp(int pointerId, _) {
_taps.remove(pointerId); taps.remove(pointerId);
} }
@override @override
void onTapCancel(int pointerId) { void onTapCancel(int pointerId) {
_taps.remove(pointerId); taps.remove(pointerId);
} }
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {
super.render(canvas); super.render(canvas);
_taps.values.forEach((rect) { taps.values.forEach((rect) {
canvas.drawRect(rect, _whitePaint); canvas.drawRect(rect, whitePaint);
}); });
} }
} }

View File

@ -7,65 +7,67 @@ import 'package:flutter/material.dart';
/// Showcases how to mix two advanced detectors /// Showcases how to mix two advanced detectors
class MultitapAdvancedGame extends BaseGame class MultitapAdvancedGame extends BaseGame
with MultiTouchTapDetector, MultiTouchDragDetector { with MultiTouchTapDetector, MultiTouchDragDetector {
static final _whitePaint = BasicPalette.white.paint; static final whitePaint = BasicPalette.white.paint;
static final _size = Vector2.all(50); static final tapSize = Vector2.all(50);
final Map<int, Rect> _taps = {}; final Map<int, Rect> taps = {};
Vector2 _start; Vector2? start;
Vector2 _end; Vector2? end;
Rect _panRect; Rect? panRect;
@override @override
void onTapDown(int pointerId, TapDownDetails details) { void onTapDown(int pointerId, TapDownDetails details) {
_taps[pointerId] = taps[pointerId] =
details.globalPosition.toVector2().toPositionedRect(_size); details.globalPosition.toVector2().toPositionedRect(tapSize);
} }
@override @override
void onTapUp(int pointerId, _) { void onTapUp(int pointerId, _) {
_taps.remove(pointerId); taps.remove(pointerId);
} }
@override @override
void onTapCancel(int pointerId) { void onTapCancel(int pointerId) {
_taps.remove(pointerId); taps.remove(pointerId);
} }
@override @override
void onDragCancel(int pointerId) { void onDragCancel(int pointerId) {
_end = null; end = null;
_start = null; start = null;
_panRect = null; panRect = null;
} }
@override @override
void onDragStart(int pointerId, Vector2 position) { void onDragStart(int pointerId, Vector2 position) {
_end = null; end = null;
_start = position; start = position;
} }
@override @override
void onDragUpdate(int pointerId, DragUpdateDetails details) { void onDragUpdate(int pointerId, DragUpdateDetails details) {
_end = details.localPosition.toVector2(); end = details.localPosition.toVector2();
} }
@override @override
void onDragEnd(int pointerId, DragEndDetails details) { void onDragEnd(int pointerId, DragEndDetails details) {
if (_start != null && _end != null) { final start = this.start, end = this.end;
_panRect = _start.toPositionedRect(_end - _start); if (start != null && end != null) {
panRect = start.toPositionedRect(end - start);
} }
} }
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {
final panRect = this.panRect;
super.render(canvas); super.render(canvas);
_taps.values.forEach((rect) { taps.values.forEach((rect) {
canvas.drawRect(rect, _whitePaint); canvas.drawRect(rect, whitePaint);
}); });
if (_panRect != null) { if (panRect != null) {
canvas.drawRect(_panRect, _whitePaint); canvas.drawRect(panRect, whitePaint);
} }
} }
} }

View File

@ -19,13 +19,12 @@ class TapableSquare extends PositionComponent with Tapable {
Paint currentPaint; Paint currentPaint;
TapableSquare({Vector2 position}) TapableSquare({Vector2? position})
: super( : currentPaint = _randomPaint(),
super(
position: position ?? Vector2.all(100), position: position ?? Vector2.all(100),
size: Vector2.all(100), size: Vector2.all(100),
) { );
currentPaint = _randomPaint();
}
@override @override
void render(Canvas canvas) { void render(Canvas canvas) {

View File

@ -12,7 +12,7 @@ class ScrollGame extends BaseGame with ScrollDetector {
final _paint = BasicPalette.white.paint; final _paint = BasicPalette.white.paint;
Vector2 position = Vector2.all(100); Vector2 position = Vector2.all(100);
Vector2 target; Vector2? target;
@override @override
void onScroll(PointerScrollEvent event) { void onScroll(PointerScrollEvent event) {
@ -29,6 +29,7 @@ class ScrollGame extends BaseGame with ScrollDetector {
@override @override
void update(double dt) { void update(double dt) {
super.update(dt); super.update(dt);
final target = this.target;
if (target != null) { if (target != null) {
final dir = (target - position).normalized(); final dir = (target - position).normalized();
position += dir * (speed * dt); position += dir * (speed * dt);

View File

@ -9,7 +9,7 @@ class TapableSquare extends PositionComponent with Tapable {
bool _beenPressed = false; bool _beenPressed = false;
TapableSquare({Vector2 position}) TapableSquare({Vector2? position})
: super( : super(
position: position ?? Vector2.all(100), position: position ?? Vector2.all(100),
size: Vector2.all(100), size: Vector2.all(100),

View File

@ -10,7 +10,7 @@ final green = Paint()..color = const Color(0xAA338833);
final red = Paint()..color = const Color(0xAA883333); final red = Paint()..color = const Color(0xAA883333);
class CombinedEffectGame extends BaseGame with TapDetector { class CombinedEffectGame extends BaseGame with TapDetector {
SquareComponent greenSquare, redSquare; late SquareComponent greenSquare, redSquare;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -19,9 +19,9 @@ SquareComponent makeSquare(Paint paint) {
} }
class InfiniteEffectGame extends BaseGame with TapDetector { class InfiniteEffectGame extends BaseGame with TapDetector {
SquareComponent greenSquare; late SquareComponent greenSquare;
SquareComponent redSquare; late SquareComponent redSquare;
SquareComponent orangeSquare; late SquareComponent orangeSquare;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -7,7 +7,7 @@ import 'package:flutter/material.dart';
import '../../commons/square_component.dart'; import '../../commons/square_component.dart';
class MoveEffectGame extends BaseGame with TapDetector { class MoveEffectGame extends BaseGame with TapDetector {
SquareComponent square; late SquareComponent square;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -10,7 +10,7 @@ import 'package:flutter/material.dart';
import '../../commons/square_component.dart'; import '../../commons/square_component.dart';
class RotateEffectGame extends BaseGame with TapDetector { class RotateEffectGame extends BaseGame with TapDetector {
SquareComponent square; late SquareComponent square;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -8,7 +8,7 @@ import 'package:flutter/material.dart';
import '../../commons/square_component.dart'; import '../../commons/square_component.dart';
class ScaleEffectGame extends BaseGame with TapDetector { class ScaleEffectGame extends BaseGame with TapDetector {
SquareComponent square; late SquareComponent square;
bool grow = true; bool grow = true;
@override @override

View File

@ -9,7 +9,7 @@ import '../../commons/square_component.dart';
final green = Paint()..color = const Color(0xAA338833); final green = Paint()..color = const Color(0xAA338833);
class SequenceEffectGame extends BaseGame with TapDetector { class SequenceEffectGame extends BaseGame with TapDetector {
SquareComponent greenSquare; late SquareComponent greenSquare;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -13,7 +13,7 @@ class MyParallaxComponent extends ParallaxComponent
with HasGameRef<ComponentParallaxGame> { with HasGameRef<ComponentParallaxGame> {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
parallax = await gameRef.loadParallax( parallax = await gameRef!.loadParallax(
[ [
'parallax/bg.png', 'parallax/bg.png',
'parallax/mountain-far.png', 'parallax/mountain-far.png',

View File

@ -10,7 +10,7 @@ import 'package:flutter/material.dart';
/// FCS is only used when you extend BaseGame, not Game, /// FCS is only used when you extend BaseGame, not Game,
/// like we do in this example. /// like we do in this example.
class NoFCSParallaxGame extends Game { class NoFCSParallaxGame extends Game {
Parallax parallax; late Parallax parallax;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -45,8 +45,8 @@ class BackgroundLayer extends PreRenderedLayer {
} }
class LayerGame extends Game { class LayerGame extends Game {
Layer gameLayer; late Layer gameLayer;
Layer backgroundLayer; late Layer backgroundLayer;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -5,8 +5,8 @@ import 'package:flame/game.dart';
import 'package:flame/palette.dart'; import 'package:flame/palette.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
final regular = TextConfig(color: BasicPalette.white.color); final _regular = TextConfig(color: BasicPalette.white.color);
final tiny = regular.withFontSize(12.0); final _tiny = _regular.withFontSize(12.0);
final _white = Paint() final _white = Paint()
..color = BasicPalette.white.color ..color = BasicPalette.white.color
@ -16,7 +16,7 @@ class MyTextBox extends TextBoxComponent {
MyTextBox(String text) MyTextBox(String text)
: super( : super(
text, text,
config: tiny, config: _tiny,
boxConfig: TextBoxConfig( boxConfig: TextBoxConfig(
timePerChar: 0.05, timePerChar: 0.05,
growingBox: true, growingBox: true,
@ -43,20 +43,20 @@ class TextGame extends BaseGame {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
add( add(
TextComponent('Hello, Flame', config: regular) TextComponent('Hello, Flame', config: _regular)
..anchor = Anchor.topCenter ..anchor = Anchor.topCenter
..x = size.x / 2 ..x = size.x / 2
..y = 32.0, ..y = 32.0,
); );
add( add(
TextComponent('center', config: tiny) TextComponent('center', config: _tiny)
..anchor = Anchor.center ..anchor = Anchor.center
..position = size / 2, ..position = size / 2,
); );
add( add(
TextComponent('bottomRight', config: tiny) TextComponent('bottomRight', config: _tiny)
..anchor = Anchor.bottomRight ..anchor = Anchor.bottomRight
..position = size, ..position = size,
); );

View File

@ -9,7 +9,8 @@ class MySpriteBatchComponent extends SpriteBatchComponent
with HasGameRef<SpritebatchAutoLoadGame> { with HasGameRef<SpritebatchAutoLoadGame> {
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
spriteBatch = await gameRef.loadSpriteBatch('boom.png'); final spriteBatch = await gameRef!.loadSpriteBatch('boom.png');
this.spriteBatch = spriteBatch;
spriteBatch.add( spriteBatch.add(
source: const Rect.fromLTWH(128 * 4.0, 128 * 4.0, 64, 128), source: const Rect.fromLTWH(128 * 4.0, 128 * 4.0, 64, 128),
@ -25,14 +26,14 @@ class MySpriteBatchComponent extends SpriteBatchComponent
color: Colors.redAccent, color: Colors.redAccent,
); );
final size = gameRef!.size;
const num = 100; const num = 100;
final r = Random(); final r = Random();
for (var i = 0; i < num; ++i) { for (var i = 0; i < num; ++i) {
final sx = r.nextInt(8) * 128.0; final sx = r.nextInt(8) * 128.0;
final sy = r.nextInt(8) * 128.0; final sy = r.nextInt(8) * 128.0;
final x = r.nextInt(gameRef.size.x.toInt()).toDouble(); final x = r.nextInt(size.x.toInt()).toDouble();
final y = final y = r.nextInt(size.y ~/ 2).toDouble() + size.y / 2.0;
r.nextInt(gameRef.size.y ~/ 2).toDouble() + gameRef.size.y / 2.0;
spriteBatch.add( spriteBatch.add(
source: Rect.fromLTWH(sx, sy, 128, 128), source: Rect.fromLTWH(sx, sy, 128, 128),
offset: Vector2(x - 64, y - 64), offset: Vector2(x - 64, y - 64),

View File

@ -34,8 +34,8 @@ class Selector extends SpriteComponent {
} }
class IsometricTileMapGame extends BaseGame with MouseMovementDetector { class IsometricTileMapGame extends BaseGame with MouseMovementDetector {
IsometricTileMapComponent base; late IsometricTileMapComponent base;
Selector selector; late Selector selector;
IsometricTileMapGame(); IsometricTileMapGame();
@ -73,9 +73,6 @@ class IsometricTileMapGame extends BaseGame with MouseMovementDetector {
@override @override
void onMouseMove(PointerHoverEvent event) { void onMouseMove(PointerHoverEvent event) {
if (base == null || selector == null) {
return; // loading
}
final screenPosition = event.localPosition.toVector2(); final screenPosition = event.localPosition.toVector2();
final block = base.getBlock(screenPosition); final block = base.getBlock(screenPosition);
selector.show = base.containsBlock(block); selector.show = base.containsBlock(block);

View File

@ -17,14 +17,14 @@ class MovableSquare extends SquareComponent
static final TextConfig config = TextConfig(fontSize: 12); static final TextConfig config = TextConfig(fontSize: 12);
final Vector2 velocity = Vector2.zero(); final Vector2 velocity = Vector2.zero();
Timer timer; late Timer timer;
MovableSquare() { MovableSquare() {
addShape(HitboxRectangle()); addShape(HitboxRectangle());
timer = Timer(3.0) timer = Timer(3.0)
..stop() ..stop()
..callback = () { ..callback = () {
gameRef.camera.setRelativeOffset(Anchor.center.toVector2()); gameRef!.camera.setRelativeOffset(Anchor.center.toVector2());
}; };
} }
@ -50,7 +50,7 @@ class MovableSquare extends SquareComponent
@override @override
void onCollision(Set<Vector2> points, Collidable other) { void onCollision(Set<Vector2> points, Collidable other) {
if (other is Rock) { if (other is Rock) {
gameRef.camera.setRelativeOffset(Anchor.topCenter.toVector2()); gameRef!.camera.setRelativeOffset(Anchor.topCenter.toVector2());
timer.start(); timer.start();
} }
} }
@ -95,7 +95,7 @@ class Rock extends SquareComponent with Hitbox, Collidable {
class CameraAndViewportGame extends BaseGame class CameraAndViewportGame extends BaseGame
with KeyboardEvents, HasCollidables { with KeyboardEvents, HasCollidables {
MovableSquare square; late MovableSquare square;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -3,7 +3,7 @@ import 'package:flame/game.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
class NineTileBoxGame extends Game { class NineTileBoxGame extends Game {
NineTileBox nineTileBox; late NineTileBox nineTileBox;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {

View File

@ -28,17 +28,14 @@ class ParticlesGame extends BaseGame {
/// Defines the lifespan of all the particles in these examples /// Defines the lifespan of all the particles in these examples
final sceneDuration = const Duration(seconds: 1); final sceneDuration = const Duration(seconds: 1);
Vector2 cellSize; Vector2 get cellSize => size / gridSize;
Vector2 halfCellSize; Vector2 get halfCellSize => cellSize / 2;
@override @override
Future<void> onLoad() async { Future<void> onLoad() async {
await images.load('zap.png'); await images.load('zap.png');
await images.load('boom.png'); await images.load('boom.png');
cellSize = size / gridSize;
halfCellSize = cellSize * .5;
// Spawn new particles every second // Spawn new particles every second
Timer.periodic(sceneDuration, (_) => spawnParticles()); Timer.periodic(sceneDuration, (_) => spawnParticles());
} }
@ -78,8 +75,7 @@ class ParticlesGame extends BaseGame {
final particle = particles.removeLast(); final particle = particles.removeLast();
final col = particles.length % gridSize; final col = particles.length % gridSize;
final row = (particles.length ~/ gridSize).toDouble(); final row = (particles.length ~/ gridSize).toDouble();
final cellCenter = final cellCenter = (cellSize..multiply(Vector2(col, row))) + halfCellSize;
(cellSize.clone()..multiply(Vector2(col, row))) + (cellSize * .5);
add( add(
// Bind all the particles to a [Component] update // Bind all the particles to a [Component] update
@ -218,7 +214,7 @@ class ParticlesGame extends BaseGame {
Colors.red, Colors.red,
Colors.blue, Colors.blue,
particle.progress, particle.progress,
), )!,
), ),
); );
} }
@ -242,14 +238,14 @@ class ParticlesGame extends BaseGame {
Colors.red, Colors.red,
Colors.blue, Colors.blue,
steppedProgress, steppedProgress,
), )!,
); );
}, },
); );
} }
/// Particle which is used in example below /// Particle which is used in example below
Particle reusablePatricle; Particle? reusablePatricle;
/// A burst of white circles which actually using a single circle /// A burst of white circles which actually using a single circle
/// as a form of optimization. Look for reusing parts of particle effects /// as a form of optimization. Look for reusing parts of particle effects
@ -261,7 +257,7 @@ class ParticlesGame extends BaseGame {
generator: (i) => MovingParticle( generator: (i) => MovingParticle(
curve: Interval(rnd.nextDouble() * .1, rnd.nextDouble() * .8 + .1), curve: Interval(rnd.nextDouble() * .1, rnd.nextDouble() * .8 + .1),
to: randomCellOffset() * .5, to: randomCellOffset() * .5,
child: reusablePatricle, child: reusablePatricle!,
), ),
); );
} }
@ -277,7 +273,7 @@ class ParticlesGame extends BaseGame {
} }
/// Particle which is used in example below /// Particle which is used in example below
Particle reusableImageParticle; Particle? reusableImageParticle;
/// A single [imageParticle] is drawn 9 times /// A single [imageParticle] is drawn 9 times
/// in a grid within grid cell. Looks as 9 particles /// in a grid within grid cell. Looks as 9 particles
@ -298,7 +294,7 @@ class ParticlesGame extends BaseGame {
(i % perLine) * colWidth - halfCellSize.x + imageSize, (i % perLine) * colWidth - halfCellSize.x + imageSize,
(i ~/ perLine) * rowHeight - halfCellSize.y + imageSize, (i ~/ perLine) * rowHeight - halfCellSize.y + imageSize,
), ),
child: reusableImageParticle, child: reusableImageParticle!,
), ),
); );
} }

View File

@ -5,12 +5,13 @@ import 'package:flame/gestures.dart';
class TimerGame extends Game with TapDetector { class TimerGame extends Game with TapDetector {
final TextConfig textConfig = TextConfig(color: const Color(0xFFFFFFFF)); final TextConfig textConfig = TextConfig(color: const Color(0xFFFFFFFF));
Timer countdown; late Timer countdown;
Timer interval; late Timer interval;
int elapsedSecs = 0; int elapsedSecs = 0;
TimerGame() { @override
Future<void> onLoad() async {
countdown = Timer(2); countdown = Timer(2);
interval = Timer( interval = Timer(
1, 1,

View File

@ -9,14 +9,14 @@ Widget overlayBuilder(DashbookContext ctx) {
} }
class OverlayExampleWidget extends StatefulWidget { class OverlayExampleWidget extends StatefulWidget {
const OverlayExampleWidget({Key key}) : super(key: key); const OverlayExampleWidget({Key? key}) : super(key: key);
@override @override
_OverlayExampleWidgetState createState() => _OverlayExampleWidgetState(); _OverlayExampleWidgetState createState() => _OverlayExampleWidgetState();
} }
class _OverlayExampleWidgetState extends State<OverlayExampleWidget> { class _OverlayExampleWidgetState extends State<OverlayExampleWidget> {
ExampleGame _myGame; ExampleGame? _myGame;
Widget pauseMenuBuilder(BuildContext buildContext, ExampleGame game) { Widget pauseMenuBuilder(BuildContext buildContext, ExampleGame game) {
return Center( return Center(
@ -33,14 +33,15 @@ class _OverlayExampleWidgetState extends State<OverlayExampleWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final myGame = _myGame;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Testing addingOverlay'), title: const Text('Testing addingOverlay'),
), ),
body: _myGame == null body: myGame == null
? const Text('Wait') ? const Text('Wait')
: GameWidget<ExampleGame>( : GameWidget<ExampleGame>(
game: _myGame, game: myGame,
overlayBuilderMap: { overlayBuilderMap: {
'PauseMenu': pauseMenuBuilder, 'PauseMenu': pauseMenuBuilder,
}, },

View File

@ -24,7 +24,7 @@ Widget spriteAnimationWidgetBuilder(DashbookContext ctx) {
animation: _animation, animation: _animation,
playing: ctx.boolProperty('playing', true), playing: ctx.boolProperty('playing', true),
anchor: Anchor.valueOf( anchor: Anchor.valueOf(
ctx.listProperty('anchor', 'Anchor.center', anchorOptions), ctx.listProperty('anchor', 'center', anchorOptions),
), ),
), ),
); );

View File

@ -12,7 +12,7 @@ Widget spriteWidgetBuilder(DashbookContext ctx) {
child: SpriteWidget( child: SpriteWidget(
sprite: Sprite(Flame.images.fromCache('shield.png')), sprite: Sprite(Flame.images.fromCache('shield.png')),
anchor: Anchor.valueOf( anchor: Anchor.valueOf(
ctx.listProperty('anchor', 'Anchor.center', anchorOptions), ctx.listProperty('anchor', 'center', anchorOptions),
), ),
), ),
); );

View File

@ -5,12 +5,13 @@ publish_to: 'none'
version: 0.1.0 version: 0.1.0
environment: environment:
sdk: ">=2.10.0 <3.0.0" sdk: ">=2.12.0-29.10.beta <3.0.0"
flutter: ">=1.24.0-10.2.pre"
dependencies: dependencies:
flame: flame:
path: ../packages/flame path: ../packages/flame
dashbook: 0.0.12 dashbook: 0.1.0
flutter: flutter:
sdk: flutter sdk: flutter

View File

@ -97,7 +97,10 @@ class Anchor {
} else { } else {
final regexp = RegExp(r'^\Anchor\(([^,]+), ([^\)]+)\)'); final regexp = RegExp(r'^\Anchor\(([^,]+), ([^\)]+)\)');
final matches = regexp.firstMatch(name)?.groups([1, 2]); final matches = regexp.firstMatch(name)?.groups([1, 2]);
assert(matches != null && matches.length == 2, 'Bad anchor format'); assert(
matches != null && matches.length == 2,
'Bad anchor format: $name',
);
return Anchor(double.parse(matches![0]!), double.parse(matches[1]!)); return Anchor(double.parse(matches![0]!), double.parse(matches[1]!));
} }
} }