/** * @author - Rune Vikestad */ package gameoflife3; public class GenericRule implements GameRule { private boolean[][] grid; private boolean[] surviveLogic = new boolean[] { false, false, true, true, false, false, false, false, false }; private boolean[] birthLogic = new boolean[] { false, false, false, true, false, false, false, false, false }; private int liveNeighboursNeededToSurvive; private int liveNeighboursNeededToBeBorn; /* * GenericRule() is an constructor to create new instances of a Colony */ public GenericRule() { grid = new boolean[][] { {true, true, true}, {true, false, true}, {true, true, true}, }; } /* * @param verticalAlign Vertical alignment of the neighboring cell. * @param horizontalAlign Horizontal alignment of the neighboring cell. * @param isNeighbour The new state of the neighbor. */ public void setNeighbour(int verticalAlign, int horizontalAlign, boolean isNeighbour) { if (verticalAlign != 0 && horizontalAlign != 0) { grid[1+horizontalAlign][1+verticalAlign] = isNeighbour; } } /* * @param y The column. * @param x The row. * @return If a cell can be a potential neighbour or not. */ public boolean isNeighbour(int y, int x) { // if (y+1 < grid.length && y >= 0 && x+1 < grid[0].length && x+1 >= 0) { // return grid[y+1][x+1]; // } // return false; if(x!=0 || y!=0) { if(this.grid[y+1][x+1]) { return true; } else { return false; } } else { return false; } } /* * setSurvive() is used for defining the next state of a Live cell with a specific * number of neighbours. */ public void setSurvive(int neighbours, boolean nextState) { liveNeighboursNeededToSurvive = neighbours; survived = nextState; } /* * setBirth() i used to defining the next state of a Dead cell with a specific * number of neighbours. */ public void setBirth(int neighbours, boolean nextState) { liveNeighboursNeededToBeBorn = neighbours; isBorn = nextState; } public int countNeighbours(Colony temp, int y, int x) { int neighbours = 0; for(int i = -1; i <= 1; i++) { for(int j = -1; j <= 1; j++) { if(isNeighbour(i, j) && temp.getCell(i+y, j+x)) { neighbours++; } } // End for } // End for return neighbours; } /* * nextState() returns the next state of the given cell at position y, x. * Where is y is the width, and x is the height. */ public boolean nextState(Colony currentState, int y, int x) { int n = this.countNeighbours(currentState, y, x); boolean lives = currentState.getCell(y, x); if (lives) return surviveLogic[n]; if (!lives) return birthLogic[n]; return false; } } // END CLASS GAMEOFLIFE