Please help me implementing Conway\'s Game of Life for this assignment. The Wiki
ID: 3818671 • Letter: P
Question
Please help me implementing Conway's Game of Life for this assignment. The Wikipedia article on the Game of Life can be found https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life and a demo of the game can be found https://bitstorm.org/gameoflife/. Use the netbeans and make sure it follows the instructions and skeleton below, make sure it is working correctly. The code should write by JAVA and working on netbeans. Please do not use any other language. Follow the instructions and fill in the skeleton below carefully. Use the skeleton below only.
Here is the instructions:
The game of life takes place on a two dimensional board (a 2D array in Java terms). Each square on the board (element in the array) is cell, either dead or alive.
The game progresses in steps. Each step, each cell determines whether it will die or spring to life. It does counting the number of live neighbors it has. Neighbors are the up to 8 adjacent cells, including diagonals. The board does not wrap around, so cells in the corners and sides have fewer than 8 neighbors.1 After counting their living neighbors, if a live cell has < 2 living neighbors, it dies of loneliness. If a live cell has > 3 living neighbors, it dies of overpopulation. If the live cell has 2 or 3 neighbors, it lives on, content. If a dead cell has exactly 3 neighbors, it springs back to life. Each of these status changes happen each step, so if a live cell has 5 neighbors on step n, then its status changes to dead for step n + 1.
Using these simple rules, we can create complex and beautiful patterns.
Implementing the Game of Life
There is a skeleton provided to make things easier. To make our job
easier, we are doing a completely text based version of the game of life. We will
represent our board as a 2D array. We also have a second 2D array of the same
size as a uer," essentially a workspace to create the next step of the game,
as we'll explain in a bit.
Use the character `X' to represent a live cell and any other character of your
choice to represent a dead one (I use the carat character).
Let's look at the constructor and each of the functions in turn.
1 The Constructor
In the constructor, build a new board of your desired size, and initialize your
initial board state. Also initialize the nextBoard variable to be an empty board
of the same size.
2 getNeighborCount
This method takes in the row and column location of a cell and returns the
number of living neighbors. This will most likely be your most challenging
method and I recommend writing and testing this method rst. Let me
be perfectly clear.
Write and test this method before trying to write the whole program at once.
If you try to write the whole program in one go, your program will crash and
you won't be able to gure out why.
The challenge of this function is that each of the 8 neighboring cells you
need to check could be out of bounds.
3 generateNextStep
This method generates the next step of the board. For each cell in the board,
get the number of neighbors and the status of the cell you are currently at.
Use this information to gure out whether the cell will be alive or dead in the
next iteration of the board. Set the cell at the same row, column location
in nextBoard to this status. To reiterate, you want to change the cells in
nextBoard, not your current board, because if you changed the cells in board,
you would lose your current board state.
Once that is done, make set board equal to nextBoard to advance to the
next step and create a new 2D for nextBoard.
4 printBoard
This one is obvious. Print out the board.
2
5 main
Use main to create a GameOfLifeBoard, and then create a while loop. In the
while loop do the following
Print out the board by calling printBoard()
wait for user input
if the user puts in quit, stop the game.
Otherwise, call generateNextStep() and keep the loop going.
6 Testing
To demo your code, create a glider and watch it go across the board.
Below is the given skeleton. Make sure the codes follows this skelon properly. please do not use other skeleton and make sure the code working on netbean 8.2.
import java.util.Scanner;
public class GameOfLifeBoard {
private char[][] board;
private char[][] nextBoard;
public static final char LIVE = 'X';
public static final char DEAD = '^';
public GameOfLifeBoard(){
}
public void generateNextStep(){
}
public int getNeighborCount(int row, int col){
int numNeighbors = 0;
return numNeighbors;
}
public void printBoard(){
}
public static void main(String[] args){
}
}
Explanation / Answer
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Life extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
/**
* Main program opens a window whose content pane is a JPanel belonging to class Life.
*/
public static void main(String[] args) {
JFrame f = new JFrame("Life");
JPanel p = new Life();
f.setContentPane(p);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocation(100,50);
f.setVisible(true);
}
private final int GRID_SIZE = 100; // Number of squares along each side of the board
// (Should probably not be less than 10 or more than 200,)
private boolean[][] alive; // Represents the board. alive[r][c] is true if the cell in row r, column c is alive.
private MosaicPanel display; // Displays the game to the user.. White squares are alive; black squares are dead.
private Timer timer; // Drives the game when the user presses the "Start" button.
private JButton stopGoButton; // Button for starting and stopping the running of the game.
private JButton nextButton; // Button for computing just the next generation.
private JButton randomButton; // Button for filling the board randomly with each cell having a 25% chance of being alive.
private JButton clearButton; // Button for clearing the board, that is setting all the cells to "dead".
private JButton quitButton; // Button for ending the program.
/**
* Create a life game board, initially empty. The number of cells on each side of the grid is GRID_SIZE.
*/
public Life() {
alive = new boolean[GRID_SIZE][GRID_SIZE];
setLayout(new BorderLayout(3,3));
setBackground(Color.GRAY);
setBorder(BorderFactory.createLineBorder(Color.GRAY,3));
int cellSize = 600/GRID_SIZE; // Aim for about a 600-by-600 pixel board.
display = new MosaicPanel(GRID_SIZE,GRID_SIZE,cellSize,cellSize);
if (cellSize < 5)
display.setGroutingColor(null);
display.setUse3D(false);
add(display,BorderLayout.CENTER);
JPanel bottom = new JPanel();
add(bottom,BorderLayout.SOUTH);
clearButton = new JButton("Clear");
stopGoButton = new JButton("Start");
quitButton = new JButton("Quit");
nextButton = new JButton("One Step");
randomButton = new JButton("Random Fill");
bottom.add(stopGoButton);
bottom.add(nextButton);
bottom.add(randomButton);
bottom.add(clearButton);
bottom.add(quitButton);
stopGoButton.addActionListener(this);
clearButton.addActionListener(this);
quitButton.addActionListener(this);
randomButton.addActionListener(this);
nextButton.addActionListener(this);
display.addMouseListener(this);
display.addMouseMotionListener(this);
timer = new Timer(50,this);
}
/**
* Compute the next generation of cells. The "alive" array is modified to reflect the
* state of each cell in the new generation. (Note that this method does not actually
* draw the new board; it only sets the values in the "alive" array. The board is
* redrawn in the showBoard() method.)
*/
private void doFrame() { // Compute the new state of the Life board.
boolean[][] newboard = new boolean[GRID_SIZE][GRID_SIZE];
for ( int r = 0; r < GRID_SIZE; r++ ) {
int above, below; // rows considered above and below row number r
int left, right; // columns considered left and right of column c
above = r > 0 ? r-1 : GRID_SIZE-1;
below = r < GRID_SIZE-1 ? r+1 : 0;
for ( int c = 0; c < GRID_SIZE; c++ ) {
left = c > 0 ? c-1 : GRID_SIZE-1;
right = c < GRID_SIZE-1 ? c+1 : 0;
int n = 0; // number of alive cells in the 8 neighboring cells
if (alive[above][left])
n++;
if (alive[above][c])
n++;
if (alive[above][right])
n++;
if (alive[r][left])
n++;
if (alive[r][right])
n++;
if (alive[below][left])
n++;
if (alive[below][c])
n++;
if (alive[below][right])
n++;
if (n == 3 || (alive[r][c] && n == 2))
newboard[r][c] = true;
else
newboard[r][c] = false;
}
}
alive = newboard;
}
/**
* Sets the color of every square in the display to show whether the corresponding
* cell on the Life board is alive or dead.
*/
private void showBoard() {
display.setAutopaint(false); // For efficiency, prevent redrawing of individual squares.
for (int r = 0; r < GRID_SIZE; r++) {
for (int c = 0; c < GRID_SIZE; c++) {
if (alive[r][c])
display.setColor(r,c,Color.WHITE);
else
display.setColor(r,c,null); // Shows the background color, black.
}
}
display.setAutopaint(true); // Redraw the whole board, and turn on drawing of individual squares.
}
/**
* Respond to an ActionEvent from one of the control buttons or from the timer.
*/
public void actionPerformed(ActionEvent e) {
Object src = e.getSource(); // The object that caused the event.
if (src == quitButton) { // End the program.
System.exit(0);
}
else if (src == clearButton) { // Clear the board.
alive = new boolean[GRID_SIZE][GRID_SIZE];
display.clear();
}
else if (src == nextButton) { // Compute and display the next generation.
doFrame();
showBoard();
}
else if (src == stopGoButton) { // Start or stop the game, depending on whether or not it is currenty running.
if (timer.isRunning()) { // If the game is currently running, stop it.
timer.stop(); // This stops the game by turning off the timer that drives the game.
clearButton.setEnabled(true); // Some buttons are disabled while the game is running.
randomButton.setEnabled(true);
nextButton.setEnabled(true);
stopGoButton.setText("Start"); // Change text of button to "Start", since it can be used to start the game again.
}
else { // If the game is not currently running, start it.
timer.start(); // This starts the game by turning the timee that will drive the game.
clearButton.setEnabled(false); // Buttons that modify the board are disabled while the game is running.
randomButton.setEnabled(false);
nextButton.setEnabled(false);
stopGoButton.setText("Stop"); // Change text of button to "Stop", since it can be used to stop the game.
}
}
else if (src == randomButton) { // Fill the board randomly.
for (int r = 0; r < GRID_SIZE; r++) {
for (int c = 0; c < GRID_SIZE; c++)
alive[r][c] = (Math.random() < 0.25); // 25% probability that the cell is alive.
}
showBoard();
}
else if (src == timer) { // Each time the timer fires, a new frame is computed and displayed.
doFrame();
showBoard();
}
}
/**
* The square containing the mouse comes to life or, if the right-mouse button is down, dies.
*/
public void mousePressed(MouseEvent e) {
if (timer.isRunning())
return;
int row = display.yCoordToRowNumber(e.getY());
int col = display.yCoordToRowNumber(e.getX());
if (row >= 0 && row < display.getRowCount() && col >= 0 && col < display.getColumnCount()) {
if (e.isMetaDown() || e.isControlDown()) {
display.setColor(row,col,null);
alive[row][col] = false;
}
else {
display.setColor(row,col,Color.WHITE);
alive[row][col] = true;
}
}
}
/**
* The square containing the mouse comes to life or, if the right-mouse button is down, dies.
*/
public void mouseDragged(MouseEvent e) {
mousePressed(e); // Dragging the mouse into a square has the same effect as clicking in that square.
}
public void mouseClicked(MouseEvent e) { } // Other methods required by the MouseListener and MouseMotionListener interfaces.
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseMoved(MouseEvent e) { }
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.