My board correctly identifies groups with less than 3 neighbors and kills them, but it does not seem to detect and give rise to cells with 3 neighbors.
Any thoughts?
If I have not provided sufficient information, let me know and I can insert more code, but I think that these are all relevant parts.
Thanks in advance for the advice you provided.
public boolean getCell(int row, int col) {
boolean state = board[row][col];
int neighbors = 0;
for (int x = row-1; x <= row+1; x++) {
for (int y = col-1; y <= col+1; y++) {
if ((x != row || y != col) && x != -1 && y != -1
&& x != NROWSCOLS && y != NROWSCOLS) {
if (board[x][y] == ALIVE){
neighbors ++;
}
}
}
}
if (neighbors > 3 || neighbors < 2)
state = DEAD;
else if(neighbors == 3)
state = ALIVE;
return state;
}
The life cycle method is requested here.
public void lifeCycle() {
for (int x = 0; x < NROWSCOLS ; x++) {
for (int y = 0; y < NROWSCOLS; y++) {
getCell(x,y);
}
}
generations ++;
}
I bound LifeGUI for reference, but this code is provided and not intended for me.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class LifeGUI extends JPanel {
private Life board;
private JLabel generationsLived;
private JButton resetButton, cycleButton;
private Cell[][] cells;
public LifeGUI() {
board = new Life();
cells = new Cell[Life.NROWSCOLS][Life.NROWSCOLS];
setLayout(new BorderLayout());
JPanel boardPanel = new JPanel();
boardPanel.setLayout(new GridLayout(Life.NROWSCOLS, Life.NROWSCOLS));
for (int row = 0; row < Life.NROWSCOLS; row++) {
for (int col = 0; col < Life.NROWSCOLS; col++) {
cells[row][col] = new Cell(Life.DEAD, row, col);
boardPanel.add(cells[row][col]);
}
}
add(boardPanel, BorderLayout.CENTER);
resetButton = new JButton("New Game");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
board.newGame();
updateDisplay();
}
});
cycleButton = new JButton("Live One Cycle");
cycleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
board.lifeCycle();
updateDisplay();
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(resetButton);
buttonPanel.add(cycleButton);
generationsLived = new JLabel(" Generations Lived: " , JLabel.RIGHT);
buttonPanel.add(generationsLived);
add(buttonPanel, BorderLayout.SOUTH);
updateDisplay();
}
public void updateDisplay() {
generationsLived.setText(" Generations Lived: " + board.getGenerationCount());
for (int row = 0; row < Life.NROWSCOLS; row++) {
for (int col = 0; col < Life.NROWSCOLS; col++) {
cells[row][col].setState(board.getCell(row,col));
}
}
repaint();
}
private static void test() {
JFrame f = new JFrame("The Game of Life");
LifeGUI l = new LifeGUI();
f.getContentPane().add(l);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600,600);
f.validate();
f.setVisible(true);
f.toFront();
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
LifeGUI.test();
}
});
}
}
source
share