Question

Write this Game of Life program in Java. The Game of Life is a well-known mathematical...

Write this Game of Life program in Java.

The Game of Life is a well-known mathematical game that gives rise to amazingly complex behavior, although it can be specified by a few simple rules. Here are the rules. The game is played on a rectangular board. Each square can be either empty or occupied. At the beginning, you can specify empty and occupied cells using 1's and 0's; then the game runs automatically. In each generation, the next generation is computed. A new cell is born on an empty square if it is surrounded by exactly three occupied neighbor cells. A cell dies of overcrowding if it is surrounded by four or more neighbors, and it dies of loneliness if it is surrounded by zero or one neighbor. A neighbor is an occupant of an adjacent square to the left, right, top, or bottom or in a diagonal direction.

Program the game to eliminate the drudgery of computing successive generations by hand. Use a two-dimensional array to store the rectangular configuration. Write a program that shows successive generations of the game on console (you may not use GUI). Ask the USER to INPUT the original configuration, by taking in USER INPUT for the number of rows and columns; and then also take USER INPUT for the initial board configuration of 1's and 0's.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Random;
import java.util.Scanner;

public class GameOfLife {

        final static String ALIVE = "1", DEAD = "0";
        final static int CHANCE_ALIVE = 6, SEED = 10;

        public static void main(String[] args) {

                final String welcomeMessage = "Welcome to Conway's Game Of Life"
                                + "\n--------------------------------";
                final String exitMessage = "----------------------------"
                                + "\nEnd of Conway's Game Of Life";
                final String optionList = "1)Glider 2)Beacon 3)Beehive 4)R-pentomino"
                                + "\n5)Random 6)Custom or 7)Exit" + "\nChoose a pattern: ";

                // Scanner to get user input
                Scanner in = new Scanner(System.in);

                int userChoice = 0;
                // Initialize world array
                boolean[][] world = new boolean[10][10];

                clearWorld(world);

                // Display welcome message
                System.out.println(welcomeMessage);
                do {
                        // Display menu
                        System.out.print(optionList);

                        userChoice = getIntChoice(in, 1, 7);

                        if (userChoice != 7) {
                                if (userChoice == 1) {
                                        initializeGliderWorld(world);
                                } else if (userChoice == 2) {
                                        initializeBeaconWorld(world);
                                } else if (userChoice == 3) {
                                        initializeBeehiveWorld(world);
                                } else if (userChoice == 4) {
                                        initializeRpentominoWorld(world);
                                } else if (userChoice == 5) {
                                        initializeRandomWorld(world);
                                } else if (userChoice == 6) {
                                        
                                        System.out.println("Enter 10 lines of (1 or 0) and type 'end' to stop ");
                                        initializeCustomWorld(in, world);
                                }
                                
                                String stringChoice = "";
                                int generationNum = 0;
                                do {
                                        // Display generation
                                        System.out.println("\nGeneration: " + generationNum);
                                        printWorld(world);

                                        int aliveCount = noOfAliveCells(world);

                                        // Display no. of alive cells
                                        if (aliveCount == 0)
                                                System.out.println("No cells are alive.");
                                        else if (aliveCount == 1)
                                                System.out.println("1 cell is alive.");
                                        else
                                                System.out.println(aliveCount + " cells are alive.");

                                        // Check if the user wants to continue
                                        System.out
                                                        .print("Press Enter for next generation, 'end' to stop: ");
                                        stringChoice = in.nextLine().trim();

                                        // Increase generation
                                        generationNum += 1;
                                        boolean[][] newWorld= new boolean[10][10]; 
                                        nextGeneration(world, newWorld);
                                        world = newWorld;
                                } while (!stringChoice.equalsIgnoreCase("end"));
                        }
                } while (userChoice != 7);

                // Display exit message
                System.out.println(exitMessage);

                // Close scanner
                in.close();
        }

        /**
         * Prints out the world showing each cell as alive or dead.
         * 
         * Loops through every cell of the world. If a cell is alive, print out the
         * Config.ALIVE character, otherwise print out the Config.DEAD character.
         * 
         * Counts how many cells are alive and prints out the number of cells alive.
         * For 2 or more cells alive, for 1 cell alive and 0 cells alive the
         * following messages are printed: 5 cells are alive. 1 cell is alive. No
         * cells are alive.
         * 
         * @param world
         *            The array representation of the current world.
         */
        public static void printWorld(boolean[][] world) {

                for (int i = 0; i < world.length; i++) {
                        for (int j = 0; j < world[i].length; j++) {
                                System.out.print((world[i][j] ? ALIVE : DEAD) + " ");
                        }
                        System.out.println();
                }
        }

        public static int noOfAliveCells(boolean[][] world) {
                int alive = 0;
                for (int i = 0; i < world.length; i++) {
                        for (int j = 0; j < world[i].length; j++) {
                                if (world[i][j])
                                        alive++;
                        }
                }
                return alive;
        }

        /**
         * This method clears the world by setting all the cells in the world to
         * false (dead). This method uses array lengths, not constants, to determine
         * the size of the world.
         * 
         * @param world
         *            the world to clear
         */
        public static void clearWorld(boolean[][] world) {
                for (int i = 0; i < world.length; i++) {
                        for (int j = 0; j < world[i].length; j++) {
                                world[i][j] = false;
                        }
                }
        }

        /**
         * This method expects an integer to be entered by the user between and
         * including the values of min and max. If the value entered is not an
         * integer or is an integer but less than min or greater than max the
         * following message is displayed: Enter a number between 1 and 5: Assuming
         * that min was 1 and max was 5 when this method was called.
         * 
         * @param input
         *            The Scanner instance for reading from System.in.
         * @param min
         *            The minimum acceptable integer.
         * @param max
         *            The maximum acceptable integer.
         * @return An integer between and including min and max.
         */
        public static int getIntChoice(Scanner input, int min, int max) {
                // Get user choice
                int userChoice = 0;

                while (true) {
                        boolean error = false;
                        try {
                                userChoice = Integer.parseInt(input.next());
                                if ((min <= userChoice) && (userChoice <= max))
                                        error = false;
                                else
                                        error = true;
                        } catch (NumberFormatException e) {
                                error = true;
                        }

                        if (error) {
                                // If user enters anything other than a value between 1-7
                                System.out.print("Enter a number between 1 and 7: ");
                        } else {
                                break;
                        }
                }

                return userChoice;
        }

        /**
         * Initializes the world to the Glider pattern.
         * 
         * <pre>
         * ..........
         * .@........
         * ..@@......
         * .@@.......
         * ..........
         * ..........
         * ..........
         * ..........
         * </pre>
         * 
         * The world may have any pattern within it when passed into this method.
         * After this method call, the only living cells in the world is the Glider
         * pattern as shown.
         * 
         * @param world
         *            the existing double dimension array that will be reinitialized
         *            to the Glider pattern.
         */
        public static void initializeGliderWorld(boolean[][] world) {
                clearWorld(world);
                world[1][1] = true;
                world[2][2] = true;
                world[2][3] = true;
                world[3][1] = true;
                world[3][2] = true;
        }

        /**
         * Initializes the world to the Beacon pattern.
         * 
         * <pre>
         * ..........
         * .@@.......
         * .@........
         * ....@.....
         * ...@@.....
         * ..........
         * ..........
         * ..........
         * </pre>
         * 
         * The world may have any pattern within it when passed into this method.
         * After this method call, the only living cells in the world is the Beacon
         * pattern as shown.
         * 
         * @param world
         *            the existing 2-dimension array that will be reinitialized to
         *            the Beacon pattern.
         */
        public static void initializeBeaconWorld(boolean[][] world) {
                clearWorld(world);
                world[1][1] = true;
                world[1][2] = true;
                world[2][1] = true;
                world[3][4] = true;
                world[4][3] = true;
                world[4][4] = true;
        }

        /**
         * Initializes the world to the Beehive pattern.
         * 
         * <pre>
         * ..........
         * ..@@......
         * .@..@.....
         * ..@@......
         * ..........
         * ..........
         * ..........
         * ..........
         * </pre>
         * 
         * The world may have any pattern within it when passed into this method.
         * After this method call, the only living cells in the world is the Beehive
         * pattern as shown.
         * 
         * @param world
         *            the existing double dimension array that will be reinitialized
         *            to the Beehive pattern.
         */
        public static void initializeBeehiveWorld(boolean[][] world) {
                clearWorld(world);
                world[1][3] = true;
                world[1][2] = true;
                world[2][1] = true;
                world[2][4] = true;
                world[3][2] = true;
                world[3][3] = true;
        }

        /**
         * Initializes the world to the R-pentomino pattern.
         * 
         * <pre>
         * ..........
         * ..@@......
         * .@@.......
         * ..@.......
         * ..........
         * ..........
         * ..........
         * ..........
         * </pre>
         * 
         * The world may have any pattern within it when passed into this method.
         * After this method call, the only living cells in the world is the
         * R-pentomino pattern as shown.
         * 
         * @param world
         *            the existing double dimension array that will be reinitialized
         *            to the R-pentomino pattern.
         */
        public static void initializeRpentominoWorld(boolean[][] world) {
                clearWorld(world);
                world[1][3] = true;
                world[1][2] = true;
                world[2][1] = true;
                world[2][2] = true;
                world[3][2] = true;
        }

        /**
         * Initialize the GameOfLife world with a random selection of cells alive.
         * 
         * For testing purposes, implementations should use the Config.CHANCE_ALIVE
         * constant and Config.SEED. Create an instance of the java.util.Random
         * class, setting the seed to the SEED constant. For each cell, if the
         * returned value of the nextDouble() method is less than
         * Config.CHANCE_ALIVE then the cell is alive.
         * 
         * @param world
         *            the existing double dimension array that will be reinitialized
         *            to a Random pattern.
         */
        public static void initializeRandomWorld(boolean[][] world) {
                Random r = new Random(SEED);
                for (int i = 0; i < world.length; i++) {
                        for (int j = 0; j < world[i].length; j++) {
                                world[i][j] = (r.nextInt() <= CHANCE_ALIVE);
                        }
                }
        }

        /**
         * Prompt for a pattern of cells. Each line of input corresponds to one row
         * in the world. Continue reading lines until 'END' is entered on a line of
         * its own. Ignore case and leading and trailing spaces when comparing to
         * 'END'. (See String methods such as trim() method.)
         * 
         * The maximum size is the size of the world passed into this method. Any
         * additional characters typed by the user are ignored. When interpreting
         * the characters typed in, only the Config.ALIVE character is used to
         * determine which cells are alive. All other characters are interpreted as
         * dead cells.
         * 
         * @param input
         *            The Scanner instance that reads from System.in.
         * @param world
         *            The world array that is filled with the pattern the user
         *            enters.
         */
        public static void initializeCustomWorld(Scanner input, boolean[][] world) {
                String s = input.nextLine();
                int row = 0;
                while(!s.equalsIgnoreCase("end")) {
                        char c[] = s.toCharArray();
                        int col=0;
                        for(char ch: c){
                                if(String.valueOf(ch).equalsIgnoreCase(ALIVE))
                                        world[row][col] = true;
                                else
                                        world[row][col] = false;
                                
                                col++;
                                if(col == 10)
                                        break;
                        }
                        
                        row++;
                        if(row == 10)
                                break;
                        s = input.nextLine();
                }
        }

        /**
         * Checks whether a specific cell is alive or dead.
         * 
         * Note that cellRow and cellColumn may not be valid indexes into the world
         * array. Return false for any cell outside the world array. Checks the
         * values of cellRow and cellColumn to make sure they are valid prior to
         * looking in the world array. Does not use try-catch blocks or other
         * exception handling mechanisms.
         * 
         * @param world
         *            The current world.
         * @param cellRow
         *            The row of the cell which we are wanting to know whether it is
         *            alive.
         * @param cellColumn
         *            The column of the cell which we are wanting to know whether it
         *            is alive.
         * 
         * @return Whether the specified cell is alive.
         */
        public static boolean isCellAlive(boolean[][] world, int cellRow,
                        int cellColumn) {

                if (cellRow < 10 && cellRow >= 0 && cellColumn < 10 && cellColumn >= 0) {
                        if (world[cellRow][cellColumn]) {
                                return true;
                        }
                }
                return false;
        }

        /**
         * Counts the number of neighbors that are currently living around the
         * specified cell.
         * 
         * A cell has eight neighbors. The neighbors are the cells that are
         * horizontally, vertically and diagonally adjacent.
         * 
         * Calls the isCellAlive method to determine whether any specific cell is
         * alive.
         * 
         * @param world
         *            The current world.
         * @param row
         *            The row of the cell for which we are looking for living
         *            neighbors.
         * @param column
         *            The column of the cell for which we are looking for living
         *            neighbors.
         * 
         * @return The number of neighbor cells that are currently living.
         */
        public static int numNeighborsAlive(boolean[][] world, int row, int col) {
                int activeNeighbours = 0;

                if (isCellAlive(world, row - 1, col - 1))
                        activeNeighbours++;
                if (isCellAlive(world, row - 1, col))
                        activeNeighbours++;
                if (isCellAlive(world, row - 1, col + 1))
                        activeNeighbours++;

                if (isCellAlive(world, row, col - 1))
                        activeNeighbours++;
                if (isCellAlive(world, row, col + 1))
                        activeNeighbours++;

                if (isCellAlive(world, row + 1, col - 1))
                        activeNeighbours++;
                if (isCellAlive(world, row + 1, col))
                        activeNeighbours++;
                if (isCellAlive(world, row + 1, col + 1))
                        activeNeighbours++;

                return activeNeighbours;
        }

        /**
         * Whether a cell is living in the next generation of the game.
         * 
         * The rules of the game are as follows: 1) Any live cell with fewer than
         * two live neighbors dies, as if caused by under-population. 2) Any live
         * cell with two or three live neighbors lives on to the next generation. 3)
         * Any live cell with more than three live neighbors dies, as if by
         * overcrowding. 4) Any dead cell with exactly three live neighbors becomes
         * a live cell, as if by reproduction.
         * 
         * @param numLivingNeighbors
         *            The number of neighbors that are currently living.
         * @param cellCurrentlyLiving
         *            Whether the cell is currently living.
         * 
         * @return true if this cell is living in the next generation, otherwise
         *         false.
         */
        public static boolean isCellLivingInNextGeneration(int numLivingNeighbors,
                        boolean cellCurrentlyLiving) {
                if (cellCurrentlyLiving) {
                        if (numLivingNeighbors == 3 || numLivingNeighbors == 2) {
                                return true;
                        }
                } else {
                        if (numLivingNeighbors == 3) {
                                return true;
                        }
                }
                return false;
        }

        /**
         * Determines the cells living in the next generation of the world. The next
         * generation is created by applying the 4 rules simultaneously to every
         * cell in the previous generation. Births and deaths occur simultaneously.
         * In other words, look only at whether cells are living in the current
         * generation to determine whether a cell lives in the new generation. Don't
         * look at other cells in the new generation.
         * 
         * For each cell in the current generation, determine whether the cell at
         * the same coordinates is living in the next generation using the
         * numNeighborsAlive and the isCellLivingInNextGeneration methods.
         * 
         * @param currentWorld
         *            The world currently shown.
         * @param newWorld
         *            The new world based on the rules of life.
         */
        public static void nextGeneration(boolean[][] currentWorld,
                        boolean[][] newWorld) {

                for (int i = 0; i < currentWorld.length; i++) {
                        for (int j = 0; j < currentWorld[i].length; j++) {
                                newWorld[i][j] = isCellLivingInNextGeneration(
                                                numNeighborsAlive(currentWorld, i, j),
                                                currentWorld[i][j]);
                        }
                }
        }
}


Please upvote, as i have given the exact answer as asked in question. Still in case of any concerns in code, let me know in comments. Thanks!

Add a comment
Answer #2

Certainly! Here's an example Java program that implements the Game of Life based on the rules you provided. It takes user input for the number of rows and columns, as well as the initial board configuration of 1's and 0's. It then displays successive generations of the game on the console.

import java.util.Scanner;


public class GameOfLife {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);


        // User input for number of rows and columns

        System.out.print("Enter the number of rows: ");

        int rows = scanner.nextInt();

        System.out.print("Enter the number of columns: ");

        int columns = scanner.nextInt();


        // Create the game board

        int[][] board = new int[rows][columns];


        // User input for initial board configuration

        System.out.println("Enter the initial board configuration (1's and 0's):");

        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < columns; j++) {

                board[i][j] = scanner.nextInt();

            }

        }


        // Display initial board

        System.out.println("Initial board:");

        displayBoard(board);


        // Generate successive generations

        while (true) {

            System.out.print("Press Enter to generate the next generation (or 'q' to quit): ");

            String input = scanner.nextLine();


            if (input.equalsIgnoreCase("q")) {

                break;

            }


            // Compute the next generation

            int[][] nextGeneration = generateNextGeneration(board);


            // Display the next generation

            System.out.println("Next generation:");

            displayBoard(nextGeneration);


            // Update the board for the next iteration

            board = nextGeneration;

        }

    }


    // Method to generate the next generation based on the current board

    public static int[][] generateNextGeneration(int[][] board) {

        int rows = board.length;

        int columns = board[0].length;

        int[][] nextGeneration = new int[rows][columns];


        for (int i = 0; i < rows; i++) {

            for (int j = 0; j < columns; j++) {

                int liveNeighbors = countLiveNeighbors(board, i, j);

                if (board[i][j] == 1) {

                    if (liveNeighbors == 2 || liveNeighbors == 3) {

                        nextGeneration[i][j] = 1; // Cell survives

                    } else {

                        nextGeneration[i][j] = 0; // Cell dies

                    }

                } else {

                    if (liveNeighbors == 3) {

                        nextGeneration[i][j] = 1; // Cell is born

                    }

                }

            }

        }


        return nextGeneration;

    }


    // Method to count the number of live neighbors for a given cell

    public static int countLiveNeighbors(int[][] board, int row, int col) {

        int count = 0;

        int rows = board.length;

        int columns = board[0].length;


        // Define the eight possible neighbors' positions

        int[][] directions = {

                {-1, -1}, {-1, 0}, {-1, 1},

                {0, -1},           {0, 1},

                {1, -1}, {1, 0}, {1, 1}

        };


        for (int[] direction : directions) {

            int newRow = row + direction[0];

            int newCol = col + direction[1];


            // Check if the neighbor is within the board boundaries and is live

            if (newRow >= 0 && newRow < rows &&


answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
Write this Game of Life program in Java. The Game of Life is a well-known mathematical...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write this Game of Life program in Java. The Game of Life is a well-known mathematical...

    Write this Game of Life program in Java. The Game of Life is a well-known mathematical game that gives rise to amazingly complex behavior, although it can be specified by a few simple rules. Here are the rules. The game is played on a rectangular board. Each square can be either empty or occupied. At the beginning, you can specify empty and occupied cells using 1's and 0's; then the game runs automatically. In each generation, the next generation is...

  • Write a program that consists of a 10 by 10 game board, with 10 generations. Project...

    Write a program that consists of a 10 by 10 game board, with 10 generations. Project The Game of Life The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the neighbors of this cell. Each game state is called "generation". The game progresses from one generation to the next according to the following rules: A creature that has...

  • Please use C++, thank you! The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the...

    Please use C++, thank you! The life game consists of a board with size of NxN cells and cells are occupied by creatures. Each cell can have at most one creature. The surrounding cells are called the neighbors of this cell Each game state is called "generation". The game progresses from one generation to the next according to the following rules: A creature that has more than 3 neighbors- dies of crowding. Its cell will be empty in the next...

  • JAVA. Threading the Game of Life Write a Java program to implement the Game of Life,...

    JAVA. Threading the Game of Life Write a Java program to implement the Game of Life, as defined by John Conway: Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies, as if by overpopulation. Any dead cell with exactly three live neighbors becomes a live cell, as if by...

  • I have a question about my assignment. Could you please make program and give me some...

    I have a question about my assignment. Could you please make program and give me some explanation of codes? I need c++ codes. Conway's Game of Life is a game invented by mathematician John Conway in 1970. The rules are as follows: Each cell lives in a cell in a square (make it 10x10) grid. A cell can either be dead or alive. Before you start the game, you need to provide an initial state. You can do this by...

  • I have a question about my assignment. Could you please make program and give me some...

    I have a question about my assignment. Could you please make program and give me some explanation of codes? Conway's Game of Life is a game invented by mathematician John Conway in 1970. The rules are as follows: Each cell lives in a cell in a square (make it 10x10) grid. A cell can either be dead or alive. Before you start the game, you need to provide an initial state. You can do this by randomly setting 20 of...

  • I am really struggling with how to approach this program. Conway's Game of life, whereby, 1....

    I am really struggling with how to approach this program. Conway's Game of life, whereby, 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. 2. Any live cell with two or three live neighbours lives on to the next generation. 3. Any live cell with more than three live neighbours dies, as if by over-population. 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. Submit...

  • Option 2: Conwav's Game of Life Your task is to write a program that plays Conway's...

    Option 2: Conwav's Game of Life Your task is to write a program that plays Conway's Game of Life (for details and ex amples, see https://en.vikipedia.org/wiki/Convay's.Game of Life). The basic gam ts played on each generation, each cell changes according to the following instructions: nal grid of square cells, each of which is either alive or dead. With 1. Any dead cell with exactly three live neighbors (out of its eight nearest neighbors) comes to life [reproduction]. 2. Any live...

  • Program in C++ Implement Conway's Game of Life using 2-dimensional arrays. All the tips, tricks, techniques...

    Program in C++ Implement Conway's Game of Life using 2-dimensional arrays. All the tips, tricks, techniques we have been using in class are allowed. Nothing else. The program should read the initial state of the board by reading in "alive" cells from a user input data file. Meaning your program should ask the user the name of the data file. Assume all the other cells are "dead." Make sure to use modular coding techniques. The main program should be pretty...

  • Objective: Write a program that implements the Game of Life cellular automata system invented by John...

    Objective: Write a program that implements the Game of Life cellular automata system invented by John Conway. 1. Create two game grids of size at least 50x50. These grid cells can be either Boolean or integer. In the following, I’ll refer to these as gridOne and gridTwo. 2. Set all cells in both grids to false. 3. Start by initializing gridOne. Allow the user to specify two different ways of initializing the grid: 1) by specifying a pattern file to...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT