Add toIndex method

can be used to get the correct index from coordinates passed in. Will only calculate the index, not take into consideration any grid size constraints etc.
This commit is contained in:
Marty Oehme 2018-08-30 09:41:43 +02:00
parent 8865af4878
commit 3f939601b3
2 changed files with 29 additions and 16 deletions

View file

@ -37,7 +37,14 @@ class Grid<E> extends DelegatingList<E> {
void set(int x, int y, E value) => setElement(x, y, value);
int toIndex(int x, int y) => y * width + x;
/// Calculate list index from coordinates.
///
/// Can be used to get the correct index from coordinates passed in.
/// Will only calculate the index, not take into consideration any grid size
/// constraints etc; use [get] for that (generally recommended).
int toIndex(int x, int y) => (x < 0 || y < 0)
? throw RangeError("Coordinates for Grid Indexing must not be negative.")
: y * width + x;
Point<int> toCoords(int index) => Point<int>(index % width, index ~/ width);
}

View file

@ -3,7 +3,6 @@ import 'package:test/test.dart';
@Tags(const ["nobrowser"])
void main() {
Grid sut;
group("Instantiation", () {
List<String> l;
setUp(() {
@ -69,23 +68,30 @@ void main() {
expect(sut.width, 3);
}, tags: const ["happy"]);
});
group("getter", () {
group("toIndex", () {
Grid sut;
setUp(() {
sut = Grid(3, 3);
sut.setAll(0, [
"Hey",
"you",
"me",
"together",
"Hello",
"World",
"I",
"am",
"ready."
]);
});
test("Engine can be instantiated without canvas", () {
expect(sut, isNot(throwsNoSuchMethodError));
test("throws RangeError on negative x argument", () {
expect(() => sut.toIndex(-1, 2), throwsA(isRangeError));
}, tags: const ["bad"]);
test("throws RangeError on negative y argument", () {
expect(() => sut.toIndex(2, -1), throwsA(isRangeError));
}, tags: const ["bad"]);
test("calculates correct index for first element", () {
expect(sut.toIndex(0, 0), equals(0));
}, tags: const ["happy"]);
test("calculates correct index for last element", () {
expect(sut.toIndex(2, 2), equals(8));
}, tags: const ["happy"]);
test("calculates correct index for element on first row", () {
expect(sut.toIndex(2, 0), equals(2));
}, tags: const ["happy"]);
test("calculates correct index for example element", () {
expect(sut.toIndex(1, 1), equals(4));
}, tags: const ["happy"]);
});
});
});
}