OOP_G3_Project/src/backend/Grid.java

106 lines
3.3 KiB
Java

package backend;
import java.util.ArrayList;
public class Grid {
// Private fields to store the grid data and dimensions
private int[][] cells;
private int width;
private int height;
//Constructor to initialize the grid with given the width and height
public Grid(int width, int height) {
this.width = width;
this.height = height;
this.cells = new int[width][height];
}
// Getter methods to retrieve the grid dimensions
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
// Getter and setter methods for individual cells
public int getCell(int x, int y) {
return cells[x][y];
}
public void setCell(int x, int y, int val) {
cells[x][y] = val;
}
//Method to change the state of a cell (0=not colored, 1=colored)
public void toggleCell(int x, int y) {
cells[x][y] = (cells[x][y] == 0) ? 1 : 0;
}
// Method to save the current state of the grid to an ArrayList of strings
public ArrayList<String> saveState() {
ArrayList<String> state = new ArrayList<>();
for (int x = 0; x < width; x++) {
StringBuilder row = new StringBuilder();
for (int y = 0; y < height; y++) {
row.append(cells[x][y]).append(";");
}
state.add(row.toString());
}
return state;
}
// Method to load the state of the grid from an ArrayList of strings
public void loadState(ArrayList<String> lines) {
for (int x = 0; x < lines.size(); x++) {
String[] values = lines.get(x).split(";");
for (int y = 0; y < values.length; y++) {
cells[x][y] = Integer.parseInt(values[y]);
}
}
}
// Method to update the cells of the grid based on game of life rules
public void updateCells(ArrayList<Integer> surviveRules, ArrayList<Integer> birthRules, boolean loopingBorder) {
int[][] newCells = new int[width][height];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int neighbors = countNeighbors(x, y, loopingBorder);
if (cells[x][y] == 1) {
newCells[x][y] = (surviveRules.contains(neighbors)) ? 1 : 0;
} else {
newCells[x][y] = (birthRules.contains(neighbors)) ? 1 : 0;
}
}
}
cells = newCells;
}
// Method to count the number of live neighbors of a cell
private int countNeighbors(int x, int y, boolean loopingBorder) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0)
continue;
int nx = x + i;
int ny = y + j;
if (loopingBorder) {
nx = (nx + width) % width;
ny = (ny + height) % height;
}
if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
count += cells[nx][ny];
}
}
}
return count;
}
}