Add .toCoordinates() method to grid

Calculates the 2-D array coordinates from the corresponding list index passed in. Relies on grid width to calculate coordinates. Does not check against grid size constraints.
This commit is contained in:
Marty Oehme 2018-08-30 09:52:00 +02:00
parent 6c3fcbe7b0
commit 5a72783d57
2 changed files with 32 additions and 2 deletions

View file

@ -35,7 +35,7 @@ class Grid<E> extends DelegatingList<E> {
void set(int x, int y, E value) => setElement(x, y, value);
/// Calculate list index from coordinates.
/// 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
@ -44,5 +44,12 @@ class Grid<E> extends DelegatingList<E> {
? throw RangeError("Coordinates for Grid Indexing must not be negative.")
: y * width + x;
Point<int> toCoords(int index) => Point<int>(index % width, index ~/ width);
/// Calculate coordinates from list index
///
/// Calculates the 2-D array coordinates from the corresponding list index
/// passed in. Relies on grid width to calculate coordinates. Does not check
/// against grid size constraints; use [set] for that (generally recommended).
Point<int> toCoordinates(int index) => (index < 0)
? throw RangeError("Index for Grid Coordinates must not be negative")
: Point<int>(index % width, index ~/ width);
}