Для школьного проекта я должен завершить жизненную игру Конвейса, используя некоторый предоставленный скелетный код.
Моя проблема в том, что все мои ячейки, кажется, инициализируются как мертвые (и, следовательно, не оживают), когда я использую визуализатор - я не ищу прямого ответа по всему проекту, а просто какое-то направление того, где мой код сломан ( Прошу прощения за ужасное форматирование, я впервые здесь):
Ниже Cell.class
и ниже CellGrid
- визуализатор был предоставлен.
package simulation;
/**
* This class represents a single Cell in the grid.
*
* Complete this class as part of the core of the assessment.
* You must implement the constructor, isAlive, setAlive and isAliveNextStep.
*/
public class Cell
{
// true if the cell is alive and false if it is dead
private boolean alive;
/**
* Cell constructor - all cells should start out dead
*/
public Cell()
{
alive = false;
}
/**
* Accessor method for alive
*
* @return true if the cell is currently alive; false otherwise
*/
public boolean isAlive()
{
if (alive == true)
{
return true;
}
else
return false;
}
/**
* Mutator method for alive
*
* @param alive - the new state of the cell
*/
public void setAlive(boolean alive)
{
if (alive == true)
alive = false;
else alive = true;
}
/**
* Determine whether this cell should be alive in the next step,
* given the number of surrounding neighbours.
*
* See the assignment specification sheet to determine the rules
* for living and dead cells.
*
* @param numNeighbours - the number of living cells surrounding this cell
* @return true if the cell should be alive; false otherwise
*/
public boolean isAliveNextStep(int numNeighbours)
{
if (numNeighbours <= 2)
return false;
if (numNeighbours == 3)
return true;
if (numNeighbours == 4 && alive == true)
return true;
if (numNeighbours == 5)
return false;
if (numNeighbours > 5)
return true;
else return false;
}
}
CellGrid класс:
package simulation;
/**
* This class represents an n x n grid of Cells.
*
* Complete this class as part of the core of the assessment.
* You must implement the constructor, simulateStep, isValidCoordinate,
* countNeighbours, getCell and setCell.
*/
public class CellGrid
{
// Store the cells of the game in this 2D array
private Cell[][] cells;
/**
* Constructor for a CellGrid. Populates the grid with cells that will be
* either living or dead. Consider using Math.random() in order to generate
* random numbers between 0.0 and 1.0, in conjunction with lifeChance.
*
* @param size - the size of the grid will be size x size
* @param lifeChance - the probability of each cell starting out
* alive (0.0 = 0%, 1.0 = 100%)
*/
public CellGrid(int size, double lifeChance)
{
cells = new Cell[size][size];
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cells[i][j] = new Cell();
if (Math.random() < lifeChance);
{
cells[i][j].setAlive(false);
}
}
}
}
/**
* Run one step in the simulation. This has 2 stages in the following order:
*
* 1. (Core) Update all cells in the grid according to the rules given in the
* assignment specification sheet.
*
* 2. (Extension) Evolve the cells by calculating their new genes - also
* see the assignment specification sheet.
*/
public void simulateStep()
{
for (int i = 0; i < cells.length; i++)
{
for (int j = 0; j < cells.length; j++)
{
int Neighbours = countNeighbours(i, j);
cells[i][j].isAliveNextStep(Neighbours);
}
}
}
/**
* Check if the given coordinates are inside the grid of cells.
*
* @param x - the x coordinate (column) of the cell
* @param y - the y coordinate (row) of the cell
* @return true if the given coordinates are inside the grid of cells; false
* otherwise.
*/
public boolean isValidCoordinate(int x, int y)
{
int validc = 0; //*variable to check for validity of coordinate by traversal *//
for (int i = 0; i < cells.length; i++)
{
for (int j = 0; j > cells.length; j++)
{
if (x == i+1 && y == j+1)
{
validc = 1;
}
}
}
if (validc == 1)
{
return true;
}
else return false;
}
/**
* Count the number of living neighbours in the 8 cells surrounding the
* given coordinates.
*
* @param x - the x coordinate (column) of the cell
* @param y - the y coordinate (row) of the cell
* @return the number of living neighbours of the cell at the given
* coordinates; or 0 if the coordinates are invalid.
*/
public int countNeighbours(int x, int y)
{
int N = 0;
for (int i = 0; i < cells.length; i++)
{
for (int j = 0; j > cells.length; j++)
{
if (i-1 >= 0 && j-1 >= 0 && cells[i-1][j-1].equals(true))
N++;
if (i-1 >= 0 && cells[i-1][j].equals(true))
N++;
if (i-1 >= 0 && j+1 <= cells.length && cells[i-1][j+1].equals(true))
N++;
if (i >= 0 && j-1 >=0 && cells[i][j-1].equals(true))
N++;
if (i >= 0 && j >= 0 && cells[i][j].equals(true))
N++;
if (i >= 0 && j+1 <= cells.length && cells[i][j+1].equals(true))
N++;
if (i+1 <= cells.length && j-1 >= 0 && cells[i+1][j-1].equals(true))
N++;
if (i+1 <= cells.length && j >= 0 && cells[i+1][j].equals(true))
N++;
if (i+1 <= cells.length && j+1 <= cells.length && cells[i+1][j+1].equals(true))
N++;
}
}
return N;
}
/**
* Get the cell at the given coordinates.
*
* @param x - the x coordinate (column) of the cell
* @param y - the y coordinate (row) of the cell
* @return the cell at the given coordinates; or null if the coordinates are
* invalid
*/
public Cell getCell(int x, int y)
{
if (x < cells.length && y < cells.length)
return cells[x][y];
else return null;
}
/**
* Set the cell at the given coordinates to the cell provided, if the
* coordinates are valid.
*
* @param x - the x coordinate (column) of the cell
* @param y - the y coordinate (row) of the cell
* @param cell - the new cell to put at the coordinates given.
*/
public void setCell(int x, int y, Cell cell)
{
cells[x][y] = getCell(x,y);
}
}
setAlive
методе, где вы меняете не свойство класса, а параметр, полученный методом. Чтобы упростить ваш метод, я бы использовалthis.alive = !alive
. - person AndrewMcCoist   schedule 15.10.2015isAlive()
методом. Он должен просто вернуться живым, вот и все. Но да, у @AndrewMcCoist твоя проблема. Пожалуйста, изучите геттеры и сеттеры - базовая Java. Вы слишком усложняете это до смерти, это ваша главная проблема. Не забудьте ПОЦЕЛУЙ. - person Hovercraft Full Of Eels   schedule 15.10.2015Cell.isAlive()
можно значительно упростить. Просто вернитеalive
вместо использования этого предложенияif-else
. Результат будет таким же. - person Paul   schedule 15.10.2015