package inf101.v18.connectfour.board; /** * An implementation of IGrid * * @param Can be anything */ public class Grid implements IGrid { private final T[][] grid; private final int width; private final int height; private final T empty; /** * Creates a new grid. * * @param width The width of the new grid * @param height The height of the new grid * @param object The default object for all cells */@SuppressWarnings("unchecked") public Grid(int width, int height, T object) { if (!(width > 0 && height > 0)) { throw new IllegalArgumentException("Negative or zero height and/or width."); } if (object == null) { throw new IllegalArgumentException("Grid can't be initialized with null"); } T[][] list = (T[][])new Object[width][height]; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { list[i][j] = object; } } grid = list; this.empty = object; this.width = width; this.height = height; } @Override public void flush() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { grid[i][j] = empty; } } } @Override public boolean isFull() { for (T[] list : grid) { for (T item : list) { if (this.empty.getClass().isInstance(item)) { return false; } } } return true; } @Override public int getHeight() { return height; } @Override public int getWidth() { return width; } @Override public void set(int x, int y, T element) { if (x >= width || y >= height || x < 0 || y < 0) { throw new IllegalArgumentException("Index out of bounds."); } if (element == null) { throw new IllegalArgumentException("This grid does not accept null."); } grid[x][y] = element; } @Override public T get(int x, int y) { if (y >= height || x >= width || x < 0 || y < 0) { throw new IllegalArgumentException("Index out of bound."); } return grid[x][y]; } @Override public IGrid copy() { Grid newGrid = new Grid<>(width, height, empty); for (int i = 0; i < width; i++) { System.arraycopy(grid[i], 0, newGrid.grid[i], 0, height); } return newGrid; } }