use final

This commit is contained in:
Renan Araujo
2019-03-22 13:35:46 -03:00
parent 5a2f576610
commit b1a3d222a9
26 changed files with 144 additions and 149 deletions

View File

@ -12,7 +12,7 @@ class MyGame extends BaseGame {
} }
_start() async { _start() async {
Size size = await Flame.util.initialDimensions(); final Size size = await Flame.util.initialDimensions();
final animation = await FlameAnimation.Animation.fromAsepriteData( final animation = await FlameAnimation.Animation.fromAsepriteData(
'chopper.png', 'chopper.json'); 'chopper.png', 'chopper.json');

View File

@ -20,8 +20,8 @@ class MyTextBox extends TextBoxComponent {
@override @override
void drawBackground(Canvas c) { void drawBackground(Canvas c) {
Rect rect = Rect.fromLTWH(0, 0, width, height); final Rect rect = Rect.fromLTWH(0, 0, width, height);
c.drawRect(rect, Paint()..color = Color(0xFFFF00FF)); c.drawRect(rect, Paint()..color = const Color(0xFFFF00FF));
c.drawRect( c.drawRect(
rect.deflate(boxConfig.margin), rect.deflate(boxConfig.margin),
Paint() Paint()
@ -36,7 +36,7 @@ class MyGame extends BaseGame {
} }
_start() async { _start() async {
Size size = await Flame.util.initialDimensions(); final Size size = await Flame.util.initialDimensions();
add(TextComponent('Hello, Flame', config: regular) add(TextComponent('Hello, Flame', config: regular)
..anchor = Anchor.topCenter ..anchor = Anchor.topCenter

View File

@ -3,7 +3,7 @@ import 'package:flame/game.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
void main() { void main() {
TiledGame game = TiledGame(); final TiledGame game = TiledGame();
runApp(game.widget); runApp(game.widget);
} }

View File

@ -41,7 +41,7 @@ class Square extends PositionComponent {
@override @override
void update(double t) { void update(double t) {
angle += SPEED * t; angle += SPEED * t;
angle %= (2 * math.pi); angle %= 2 * math.pi;
} }
} }

View File

@ -71,7 +71,7 @@ class Animation {
}) { }) {
frames = List<Frame>(amount); frames = List<Frame>(amount);
for (var i = 0; i < amount; i++) { for (var i = 0; i < amount; i++) {
Sprite sprite = Sprite( final Sprite sprite = Sprite(
imagePath, imagePath,
x: textureX + i * textureWidth, x: textureX + i * textureWidth,
y: textureY, y: textureY,
@ -94,7 +94,7 @@ class Animation {
}) { }) {
frames = List<Frame>(amount); frames = List<Frame>(amount);
for (var i = 0; i < amount; i++) { for (var i = 0; i < amount; i++) {
Sprite sprite = Sprite( final Sprite sprite = Sprite(
imagePath, imagePath,
x: textureX + i * textureWidth, x: textureX + i * textureWidth,
y: textureY, y: textureY,
@ -112,12 +112,12 @@ class Animation {
/// [dataPath]: Animation's exported data in json format /// [dataPath]: Animation's exported data in json format
static Future<Animation> fromAsepriteData( static Future<Animation> fromAsepriteData(
String imagePath, String dataPath) async { String imagePath, String dataPath) async {
String content = await Flame.assets.readFile(dataPath); final String content = await Flame.assets.readFile(dataPath);
Map<String, dynamic> json = jsonDecode(content); final Map<String, dynamic> json = jsonDecode(content);
Map<String, dynamic> jsonFrames = json['frames']; final Map<String, dynamic> jsonFrames = json['frames'];
var frames = jsonFrames.values.map((value) { final frames = jsonFrames.values.map((value) {
final frameData = value['frame']; final frameData = value['frame'];
final int x = frameData['x']; final int x = frameData['x'];
final int y = frameData['y']; final int y = frameData['y'];
@ -126,7 +126,7 @@ class Animation {
final stepTime = value['duration'] / 1000; final stepTime = value['duration'] / 1000;
Sprite sprite = Sprite( final Sprite sprite = Sprite(
imagePath, imagePath,
x: x.toDouble(), x: x.toDouble(),
y: y.toDouble(), y: y.toDouble(),
@ -203,7 +203,7 @@ class Animation {
/// Returns a new Animation based on this animation, but with its frames in reversed order /// Returns a new Animation based on this animation, but with its frames in reversed order
Animation reversed() { Animation reversed() {
return Animation(this.frames.reversed.toList(), loop: this.loop); return Animation(frames.reversed.toList(), loop: loop);
} }
/// Wether all sprites composing this animation are loaded. /// Wether all sprites composing this animation are loaded.

View File

@ -19,7 +19,7 @@ class AudioPool {
bool repeating; bool repeating;
int minPlayers, maxPlayers; int minPlayers, maxPlayers;
Lock _lock = Lock(); final Lock _lock = Lock();
AudioPool(this.sound, AudioPool(this.sound,
{this.repeating = false, {this.repeating = false,
@ -40,13 +40,13 @@ class AudioPool {
if (availablePlayers.isEmpty) { if (availablePlayers.isEmpty) {
availablePlayers.add(await _createNewAudioPlayer()); availablePlayers.add(await _createNewAudioPlayer());
} }
AudioPlayer player = availablePlayers.removeAt(0); final AudioPlayer player = availablePlayers.removeAt(0);
currentPlayers[player.playerId] = player; currentPlayers[player.playerId] = player;
await player.setVolume(volume); await player.setVolume(volume);
await player.resume(); await player.resume();
Stoppable stop = () { final Stoppable stop = () {
_lock.synchronized(() async { _lock.synchronized(() async {
AudioPlayer p = currentPlayers.remove(player.playerId); final AudioPlayer p = currentPlayers.remove(player.playerId);
p.completionHandler = null; p.completionHandler = null;
await p.stop(); await p.stop();
if (availablePlayers.length >= maxPlayers) { if (availablePlayers.length >= maxPlayers) {
@ -66,8 +66,8 @@ class AudioPool {
} }
Future<AudioPlayer> _createNewAudioPlayer() async { Future<AudioPlayer> _createNewAudioPlayer() async {
AudioPlayer player = AudioPlayer(); final AudioPlayer player = AudioPlayer();
String url = (await cache.load(sound)).path; final String url = (await cache.load(sound)).path;
await player.setUrl(url); await player.setUrl(url);
await player.setReleaseMode(ReleaseMode.STOP); await player.setReleaseMode(ReleaseMode.STOP);
return player; return player;

View File

@ -21,17 +21,15 @@ abstract class Box2DComponent extends Component {
Viewport viewport; Viewport viewport;
Box2DComponent({ Box2DComponent({
this.dimensions: null, this.dimensions,
int worldPoolSize: DEFAULT_WORLD_POOL_SIZE, int worldPoolSize= DEFAULT_WORLD_POOL_SIZE,
int worldPoolContainerSize: DEFAULT_WORLD_POOL_CONTAINER_SIZE, int worldPoolContainerSize= DEFAULT_WORLD_POOL_CONTAINER_SIZE,
double gravity: DEFAULT_GRAVITY, double gravity= DEFAULT_GRAVITY,
this.velocityIterations: DEFAULT_VELOCITY_ITERATIONS, this.velocityIterations= DEFAULT_VELOCITY_ITERATIONS,
this.positionIterations: DEFAULT_POSITION_ITERATIONS, this.positionIterations= DEFAULT_POSITION_ITERATIONS,
double scale: DEFAULT_SCALE, double scale= DEFAULT_SCALE,
}) { }) {
if (dimensions == null) { dimensions ??= window.physicalSize;
dimensions = window.physicalSize;
}
final pool = DefaultWorldPool(worldPoolSize, worldPoolContainerSize); final pool = DefaultWorldPool(worldPoolSize, worldPoolContainerSize);
world = World.withPool(Vector2(0.0, gravity), pool); world = World.withPool(Vector2(0.0, gravity), pool);
viewport = Viewport(dimensions, scale); viewport = Viewport(dimensions, scale);
@ -137,8 +135,8 @@ abstract class BodyComponent extends Component {
Vector2 get center => body.worldCenter; Vector2 get center => body.worldCenter;
void _renderCircle(Canvas canvas, Fixture fixture) { void _renderCircle(Canvas canvas, Fixture fixture) {
Vector2 center = Vector2.zero(); final Vector2 center = Vector2.zero();
CircleShape circle = fixture.getShape(); final CircleShape circle = fixture.getShape();
body.getWorldPointToOut(circle.p, center); body.getWorldPointToOut(circle.p, center);
viewport.getWorldToScreen(center, center); viewport.getWorldToScreen(center, center);
renderCircle( renderCircle(
@ -152,16 +150,16 @@ abstract class BodyComponent extends Component {
} }
void _renderPolygon(Canvas canvas, Fixture fixture) { void _renderPolygon(Canvas canvas, Fixture fixture) {
PolygonShape polygon = fixture.getShape(); final PolygonShape polygon = fixture.getShape();
assert(polygon.count <= MAX_POLYGON_VERTICES); assert(polygon.count <= MAX_POLYGON_VERTICES);
List<Vector2> vertices = Vec2Array().get(polygon.count); final List<Vector2> vertices = Vec2Array().get(polygon.count);
for (int i = 0; i < polygon.count; ++i) { for (int i = 0; i < polygon.count; ++i) {
body.getWorldPointToOut(polygon.vertices[i], vertices[i]); body.getWorldPointToOut(polygon.vertices[i], vertices[i]);
viewport.getWorldToScreen(vertices[i], vertices[i]); viewport.getWorldToScreen(vertices[i], vertices[i]);
} }
List<Offset> points = []; final List<Offset> points = [];
for (int i = 0; i < polygon.count; i++) { for (int i = 0; i < polygon.count; i++) {
points.add(Offset(vertices[i].x, vertices[i].y)); points.add(Offset(vertices[i].x, vertices[i].y));
} }

View File

@ -37,10 +37,10 @@ class Viewport extends ViewportTransform {
/// @param screens multiplies the visible screen with to create a bigger virtual screen. /// @param screens multiplies the visible screen with to create a bigger virtual screen.
/// @return the percentage in the range of [0, 1] /// @return the percentage in the range of [0, 1]
double getCenterHorizontalScreenPercentage({double screens: 1.0}) { double getCenterHorizontalScreenPercentage({double screens: 1.0}) {
var width = size.width * screens; final width = size.width * screens;
var x = center.x + ((screens - 1) * size.width / 2); final x = center.x + ((screens - 1) * size.width / 2);
double rest = x.abs() % width; final double rest = x.abs() % width;
double scroll = rest / width; final double scroll = rest / width;
return x > 0 ? scroll : 1 - scroll; return x > 0 ? scroll : 1 - scroll;
} }
@ -51,17 +51,17 @@ class Viewport extends ViewportTransform {
/// @param vertical percentage of the vertical viewport. Null means no vertical following. /// @param vertical percentage of the vertical viewport. Null means no vertical following.
void cameraFollow(BodyComponent component, void cameraFollow(BodyComponent component,
{double horizontal, double vertical}) { {double horizontal, double vertical}) {
Vector2 position = component.center; final Vector2 position = component.center;
double x = center.x; double x = center.x;
double y = center.y; double y = center.y;
if (horizontal != null) { if (horizontal != null) {
Vector2 temp = Vector2.zero(); final Vector2 temp = Vector2.zero();
getWorldToScreen(position, temp); getWorldToScreen(position, temp);
var margin = horizontal / 2 * size.width / 2; final margin = horizontal / 2 * size.width / 2;
var focus = size.width / 2 - temp.x; final focus = size.width / 2 - temp.x;
if (focus.abs() > margin) { if (focus.abs() > margin) {
x = size.width / 2 + x = size.width / 2 +
@ -71,11 +71,11 @@ class Viewport extends ViewportTransform {
} }
if (vertical != null) { if (vertical != null) {
Vector2 temp = Vector2.zero(); final Vector2 temp = Vector2.zero();
getWorldToScreen(position, temp); getWorldToScreen(position, temp);
var margin = vertical / 2 * size.height / 2; final margin = vertical / 2 * size.height / 2;
var focus = size.height / 2 - temp.y; final focus = size.height / 2 - temp.y;
if (focus.abs() > margin) { if (focus.abs() > margin) {
y = size.height / 2 + y = size.height / 2 +

View File

@ -96,8 +96,8 @@ abstract class PositionComponent extends Component {
canvas.translate(x, y); canvas.translate(x, y);
canvas.rotate(angle); canvas.rotate(angle);
double dx = -anchor.relativePosition.dx * width; final double dx = -anchor.relativePosition.dx * width;
double dy = -anchor.relativePosition.dy * height; final double dy = -anchor.relativePosition.dy * height;
canvas.translate(dx, dy); canvas.translate(dx, dy);
} }
} }
@ -145,7 +145,7 @@ class SvgComponent extends PositionComponent {
} }
@override @override
render(Canvas canvas) { void render(Canvas canvas) {
prepareCanvas(canvas); prepareCanvas(canvas);
svg.render(canvas, width, height); svg.render(canvas, width, height);
} }

View File

@ -60,7 +60,7 @@ mixin ComposedComponent on Component {
if (this is Resizable) { if (this is Resizable) {
// first time resize // first time resize
Resizable thisResizable = this as Resizable; final Resizable thisResizable = this as Resizable;
if (thisResizable.size != null) { if (thisResizable.size != null) {
c.resize(thisResizable.size); c.resize(thisResizable.size);
} }

View File

@ -17,18 +17,24 @@ class DebugComponent extends PositionComponent {
..style = PaintingStyle.stroke; ..style = PaintingStyle.stroke;
/// Don't do anything (change as desired) /// Don't do anything (change as desired)
@override
void update(double t) {} void update(double t) {}
/// Renders the rectangle /// Renders the rectangle
@override
void render(Canvas c) { void render(Canvas c) {
prepareCanvas(c); prepareCanvas(c);
c.drawRect(Rect.fromLTWH(0.0, 0.0, width, height), paint); c.drawRect(Rect.fromLTWH(0.0, 0.0, width, height), paint);
} }
/// Don't do anything (change as desired) /// Don't do anything (change as desired)
@override
void resize(Size size) {} void resize(Size size) {}
@override
bool loaded() => true; bool loaded() => true;
@override
bool destroy() => false; bool destroy() => false;
@override
bool isHud() => false; bool isHud() => false;
} }

View File

@ -14,7 +14,7 @@ class ParallaxRenderer {
double scroll = 0.0; double scroll = 0.0;
ParallaxRenderer(this.filename) { ParallaxRenderer(this.filename) {
this.future = _load(); future = _load();
} }
Future<Image> _load() { Future<Image> _load() {
@ -30,12 +30,12 @@ class ParallaxRenderer {
return; return;
} }
var imageHeight = image.height / window.devicePixelRatio; final imageHeight = image.height / window.devicePixelRatio;
var imageWidth = final imageWidth =
(rect.height / imageHeight) * (image.width / window.devicePixelRatio); (rect.height / imageHeight) * (image.width / window.devicePixelRatio);
var count = rect.width / imageWidth; final count = rect.width / imageWidth;
Rect fullRect = Rect.fromLTWH( final Rect fullRect = Rect.fromLTWH(
-scroll * imageWidth, rect.top, (count + 1) * imageWidth, rect.height); -scroll * imageWidth, rect.top, (count + 1) * imageWidth, rect.height);
paintImage( paintImage(
@ -51,7 +51,7 @@ abstract class ParallaxComponent extends PositionComponent {
final BASE_SPEED = 30; final BASE_SPEED = 30;
final LAYER_DELTA = 40; final LAYER_DELTA = 40;
List<ParallaxRenderer> _layers = []; final List<ParallaxRenderer> _layers = [];
Size _size; Size _size;
bool _loaded = false; bool _loaded = false;
@ -96,7 +96,7 @@ abstract class ParallaxComponent extends PositionComponent {
} }
void _drawLayers(Canvas canvas) { void _drawLayers(Canvas canvas) {
Rect rect = Rect.fromPoints( final Rect rect = Rect.fromPoints(
const Offset(0.0, 0.0), Offset(_size.width, _size.height)); const Offset(0.0, 0.0), Offset(_size.width, _size.height));
_layers.forEach((layer) => layer.render(canvas, rect)); _layers.forEach((layer) => layer.render(canvas, rect));
} }

View File

@ -16,10 +16,10 @@ class TextBoxConfig {
final double dismissDelay; final double dismissDelay;
const TextBoxConfig({ const TextBoxConfig({
this.maxWidth: 200.0, this.maxWidth= 200.0,
this.margin: 8.0, this.margin= 8.0,
this.timePerChar: 0.0, this.timePerChar= 0.0,
this.dismissDelay: 0.0, this.dismissDelay= 0.0,
}); });
} }
@ -51,11 +51,9 @@ class TextBoxComponent extends PositionComponent with Resizable {
_text = text; _text = text;
_lines = ['']; _lines = [''];
text.split(' ').forEach((word) { text.split(' ').forEach((word) {
String possibleLine = _lines.last + ' ' + word; final String possibleLine = _lines.last + ' ' + word;
widgets.TextPainter p = config.toTextPainter(possibleLine); final widgets.TextPainter p = config.toTextPainter(possibleLine);
if (_lineHeight == null) { _lineHeight ??= p.height;
_lineHeight = p.height;
}
if (p.width <= _boxConfig.maxWidth - 2 * _boxConfig.margin) { if (p.width <= _boxConfig.maxWidth - 2 * _boxConfig.margin) {
_lines.last = possibleLine; _lines.last = possibleLine;
_updateMaxWidth(p.width); _updateMaxWidth(p.width);
@ -84,7 +82,7 @@ class TextBoxComponent extends PositionComponent with Resizable {
int get currentLine { int get currentLine {
int totalCharCount = 0; int totalCharCount = 0;
int _currentChar = currentChar; final int _currentChar = currentChar;
for (int i = 0; i < _lines.length; i++) { for (int i = 0; i < _lines.length; i++) {
totalCharCount += _lines[i].length; totalCharCount += _lines[i].length;
if (totalCharCount > _currentChar) { if (totalCharCount > _currentChar) {
@ -115,10 +113,10 @@ class TextBoxComponent extends PositionComponent with Resizable {
double get currentWidth { double get currentWidth {
int i = 0; int i = 0;
int totalCharCount = 0; int totalCharCount = 0;
int _currentChar = currentChar; final int _currentChar = currentChar;
int _currentLine = currentLine; final int _currentLine = currentLine;
return _lines.sublist(0, _currentLine + 1).map((line) { return _lines.sublist(0, _currentLine + 1).map((line) {
int charCount = final int charCount =
(i < _currentLine) ? line.length : (_currentChar - totalCharCount); (i < _currentLine) ? line.length : (_currentChar - totalCharCount);
totalCharCount += line.length; totalCharCount += line.length;
i++; i++;
@ -137,8 +135,8 @@ class TextBoxComponent extends PositionComponent with Resizable {
} }
Future<Image> _redrawCache() { Future<Image> _redrawCache() {
PictureRecorder recorder = PictureRecorder(); final PictureRecorder recorder = PictureRecorder();
Canvas c = Canvas( final Canvas c = Canvas(
recorder, Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble())); recorder, Rect.fromLTWH(0.0, 0.0, width.toDouble(), height.toDouble()));
_fullRender(c); _fullRender(c);
return recorder.endRecording().toImage(width.toInt(), height.toInt()); return recorder.endRecording().toImage(width.toInt(), height.toInt());
@ -149,7 +147,7 @@ class TextBoxComponent extends PositionComponent with Resizable {
void _fullRender(Canvas c) { void _fullRender(Canvas c) {
drawBackground(c); drawBackground(c);
int _currentLine = currentLine; final int _currentLine = currentLine;
int charCount = 0; int charCount = 0;
double dy = _boxConfig.margin; double dy = _boxConfig.margin;
for (int line = 0; line < _currentLine; line++) { for (int line = 0; line < _currentLine; line++) {
@ -159,7 +157,7 @@ class TextBoxComponent extends PositionComponent with Resizable {
.paint(c, Offset(_boxConfig.margin, dy)); .paint(c, Offset(_boxConfig.margin, dy));
dy += _lineHeight; dy += _lineHeight;
} }
int max = math.min(currentChar - charCount, _lines[_currentLine].length); final int max = math.min(currentChar - charCount, _lines[_currentLine].length);
_config _config
.toTextPainter(_lines[_currentLine].substring(0, max)) .toTextPainter(_lines[_currentLine].substring(0, max))
.paint(c, Offset(_boxConfig.margin, dy)); .paint(c, Offset(_boxConfig.margin, dy));
@ -170,7 +168,7 @@ class TextBoxComponent extends PositionComponent with Resizable {
} }
void update(double dt) { void update(double dt) {
int prevCurrentChar = currentChar; final int prevCurrentChar = currentChar;
_lifeTime += dt; _lifeTime += dt;
if (prevCurrentChar != currentChar) { if (prevCurrentChar != currentChar) {
redrawLater(); redrawLater();

View File

@ -30,7 +30,7 @@ class TextComponent extends PositionComponent {
} }
void _updateBox() { void _updateBox() {
TextPainter tp = config.toTextPainter(text); final TextPainter tp = config.toTextPainter(text);
width = tp.width; width = tp.width;
height = tp.height; height = tp.height;
} }

View File

@ -29,13 +29,13 @@ class TiledComponent extends Component {
Future<TileMap> _loadMap() { Future<TileMap> _loadMap() {
return Flame.bundle.loadString('assets/tiles/' + filename).then((contents) { return Flame.bundle.loadString('assets/tiles/' + filename).then((contents) {
var parser = TileMapParser(); final parser = TileMapParser();
return parser.parse(contents); return parser.parse(contents);
}); });
} }
Future<Map<String, Image>> _loadImages(TileMap map) async { Future<Map<String, Image>> _loadImages(TileMap map) async {
Map<String, Image> result = {}; final Map<String, Image> result = {};
await Future.forEach(map.tilesets, (tileset) async { await Future.forEach(map.tilesets, (tileset) async {
await Future.forEach(tileset.images, (tmxImage) async { await Future.forEach(tileset.images, (tmxImage) async {
result[tmxImage.source] = await Flame.images.load(tmxImage.source); result[tmxImage.source] = await Flame.images.load(tmxImage.source);
@ -44,6 +44,7 @@ class TiledComponent extends Component {
return result; return result;
} }
@override
bool loaded() => _loaded; bool loaded() => _loaded;
@override @override
@ -65,12 +66,12 @@ class TiledComponent extends Component {
return; return;
} }
var image = images[tile.image.source]; final image = images[tile.image.source];
var rect = tile.computeDrawRect(); final rect = tile.computeDrawRect();
var src = Rect.fromLTWH(rect.left.toDouble(), rect.top.toDouble(), final src = Rect.fromLTWH(rect.left.toDouble(), rect.top.toDouble(),
rect.width.toDouble(), rect.height.toDouble()); rect.width.toDouble(), rect.height.toDouble());
var dst = Rect.fromLTWH(tile.x.toDouble(), tile.y.toDouble(), final dst = Rect.fromLTWH(tile.x.toDouble(), tile.y.toDouble(),
rect.width.toDouble(), rect.height.toDouble()); rect.width.toDouble(), rect.height.toDouble());
c.drawImageRect(image, src, dst, paint); c.drawImageRect(image, src, dst, paint);

View File

@ -119,7 +119,7 @@ class _GameRenderBox extends RenderBox with WidgetsBindingObserver {
} }
void _update(Duration now) { void _update(Duration now) {
double dt = _computeDeltaT(now); final double dt = _computeDeltaT(now);
game._recordDt(dt); game._recordDt(dt);
game.update(dt); game.update(dt);
} }
@ -280,12 +280,12 @@ abstract class BaseGame extends Game {
/// So it's technically updates per second, but the relation between updates and renders is 1:1. /// So it's technically updates per second, but the relation between updates and renders is 1:1.
/// Returns 0 if empty. /// Returns 0 if empty.
double fps([int average = 1]) { double fps([int average = 1]) {
List<double> dts = _dts.sublist(math.max(0, _dts.length - average)); final List<double> dts = _dts.sublist(math.max(0, _dts.length - average));
if (dts.isEmpty) { if (dts.isEmpty) {
return 0.0; return 0.0;
} }
double dtSum = dts.reduce((s, t) => s + t); final double dtSum = dts.reduce((s, t) => s + t);
double averageDt = dtSum / average; final double averageDt = dtSum / average;
return 1 / averageDt; return 1 / averageDt;
} }
@ -341,7 +341,7 @@ class _EmbeddedGameWidgetState extends State<EmbeddedGameWidget> {
} }
void _afterLayout(_) { void _afterLayout(_) {
RenderBox box = context.findRenderObject(); final RenderBox box = context.findRenderObject();
widget.game.builder.offset = box.localToGlobal(Offset.zero); widget.game.builder.offset = box.localToGlobal(Offset.zero);
} }

View File

@ -27,9 +27,9 @@ class Images {
} }
Future<Image> _fetchToMemory(String name) async { Future<Image> _fetchToMemory(String name) async {
ByteData data = await Flame.bundle.load('assets/images/' + name); final ByteData data = await Flame.bundle.load('assets/images/' + name);
Uint8List bytes = Uint8List.view(data.buffer); final Uint8List bytes = Uint8List.view(data.buffer);
Completer<Image> completer = Completer(); final Completer<Image> completer = Completer();
decodeImageFromList(bytes, (image) => completer.complete(image)); decodeImageFromList(bytes, (image) => completer.complete(image));
return completer.future; return completer.future;
} }

View File

@ -68,8 +68,8 @@ class Position {
} }
Position rotate(double angle) { Position rotate(double angle) {
double nx = math.cos(angle) * x - math.sin(angle) * y; final double nx = math.cos(angle) * x - math.sin(angle) * y;
double ny = math.sin(angle) * x + math.cos(angle) * y; final double ny = math.sin(angle) * x + math.cos(angle) * y;
x = nx; x = nx;
y = ny; y = ny;
return this; return this;
@ -109,10 +109,10 @@ class Position {
} }
static ui.Rect bounds(List<Position> pts) { static ui.Rect bounds(List<Position> pts) {
double minx = pts.map((e) => e.x).reduce(math.min); final double minx = pts.map((e) => e.x).reduce(math.min);
double maxx = pts.map((e) => e.x).reduce(math.max); final double maxx = pts.map((e) => e.x).reduce(math.max);
double miny = pts.map((e) => e.y).reduce(math.min); final double miny = pts.map((e) => e.y).reduce(math.min);
double maxy = pts.map((e) => e.y).reduce(math.max); final double maxy = pts.map((e) => e.y).reduce(math.max);
return ui.Rect.fromPoints(ui.Offset(minx, miny), ui.Offset(maxx, maxy)); return ui.Rect.fromPoints(ui.Offset(minx, miny), ui.Offset(maxx, maxy));
} }
} }

View File

@ -14,16 +14,12 @@ class Sprite {
String fileName, { String fileName, {
double x = 0.0, double x = 0.0,
double y = 0.0, double y = 0.0,
double width = null, double width,
double height = null, double height,
}) { }) {
Flame.images.load(fileName).then((img) { Flame.images.load(fileName).then((img) {
if (width == null) { width ??= img.width.toDouble();
width = img.width.toDouble(); height ??= img.height.toDouble();
}
if (height == null) {
height = img.height.toDouble();
}
image = img; image = img;
src = Rect.fromLTWH(x, y, width, height); src = Rect.fromLTWH(x, y, width, height);
}); });
@ -33,15 +29,11 @@ class Sprite {
this.image, { this.image, {
double x = 0.0, double x = 0.0,
double y = 0.0, double y = 0.0,
double width = null, double width,
double height = null, double height,
}) { }) {
if (width == null) { width ??= image.width.toDouble();
width = image.width.toDouble(); height ??= image.height.toDouble();
}
if (height == null) {
height = image.height.toDouble();
}
src = Rect.fromLTWH(x, y, width, height); src = Rect.fromLTWH(x, y, width, height);
} }
@ -49,10 +41,10 @@ class Sprite {
String fileName, { String fileName, {
double x = 0.0, double x = 0.0,
double y = 0.0, double y = 0.0,
double width = null, double width,
double height = null, double height,
}) async { }) async {
Image image = await Flame.images.load(fileName); final Image image = await Flame.images.load(fileName);
return Sprite.fromImage( return Sprite.fromImage(
image, image,
x: x, x: x,

View File

@ -10,7 +10,7 @@ class Svg {
Svg(String fileName) { Svg(String fileName) {
Flame.assets.readFile(fileName).then((svgString) async { Flame.assets.readFile(fileName).then((svgString) async {
this.svgRoot = await svg.fromSvgString(svgString, svgString); svgRoot = await svg.fromSvgString(svgString, svgString);
}); });
} }
@ -18,7 +18,7 @@ class Svg {
/// ///
/// If not loaded, does nothing /// If not loaded, does nothing
void render(Canvas canvas, double width, double height) { void render(Canvas canvas, double width, double height) {
if (!this.loaded()) { if (!loaded()) {
return; return;
} }
@ -30,7 +30,7 @@ class Svg {
/// ///
/// If not loaded, does nothing /// If not loaded, does nothing
void renderPosition(Canvas canvas, Position position, double width, double height) { void renderPosition(Canvas canvas, Position position, double width, double height) {
if (!this.loaded()) { if (!loaded()) {
return; return;
} }

View File

@ -53,11 +53,11 @@ class TextConfig {
/// ///
/// Every parameter can be specified. /// Every parameter can be specified.
const TextConfig({ const TextConfig({
this.fontSize: 24.0, this.fontSize= 24.0,
this.color: const Color(0xFF000000), this.color= const Color(0xFF000000),
this.fontFamily: 'Arial', this.fontFamily= 'Arial',
this.textAlign: TextAlign.left, this.textAlign= TextAlign.left,
this.textDirection: TextDirection.ltr, this.textDirection= TextDirection.ltr,
}); });
/// Renders a given [text] in a given position [p] using the provided [canvas] and [anchor]. /// Renders a given [text] in a given position [p] using the provided [canvas] and [anchor].
@ -70,9 +70,9 @@ class TextConfig {
/// const TextConfig config = TextConfig(fontSize: 48.0, fontFamily: 'Awesome Font', anchor: Anchor.rightBottom); /// const TextConfig config = TextConfig(fontSize: 48.0, fontFamily: 'Awesome Font', anchor: Anchor.rightBottom);
/// config.render(c, Offset(size.width - 10, size.height - 10); /// config.render(c, Offset(size.width - 10, size.height - 10);
void render(Canvas canvas, String text, Position p, void render(Canvas canvas, String text, Position p,
{Anchor anchor: Anchor.topLeft}) { {Anchor anchor= Anchor.topLeft}) {
material.TextPainter tp = toTextPainter(text); final material.TextPainter tp = toTextPainter(text);
Position translatedPosition = final Position translatedPosition =
anchor.translate(p, Position.fromSize(tp.size)); anchor.translate(p, Position.fromSize(tp.size));
tp.paint(canvas, translatedPosition.toOffset()); tp.paint(canvas, translatedPosition.toOffset());
} }
@ -90,16 +90,16 @@ class TextConfig {
/// However, you probably want to use the [render] method witch already renders for you considering the anchor. /// However, you probably want to use the [render] method witch already renders for you considering the anchor.
/// That way, you don't need to perform the math for yourself. /// That way, you don't need to perform the math for yourself.
material.TextPainter toTextPainter(String text) { material.TextPainter toTextPainter(String text) {
material.TextStyle style = material.TextStyle( final material.TextStyle style = material.TextStyle(
color: color, color: color,
fontSize: fontSize, fontSize: fontSize,
fontFamily: fontFamily, fontFamily: fontFamily,
); );
material.TextSpan span = material.TextSpan( final material.TextSpan span = material.TextSpan(
style: style, style: style,
text: text, text: text,
); );
material.TextPainter tp = material.TextPainter( final material.TextPainter tp = material.TextPainter(
text: span, text: span,
textAlign: textAlign, textAlign: textAlign,
textDirection: textDirection, textDirection: textDirection,

View File

@ -4,7 +4,7 @@ import 'package:flame/box2d/viewport.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
final viewport = Viewport(Size(100.0, 100.0), 1.0); final viewport = Viewport(const Size(100.0, 100.0), 1.0);
group('getCenterHorizontalScreenPercentage', () { group('getCenterHorizontalScreenPercentage', () {
test('center starts in the middle', () { test('center starts in the middle', () {

View File

@ -7,7 +7,7 @@ import 'package:flame/position.dart';
void main() { void main() {
group('component test', () { group('component test', () {
test('test get/set x/y or position', () { test('test get/set x/y or position', () {
PositionComponent c = SpriteComponent(); final PositionComponent c = SpriteComponent();
c.x = 2.2; c.x = 2.2;
c.y = 3.4; c.y = 3.4;
expect(c.toPosition().x, 2.2); expect(c.toPosition().x, 2.2);
@ -19,7 +19,7 @@ void main() {
}); });
test('test get/set widt/height or size', () { test('test get/set widt/height or size', () {
PositionComponent c = SpriteComponent(); final PositionComponent c = SpriteComponent();
c.width = 2.2; c.width = 2.2;
c.height = 3.4; c.height = 3.4;
expect(c.toSize().x, 2.2); expect(c.toSize().x, 2.2);
@ -31,7 +31,7 @@ void main() {
}); });
test('test get/set rect', () { test('test get/set rect', () {
PositionComponent c = SpriteComponent(); final PositionComponent c = SpriteComponent();
c.x = 0.0; c.x = 0.0;
c.y = 1.0; c.y = 1.0;
c.width = 2.0; c.width = 2.0;

View File

@ -10,7 +10,7 @@ import 'package:test/test.dart';
void main() { void main() {
test('my first widget test', () async { test('my first widget test', () async {
await Flame.init(bundle: TestAssetBundle()); await Flame.init(bundle: TestAssetBundle());
var tiled = TiledComponent('x'); final tiled = TiledComponent('x');
await tiled.future; await tiled.future;
expect(1, equals(1)); expect(1, equals(1));
}); });

View File

@ -10,16 +10,16 @@ void expectDouble(double d1, double d2) {
void main() { void main() {
group('position test', () { group('position test', () {
test('test add', () { test('test add', () {
Position p = Position(0.0, 5.0); final Position p = Position(0.0, 5.0);
Position p2 = p.add(Position(5.0, 5.0)); final Position p2 = p.add(Position(5.0, 5.0));
expect(p, p2); expect(p, p2);
expectDouble(p.x, 5.0); expectDouble(p.x, 5.0);
expectDouble(p.y, 10.0); expectDouble(p.y, 10.0);
}); });
test('test clone', () { test('test clone', () {
Position p = Position(1.0, 0.0); final Position p = Position(1.0, 0.0);
Position clone = p.clone(); final Position clone = p.clone();
clone.times(2.0); clone.times(2.0);
expectDouble(p.x, 1.0); expectDouble(p.x, 1.0);
@ -27,20 +27,20 @@ void main() {
}); });
test('test rotate', () { test('test rotate', () {
Position p = Position(1.0, 0.0).rotate(math.pi / 2); final Position p = Position(1.0, 0.0).rotate(math.pi / 2);
expectDouble(p.x, 0.0); expectDouble(p.x, 0.0);
expectDouble(p.y, 1.0); expectDouble(p.y, 1.0);
}); });
test('test length', () { test('test length', () {
Position p = Position(3.0, 4.0); final Position p = Position(3.0, 4.0);
expectDouble(p.length(), 5.0); expectDouble(p.length(), 5.0);
}); });
test('test distance', () { test('test distance', () {
Position p1 = Position(10.0, 20.0); final Position p1 = Position(10.0, 20.0);
Position p2 = Position(13.0, 24.0); final Position p2 = Position(13.0, 24.0);
double result = p1.distance(p2); final double result = p1.distance(p2);
expectDouble(result, 5.0); expectDouble(result, 5.0);
}); });
}); });

View File

@ -23,23 +23,23 @@ Size size = const Size(1.0, 1.0);
void main() { void main() {
group('resizable test', () { group('resizable test', () {
test('propagate resize to children', () { test('propagate resize to children', () {
MyComponent a = MyComponent('a'); final MyComponent a = MyComponent('a');
MyComponent b = MyComponent('b', myChildren: [a]); final MyComponent b = MyComponent('b', myChildren: [a]);
b.resize(size); b.resize(size);
expect(a.size, size); expect(a.size, size);
}); });
test('game calls resize on add', () { test('game calls resize on add', () {
MyComponent a = MyComponent('a'); final MyComponent a = MyComponent('a');
MyGame game = MyGame(); final MyGame game = MyGame();
game.resize(size); game.resize(size);
game.add(a); game.add(a);
expect(a.size, size); expect(a.size, size);
}); });
test('game calls resize after added', () { test('game calls resize after added', () {
MyComponent a = MyComponent('a'); final MyComponent a = MyComponent('a');
MyGame game = MyGame(); final MyGame game = MyGame();
game.add(a); game.add(a);
game.resize(size); game.resize(size);
expect(a.size, size); expect(a.size, size);