Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

You will write a Java program that implements Conway’s Game of Life, a simple ce

ID: 3767422 • Letter: Y

Question

You will write a Java program that implements Conway’s Game of Life, a simple cellular automaton.

Our simplified version has a 10 x 10 grid, numbered like this:

0 1 2 3 4 5 6 7 8 9

        0

        1

        2

        3

        4

        5

        6

        7

        8

        9

The grid is represented by a 10 x 10 2-dimensional integer array. If the grid point (i, j) is “populated”, the array element [i][j] contains 1; otherwise it contains 0. Elements along the edges, i == 0 or 9, or j == 0 or 9, are always unpopulated.

When we display the grid, a populated cell is indicated by a ‘#’; an unpopulated cell is indicated by a space.

What your program should do:

            Prompt the user to enter a list of (i,j) pairs (both non-negative integers)

                        (stop when a negative integer is read for either i or j)

            Prompt the user to enter the number of time steps

            Initialize the grid based on the (i,j) pairs entered by the user

            Display the initial state of the grid

                        (call the displayGrid() method)

            For each time step,

update the grid according to Conway’s rules (call the updateGrid() method)

display the grid (call the displayGrid() method)

We follow Conway’s standard rules for updating the cells.

For a cell that is “populated”, if the cell has <= 1 neighbors, or > = 4 neighbors, it dies (becomes 0). Otherwise, it survives (remains 1).

For a cell that is not populated, if the cell has exactly 3 neighbors, it becomes populated (becomes 1).

Cells on the edge always remain unpopulated (0).

Some sample runs are shown in text files on libra in ~whsu/csc210/P8/.

The displayGrid() method has prototype:

     void displayGrid(int mat[][]);

It displays the borders of the grid (see sample runs below), and prints the 10 x 10 grid of cells. Populated cells are indicated with a ‘#’ sign, unpopulated cells with a space.

The updateGrid() method has prototype:

     void updateGrid(int mat[][]);

mat is the 2-dimensional array that contains the current state of the grid. The method counts the neighbors in each cell of the grid, updates the cells in the grid according to Conway’s rules, and returns the grid.

Sample runs:

libra% java Life

Please enter list of (i,j) pairs for populated cells

(negative i or j to quit): 6 4 6 5 6 6 6 7 6 8 -1 -1

Enter number of time steps: 5

Initial grid:

0123456789

          0

          1

          2

          3

          4

          5

    ##### 6

          7

          8

          9

Time step 1

0123456789

          0

          1

          2

          3

          4

     ### 5

     ### 6

     ### 7

          8

          9

Time step 2

0123456789

          0

          1

          2

          3

      #   4

     # # 5

    #   # 6

     # # 7

      #   8

          9

Time step 3

0123456789

          0

          1

          2

          3

      #   4

     ### 5

    ## ## 6

     ### 7

      #   8

          9

Time step 4

0123456789

          0

          1

          2

          3

     ### 4

    #   # 5

    #   # 6

    #   # 7

     ### 8

          9

Time step 5

0123456789

          0

          1

          2

      #   3

     ### 4

    # # # 5

   ### ## 6

    # # # 7

     ### 8

          9

libra% java Life

Please enter list of (i,j) pairs for populated cells

(negative i or j to quit): 4 5

4 6

5 4

5 5

5 7

6 5

6 6

-1 -1

Enter number of time steps: 5

Initial grid:

0123456789

         0

          1

          2

          3

     ##   4

    ## # 5

     ##   6

          7

          8

          9

Time step 1

0123456789

          0

          1

          2

          3

    ###   4

    # # 5

    ###   6

          7

          8

          9

Time step 2

0123456789

          0

          1

          2

     #    3

    ###   4

   #   # 5

    ###   6

     #    7

          8

          9

Time step 3

0123456789

          0

          1

          2

    ###   3

    ###   4

   #   # 5

    ###   6

    ###   7

          8

          9

Time step 4

0123456789

          0

          1

     #    2

    # #   3

   #   # 4

   #   # 5

   #   # 6

    # #   7

     #    8

          9

Time step 5

0123456789

          0

          1

     #    2

    ###   3

   ## ## 4

### ### 5

   ## ## 6

    ###   7

     #    8

          9

Explanation / Answer

import java.awt.*;
import java.awt.event.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import javax.swing.*;


public class ConwaysGame extends JFrame implements ActionListener
{
private static final Dimension DEFAULT_WINDOW_SIZE = new Dimension(600, 400);
private static final Dimension MINIMUM_WINDOW_SIZE = new Dimension(200, 200);
private static final int BLOCK_SIZE = 10;

private JMenuBar mb_menu;
private JMenu m_file, m_game, m_help;
private JMenuItem mi_file_options, mi_file_exit;
private JMenuItem mi_game_autofill, mi_game_play, mi_game_stop, mi_game_reset;
private JMenuItem mi_help_about, mi_help_source;
private int i_movesPerSecond = 3;
private GameBoard gb_gameBoard;
private Thread game;

public static void main(String[] args)
{

JFrame game = new ConwaysGame ();
game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.setTitle("Conway's Game of Life");
game.setIconImage(new ImageIcon(ConwaysGame .class.getResource("/images/logo.png")).getImage());
game.setSize(DEFAULT_WINDOW_SIZE);
game.setMinimumSize(MINIMUM_WINDOW_SIZE);
game.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - game.getWidth())/2,
(Toolkit.getDefaultToolkit().getScreenSize().height - game.getHeight())/2);
game.setVisible(true);
}

public ConwaysGame()
{

mb_menu = new JMenuBar();
setJMenuBar(mb_menu);
m_file = new JMenu("File");
mb_menu.add(m_file);
m_game = new JMenu("Game");
mb_menu.add(m_game);
m_help = new JMenu("Help");
mb_menu.add(m_help);
mi_file_options = new JMenuItem("Options");
mi_file_options.addActionListener(this);
mi_file_exit = new JMenuItem("Exit");
mi_file_exit.addActionListener(this);
m_file.add(mi_file_options);
m_file.add(new JSeparator());
m_file.add(mi_file_exit);
mi_game_autofill = new JMenuItem("Autofill");
mi_game_autofill.addActionListener(this);
mi_game_play = new JMenuItem("Play");
mi_game_play.addActionListener(this);
mi_game_stop = new JMenuItem("Stop");
mi_game_stop.setEnabled(false);
mi_game_stop.addActionListener(this);
mi_game_reset = new JMenuItem("Reset");
mi_game_reset.addActionListener(this);
m_game.add(mi_game_autofill);
m_game.add(new JSeparator());
m_game.add(mi_game_play);
m_game.add(mi_game_stop);
m_game.add(mi_game_reset);
mi_help_about = new JMenuItem("About");
mi_help_about.addActionListener(this);
mi_help_source = new JMenuItem("Source");
mi_help_source.addActionListener(this);
m_help.add(mi_help_about);
m_help.add(mi_help_source);
// Setup game board
gb_gameBoard = new GameBoard();
add(gb_gameBoard);
}

public void setGameBeingPlayed(boolean isBeingPlayed) {
if (isBeingPlayed) {
mi_game_play.setEnabled(false);
mi_game_stop.setEnabled(true);
game = new Thread(gb_gameBoard);
game.start();
} else {
mi_game_play.setEnabled(true);
mi_game_stop.setEnabled(false);
game.interrupt();
}
}


public void actionPerformed(ActionEvent ae) {
if (ae.getSource().equals(mi_file_exit)) {

System.exit(0);
} else if (ae.getSource().equals(mi_file_options)) {

final JFrame f_options = new JFrame();
f_options.setTitle("Options");
f_options.setSize(300,60);
f_options.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - f_options.getWidth())/2,
(Toolkit.getDefaultToolkit().getScreenSize().height - f_options.getHeight())/2);
f_options.setResizable(false);
JPanel p_options = new JPanel();
p_options.setOpaque(false);
f_options.add(p_options);
p_options.add(new JLabel("Number of moves per second:"));
Integer[] secondOptions = {1,2,3,4,5,10,15,20};
final JComboBox cb_seconds = new JComboBox(secondOptions);
p_options.add(cb_seconds);
cb_seconds.setSelectedItem(i_movesPerSecond);
cb_seconds.addActionListener(new ActionListener()
{

public void actionPerformed(ActionEvent ae)
{
i_movesPerSecond = (Integer)cb_seconds.getSelectedItem();
f_options.dispose();
}
});
f_options.setVisible(true);
}
else if (ae.getSource().equals(mi_game_autofill))
{
final JFrame f_autoFill = new JFrame();
f_autoFill.setTitle("Autofill");
f_autoFill.setSize(360, 60);
f_autoFill.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - f_autoFill.getWidth())/2,
(Toolkit.getDefaultToolkit().getScreenSize().height - f_autoFill.getHeight())/2);
f_autoFill.setResizable(false);
JPanel p_autoFill = new JPanel();
p_autoFill.setOpaque(false);
f_autoFill.add(p_autoFill);
p_autoFill.add(new JLabel("What percentage should be filled? "));
Object[] percentageOptions = {"Select",5,10,15,20,25,30,40,50,60,70,80,90,95};
final JComboBox cb_percent = new JComboBox(percentageOptions);
p_autoFill.add(cb_percent);
cb_percent.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (cb_percent.getSelectedIndex() > 0) {
gb_gameBoard.resetBoard();
gb_gameBoard.randomlyFillBoard((Integer)cb_percent.getSelectedItem());
f_autoFill.dispose();
}
}
});
f_autoFill.setVisible(true);
} else if (ae.getSource().equals(mi_game_reset)) {
gb_gameBoard.resetBoard();
gb_gameBoard.repaint();
} else if (ae.getSource().equals(mi_game_play)) {
setGameBeingPlayed(true);
} else if (ae.getSource().equals(mi_game_stop)) {
setGameBeingPlayed(false);
} else if (ae.getSource().equals(mi_help_source)) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
try {
desktop.browse(new URI("https://link adress));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Source is available on GitHub at: ",//link adress "Source", JOptionPane.INFORMATION_MESSAGE);
}
}
else if (ae.getSource().equals(mi_help_about))
{
JOptionPane.showMessageDialog(null, "Conway's game of life was a cellular animation ");
}
}

private class GameBoard extends JPanel implements ComponentListener, MouseListener, MouseMotionListener, Runnable {
private Dimension d_gameBoardSize = null;
private ArrayList<Point> point = new ArrayList<Point>(0);

public GameBoard() {

addComponentListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}

private void updateArraySize() {
ArrayList<Point> removeList = new ArrayList<Point>(0);
for (Point current : point) {
if ((current.x > d_gameBoardSize.width-1) || (current.y > d_gameBoardSize.height-1)) {
removeList.add(current);
}
}
point.removeAll(removeList);
repaint();
}

public void addPoint(int x, int y) {
if (!point.contains(new Point(x,y))) {
point.add(new Point(x,y));
}
repaint();
}

public void addPoint(MouseEvent me) {
int x = me.getPoint().x/BLOCK_SIZE-1;
int y = me.getPoint().y/BLOCK_SIZE-1;
if ((x >= 0) && (x < d_gameBoardSize.width) && (y >= 0) && (y < d_gameBoardSize.height)) {
addPoint(x,y);
}
}

public void removePoint(int x, int y) {
point.remove(new Point(x,y));
}

public void resetBoard() {
point.clear();
}

public void randomlyFillBoard(int percent)
{
for (int m=0; m<d_gameBoardSize.width; m++)
{
for (int j=0; j<d_gameBoardSize.height; j++) {
if (Math.random()*100 < percent) {
addPoint(m,j);
}
}
}
}

  

public void paintComponent(Graphics g) {
super.paintComponent(g);
try {
for (Point newPoint : point) {

g.setColor(Color.blue);
g.fillRect(BLOCK_SIZE + (BLOCK_SIZE*newPoint.x), BLOCK_SIZE + (BLOCK_SIZE*newPoint.y), BLOCK_SIZE, BLOCK_SIZE);
}
} catch (ConcurrentModificationException cme) {}

g.setColor(Color.BLACK);
for (int m=0; m<=d_gameBoardSize.width; m++)
{
g.drawLine(((m*BLOCK_SIZE)+BLOCK_SIZE), BLOCK_SIZE, (m*BLOCK_SIZE)+BLOCK_SIZE, BLOCK_SIZE + (BLOCK_SIZE*d_gameBoardSize.height));
}
for (int m=0; m<=d_gameBoardSize.height; m++) {
g.drawLine(BLOCK_SIZE, ((m*BLOCK_SIZE)+BLOCK_SIZE), BLOCK_SIZE*(d_gameBoardSize.width+1), ((m*BLOCK_SIZE)+BLOCK_SIZE));
}
}

  
public void componentResized(ComponentEvent e) {

d_gameBoardSize = new Dimension(getWidth()/BLOCK_SIZE-2, getHeight()/BLOCK_SIZE-2);
updateArraySize();
}

public void componentMoved(ComponentEvent e) {}

public void componentShown(ComponentEvent e) {}

public void componentHidden(ComponentEvent e) {}
  
public void mouseClicked(MouseEvent e) {}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {

addPoint(e);
}

public void mouseEntered(MouseEvent e) {}

  
public void mouseExited(MouseEvent e) {}


public void mouseDragged(MouseEvent e) {
  
addPoint(e);
}
  
public void mouseMoved(MouseEvent e) {}

  
public void run()
{
boolean[][] gameBoard = new boolean[d_gameBoardSize.width+2][d_gameBoardSize.height+2];
for (Point current : point)
{
gameBoard[current.x+1][current.y+1] = true;
}
ArrayList<Point> survivingCells = new ArrayList<Point>(0);
  
for (int m=1; m<gameBoard.length-1; m++)
{
for (int j=1; j<gameBoard[0].length-1; j++)
{
int surrounding = 0;
if (gameBoard[i-1][j-1]) { surrounding++; }
if (gameBoard[i-1][j]) { surrounding++; }
if (gameBoard[i-1][j+1]) { surrounding++; }
if (gameBoard[i][j-1]) { surrounding++; }
if (gameBoard[i][j+1]) { surrounding++; }
if (gameBoard[i+1][j-1]) { surrounding++; }
if (gameBoard[i+1][j]) { surrounding++; }
if (gameBoard[i+1][j+1]) { surrounding++; }
if (gameBoard[i][j]) {

if ((surrounding == 2) || (surrounding == 3))
{
survivingCells.add(new Point(m-1,j-1));
}
} else
{
  
if (surrounding == 3) {
survivingCells.add(new Point(m-1,j-1));
}
}
}
}
resetBoard();
point.addAll(survivingCells);
repaint();
try {
Thread.sleep(1000/m_movesPerSecond);
run();
} catch (InterruptedException ex) {}
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote