Question

In: Computer Science

Project #1 Designing and implementing the Game of Life The main task is to implement (in...

Project #1

Designing and implementing the Game of Life

The main task is to implement (in java) a 2-D (or 3-D) Graphic version of the Game of Life

Solutions

Expert Solution

NOTE: We get only 2 hours to solve a problem. In this limited time frame, I could only come up with the initial game setup without any graphics.

CODE

Grid.java

public class Grid {

    private static int DEFAULT_WIDTH = 8;
    private static int DEFAULT_HEIGHT = 7;

    private int[][] grid;
    private int rows;
    private int columns;

    /**
     * Constructor that creates a random state
     */
    public Grid() {
        grid = new int[DEFAULT_WIDTH][DEFAULT_HEIGHT];
        for (int i=0; i<DEFAULT_WIDTH; i++) {
            for (int j=0; j<DEFAULT_HEIGHT; j++) {
                grid[i][j] = (int) Math.round(Math.random());
            }
        }

        this.rows = this.grid.length;
        this.columns = this.grid[0].length;
    }

    /**
     * Constructor allowing for initial state to be passed in.
     *
     * @param grid Two dimensional array of state to start with
     * @throws IllegalArgumentException
     */
    public Grid(int[][] grid) {
        if (isJagged(grid)) {
            throw new IllegalArgumentException("Arrays passed in cannot be jagged");
        }
        this.grid = grid;
        this.rows = this.grid.length;
        this.columns = this.grid[0].length;
    }

    /**
     * Returns the current generation
     *
     * @return Returns two dimensional array representing current state
     */
    public int[][] currentGeneration() {

        return this.grid;
    }

    /**
     * Returns the number of rows in the grid
     *
     * @return Number of rows
     */
    public int rows() {
        return this.rows;
    }

    /**
     * Returns the number of columns in the grid
     *
     * @return Number of columns
     */
    public int columns() {
        return this.columns;
    }

    /**
     * Returns the next generation
     *
     * @return Returns two dimensional array representing next state
     */
    public int[][] nextGeneration() {

        int[][] futureGeneration = new int[grid.length][grid[0].length];
        int rows = grid.length;
        int columns = grid[0].length;

        // iterate through two dimensional array
        for (int i=0; i<rows; i++) {
            for(int j=0; j<columns; j++) {
                futureGeneration[i][j] = this.getNextStateForCell(i,j);
            }
        }
        return futureGeneration;
    }

    /**
     * Gets next state for a particular cell
     *
     * @param i Row index of the grid
     * @param j Column index of the grid
     * @return 1 is cell alive, 0 if cell is dead
     */
    private int getNextStateForCell(int i, int j) {

        // get living neighbors
        int aliveNeighbors = this.calculateLivingNeighbors(i,j);

        /**
         * Cell is lonely with less than two live neighbors and dies
         */
        if ((grid[i][j] == 1) && (aliveNeighbors < 2)) {
            return  0;
        }

        /**
         * Cell is overcrowded and dies
         */
        else if ((grid[i][j] == 1) && aliveNeighbors > 3) {
            return  0;
        }

        /**
         * Cell is dead but 3 lives neighbors causes it to be born
         */
        else if (grid[i][j] == 0 && aliveNeighbors == 3) {
            return  1;
        }

        /**
         * Nothing changes so copy that state
         */
        else {
            return grid[i][j];
        }
    }

    /**
     * Returns the count of living neighbors for a particular cell in the grid
     *
     * @param i Row index of the grid
     * @param j Column index of the grid
     * @return Count of living neighbors for particular cell
     */
    private int calculateLivingNeighbors(int i, int j) {
        int liveCount = 0;
        for (int x=-1; x<=1; x++) {
            for (int y = -1; y <= 1; y++) {
                // check for boundary conditions
                if (i + x < 0 || i + x > (this.rows - 1) || y + j < 0 || y + j > (this.columns - 1)) {
                    continue;
                }
                liveCount += grid[i + x][y + j];
            }
        }

        // remove since we may have counted ourselves
        liveCount -= grid[i][j];

        return liveCount;
    }

    /**
     * Determines if array is jagged.
     *
     * @param array Array to test if jagged
     * @return True if jagged, otherwise false
     */
    private boolean isJagged(int[][] array) {
        boolean isJagged = false;

        if (array != null) {
            Integer length = null;
            for (int i=0; i<array.length; i++) {
                if(length == null) {
                    length = array[i].length;
                }
                else if (length.equals(array[i].length)) {
                    continue;
                }
                else {
                    isJagged = true;
                    break;
                }
            }
        }

        return isJagged;
    }
}

GameOfLife.java

public class GameOfLife {

    public static void main(String[] args) {

        Grid grid = new Grid();
        int[][] currentGen = grid.currentGeneration();
        int[][] nextGen = grid.nextGeneration();
        System.out.println("Current Generation");
        printResults(currentGen);
        System.out.println("Next Generation");
        printResults(nextGen);
    }

    private static void printResults(int[][] results) {
        for (int i=0; i<results.length; i++) {
            for (int j=0; j<results[i].length; j++) {
                if (results[i][j] == 0) {
                    System.out.print(".");
                } else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
    }
}

Related Solutions

Assignment Implement Conway’s Game of Life. The Game of Life is a simple simulation that takes...
Assignment Implement Conway’s Game of Life. The Game of Life is a simple simulation that takes place in a grid of cells. Each cell can be either alive or dead, and it interacts with its neighbors (horizontally, vertically, or diagonally). In each iteration, a decision will be made to see if living cells stay alive, or if dead cells become alive. The algorithm is as follows: If a cell is alive: If it has less than two living neighbors, it...
Assignment Implement Conway’s Game of Life IN C The Game of Life is a simple simulation...
Assignment Implement Conway’s Game of Life IN C The Game of Life is a simple simulation that takes place in a grid of cells. Each cell can be either alive or dead, and it interacts with its neighbors (horizontally, vertically, or diagonally). In each iteration, a decision will be made to see if living cells stay alive, or if dead cells become alive. The algorithm is as follows: If a cell is alive: If it has less than two living...
Assignment Implement Conway’s Game of Life. The Game of Life is a simple simulation that takes...
Assignment Implement Conway’s Game of Life. The Game of Life is a simple simulation that takes place in a grid of cells. Each cell can be either alive or dead, and it interacts with its neighbors (horizontally, vertically, or diagonally). In each iteration, a decision will be made to see if living cells stay alive, or if dead cells become alive. The algorithm is as follows: If a cell is alive: If it has less than two living neighbors, it...
List the three main goals of a project. Use an example of a project to implement...
List the three main goals of a project. Use an example of a project to implement a new billing procedure for a small lawn mowing business, describe how project management principles help achieve these goals.
In this project we will implement the Minesweeper game. Minesweeper is played on a rectangle grid....
In this project we will implement the Minesweeper game. Minesweeper is played on a rectangle grid. When the game starts, a number of bombs are hidden on random positions on the field. In every round, the player "touches" a cell of the field. If the cell contains a bomb, it explodes, the game ends, and the player loses. Otherwise, the cell is uncovered to show the number of bombs in the vicinity, that is, the number of neighboring cells that...
Project 1—UNIX Shell This project consists of designing a C program to serve as a shell...
Project 1—UNIX Shell This project consists of designing a C program to serve as a shell interface that accepts user commands and then executes each command in a separate process. Your implementation will support input and output redirection, as well as pipes as a form of IPC between a pair of commands. Completing this project will involve using the UNIX fork(), exec(), wait(), dup2(), and pipe() system calls and can be completed on any Linux, UNIX, or macOS system. I....
The Company assists clients by designing and implementing solutions that reduce the overall costs of its...
The Company assists clients by designing and implementing solutions that reduce the overall costs of its customers’ supply chains. The Company provides Just-In-Time (JIT) inventory management of spare parts used in its customers’ manufacturing processes to reduce cycle times and lower inventory-related costs. The Company entered into a supply management contract (the “Agreement”) with the Customer, an unrelated third party, to provide spare parts , management services,(including sourcing, procurement, repair, transport and delivery), and warehouse management. ?The key terms of...
Stanley & Sons Inc. (the “Company”) assists clients by designing and implementing solutions that reduce the...
Stanley & Sons Inc. (the “Company”) assists clients by designing and implementing solutions that reduce the overall costs of its customers’ supply chains. The Company provides Just-In-Time (JIT) inventory management of spare parts used in its customers’ manufacturing processes to reduce cycle times and lower inventory-related costs. The Company entered into a supply management contract (the “Agreement”) with Tadduni Partners (the “Customer”), an unrelated third party, to provide spare parts management services, including sourcing, procurement, repair, transport and delivery, and...
What are the steps in designing a Research Project?
What are the steps in designing a Research Project?
Implement Hot Potato game A group of people, numbered 1 to N, are sitting in a...
Implement Hot Potato game A group of people, numbered 1 to N, are sitting in a circle. Starting at person 1, a hot potato is passed. After X passes, the person holding the hot potato is eliminated, the circle closes ranks, and the game continues with the person who was sitting after the eliminated person picking up the hot potato. The last remaining person wins. For example: if X = 0 and N = 5, players are eliminated in order,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT