84 lines
2.2 KiB
Java
Raw Normal View History

2020-02-20 13:35:40 +01:00
package inf112.fiasko.roborally.objects;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents a grid which can store anything
* @param <K> The type of element the grid should store
*/
2020-02-20 13:35:40 +01:00
public class Grid<K> implements IGrid<K> {
private final int height;
private final int width;
private final List<ArrayList<K>> grid = new ArrayList<>();
2020-02-20 13:35:40 +01:00
/**
* Initializes an empty grid
* @param width The width of the grid
* @param height The height of the grid
2020-02-20 13:35:40 +01:00
*/
public Grid(int width, int height) {
2020-02-20 13:35:40 +01:00
this.width = width;
this.height = height;
for (int y = 0; y < height; y++) {
2020-02-20 13:35:40 +01:00
ArrayList<K> row = new ArrayList<>();
for(int x = 0; x < width; x++) {
row.add(null);
}
this.grid.add(row);
}
}
/**
* Initializes a grid filled with standard tiles.
* @param height sets the height of the grid
* @param width sets the width of the grid
* @param tile gives the TileType the grid is to be filled with
*/
public Grid(int width, int height, K tile) {
2020-02-20 13:35:40 +01:00
this.width = width;
this.height = height;
for (int y = 0; y < height; y++) {
2020-02-20 13:35:40 +01:00
ArrayList<K> row = new ArrayList<>();
for(int x = 0; x < width; x++) {
row.add(tile);
}
this.grid.add(row);
}
}
@Override
public int getWidth() {
return width;
}
@Override
public int getHeight() {
return height;
}
@Override
public K getElement(int x, int y) throws IllegalArgumentException {
makeSureCoordinatesAreWithinBounds(x, y);
return grid.get(y).get(x);
2020-02-20 13:35:40 +01:00
}
@Override
public void setElement(int x, int y, K element) throws IllegalArgumentException {
makeSureCoordinatesAreWithinBounds(x, y);
grid.get(y).set(x, element);
}
/**
* Throws an exception if input coordinates are out of bounds
* @param x The x coordinate to check
* @param y The y coordinate to check
*/
private void makeSureCoordinatesAreWithinBounds(int x, int y) {
if (x < 0 || x >= width || y < 0 || y >= height) {
throw new IllegalArgumentException();
2020-02-20 13:35:40 +01:00
}
}
}