Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 34

Thread: Game of Life, help with Array Object? Quite puzzled

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Game of Life, help with Array Object? Quite puzzled

    I've been asked to change my game of life code to include objects, and I'm not quite exactly sure how to go about doing that. Haven't worked with objects yet, and am a very mediocre beginning programmer. Attached are the specifications of the program and here is the code I have thus far. Any/All help greatly appreciated, thank you.
     
     
    import java.util.Random;
    import java.util.Scanner;
     
     
    /**This program creates a random matrix of life that exists in specific dimensions.*/
    public class Life {
        /**This method asks for user input and calls the initializing and printing
        methods.*/ 
        public static void main(String[] args) {
     
            Scanner console = new Scanner(System.in); /**New Scanner*/
     
            System.out.println("Number of rows?");
            int rows = console.nextInt(); /** Saves input as number of rows.*/
     
            System.out.println("Number of columns?");
            int columns = console.nextInt(); /** Saves input as number of columns.*/
     
            System.out.println("Seed number?");
            long seed = console.nextLong(); /** Saves input as number of seed.*/
     
            System.out.println("Birth minimum?");
            int birthLow = console.nextInt(); /** Saves input as minimum number for birth.*/
     
            System.out.println("Birth maximum?");
            int birthHigh = console.nextInt(); /** Saves input as maximum number for birth.*/
     
            System.out.println("Minimum Life?");
            int liveLow = console.nextInt(); /** Saves input as minimum number for death.*/
     
            System.out.println("Maximum Life?");
            int liveHigh = console.nextInt(); /** Saves input as maximum number for death.*/
     
            boolean newMatrix[][] = new boolean[rows][columns]; 
            /** Creates boolean array according to dimensions entered.*/
     
     
     
            array(newMatrix, rows, columns, seed); /** Calls the matrix initializing method.*/
     
            printArray(newMatrix, rows, columns); /** Calls the array printing method.*/
     
            System.out.println();
     
            for(int i=0; i<4; i++){
     
                changeMatrix(newMatrix, rows, columns, birthLow, birthHigh, liveLow, liveHigh);
                printArray(newMatrix, rows, columns);
                System.out.println();
            }
     
        }
     
        /** This method sets the matrix with true and false values.*/
        public static void array(boolean[][] Matrix, int rows, int columns,
                long seed) {
     
            Random generator = new Random(seed); /**Random number generated according to seed input.*/
     
            /** Loop traverses every row after first and before the last.*/
                   for (int i = 1; i < rows - 1; i++) {
                /** Loop traverses every column after first and before last.*/
                for (int j = 1; j < columns - 1; j++) {
     
                    /** Will generate a random boolean value.*/
                    boolean x = generator.nextBoolean();
     
                    /** If x is false, sets the array location as false.*/
                    if (!x) {
                        Matrix[i][j] = false;
     
                    }
     
                    /** If x is true, sets the array location as true.*/
                    else {
                        Matrix[i][j] = true;
                    }
                }
            }
        }
     
        /** This method will print the array.*/
        public static void printArray(boolean[][] Matrix, int rows, int columns) {
     
            /** These loops go through every value in each row and column.*/
            for (int k = 0; k < rows; k++) {
                for (int m = 0; m < columns; m++) {
     
                    /** If false, prints a dash(-).*/
                    if (!Matrix[k][m]) {
                        System.out.print(" - ");
                    }
     
                    /** If true, prints a pound sign(#).*/
                    else {
                        System.out.print(" # ");
                    }
                }
                System.out.println(); /** New Row.*/
            }
        }
     
        public static void changeMatrix(boolean[][] initialMatrix, int rows,
                int columns, int birthLow, int birthHigh, int liveLow, int liveHigh) {
     
            boolean matrixUpdate[][] = initialMatrix.clone();
            for (int row = 0; row < initialMatrix.length; row++) {
                matrixUpdate[row] = matrixUpdate[row].clone();
     
                /** Loop traverses all rows except the first and last.*/
                for (int i = 1; i < rows - 1; i++) {
                    /** Loop traverses all columns after the first and before the last.*/
                    for (int j = 1; j < columns - 1; j++) {
     
                        /**If initMatrix was false, look to see if life can be born.*/
                        if (!initialMatrix[i][j]) {
                            int counter = 0;
                            /** Tests neighbors for life, if true, counter is incremented by 1.*/
                            if (initialMatrix[i - 1][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i - 1][j] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i - 1][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j] == true) {
                                counter = counter + 1;
                            } else {
     
                            }
     
                            /** If counter is within birth range, set that value as true. */
                            if (counter >= birthLow && counter <= birthHigh) {
                                matrixUpdate[i][j] = true;
                            }
     
                        }
     
                        /** If initMatrix was true, check if life will die.*/
                        else {
     
                            int counter2 = 0;
     
                            /** The if statements tests neighboring spots
                       for life, and if life is found the counter will increase by 1.*/
                            if (initialMatrix[i - 1][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i - 1][j] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i - 1][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j] == true) {
                                counter2 = counter2 + 1;
                            }
                            /**If counter is beyond death range then life will be eliminated.*/
                            if (counter2 >= liveHigh || counter2 <= liveLow) {
                                matrixUpdate[i][j] = false;
                            } else {
     
                            }
                        }
                    }
                }
            }
        }
    }
    Attached Files Attached Files


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    Eriosblood (September 17th, 2012)

  4. #3
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Thank you. Reading now.

  5. #4
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Even more confused now.

  6. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Did the person that suggested adding objects give any clues?
    If you don't understand my answer, don't ignore it, ask a question.

  7. #6
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Thanks for the quick reply, greatly appreciated, been working all day on this. The clues are in the file I attached in my first post.

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Sorry, I don't read attachments. Can you post what is needed here?
    If you don't understand my answer, don't ignore it, ask a question.

  9. #8
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Sure would be easier to read if your attached files were pasted to the forum rather than uploaded. I didn't (and usually never) look at attachments, but always look if it is pasted in the forum.

  10. #9
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Oh I am sorry, quite rude of me. My apologies.

    Overview
    This lab extends the game of Life assignment that was started in the Life Matrix assignment and continued in the Life Update assignment. You will convert your Life class to allow for the creation of Life objects. These objects are used by interfaces that are available in ~hutchens162/labs/life. The interfaces provide console and graphical views. You should build the methods so that they make use of the already existing functions that you wrote for earlier parts of the Life assignment.
    This part of the assignment will take the matrix built in the previous assignment and make discrete time increments to advance the state of the game.
    Specifications
    Your class will provide a constructor of seven parameters, a seed for the random number generator, the number of rows and columns in the area, the lower and upper bounds of the birth range, and the lower and upper bounds of the live range. The seed is of type long, the other parameters are int. It should initialize an object that has a matrix filled with random boolean values and retains the ranges for update processing.
    The class should provide a method, update, that advances the state by one time unit. This method has no parameters.
    The class should provide a method, world, that returns a boolean matrix that describes the current state. This method also has no parameters.
    The class should still operate as in the last assignment when started from the main method of the Life class.
    Instructions
    You should not need to modify the static methods that you wrote for earlier parts of the assignment. You should call them with appropriate parameters. However, if you did not build appropriate methods that do one thing well, you may have to redo your code to include them. Your original program should still work if you run the program starting with the main in the Life class.
    Copy the files in ~hutchens162/labs/life to your project source code using:
    cp ~hutchens162/labs/life/* .
    from inside your source code directory (where you submit from, and where Life.java is). Note that the space and dot following the * are required. Then open eclipse, select the Life project, and use the File/refresh menu command. Eclipse should update the project information to match the actual file system and thus include the new files.
    At this point, the interface files will not compile cleanly. That is because it expects to be able to use a Life object which you have not yet built. DO NOT change the interfaces. They should work after you modify the Life class.
    Your life class must have constructors, accessors, and modifiers that precisely match the requirements of the interfaces. You may not modify the interfaces. I will not take these from you when you submit. So your class must precisely interact with these interfaces so my testing will work.
    You will need to declare instance variables to hold the matrix and the two ranges (four ints). Your instance methods can then pass them as needed to the static class methods you have previously written.
    You can then write the constructor, update, and world methods as described in the Specifications section.
    The constructor has parameters that should be checked for validity. Row and column should be at least one. The range values should be between one and nine inclusive. A high value that is less than a low value is legal and specifies an empty range. If a value is not valid, you should throw an IllegalArgumentException with a string that states what the value is and why it is illegal. You can do this with code such as:
    throw new IllegalArgumentException("Row must be positive, not " + row);
    The world method should return a copy of the state matrix rather than just return the instance variable so that users of the class cannot modify the world. This is a speed versus strict protection of the representation issue. Java does not provide a mechanism to provide fast access with strict protection.
    Check your work. Have you tested your program with both interfaces? Have you included your name in the comments and expanded the comments to include a description of the problem? Did you use methods? Are their parameters clear, appropriate, and minimal? Does each method have a short comment describing what it does and perhaps pre- and post-conditions? Does the program's indenting match its control structure? Do the for loops have appropriate bounds?

    Sample Input (console interface)
    6 8
    7
    3 8
    3 8

    Sample Output (console interface)
    - - - - - - - -
    - # # # - - - -
    - # # # # - # -
    - - - # # - # -
    - # - # - # # -
    - - - - - - - -

    - - - - - - - -
    - # # # # - - -
    - # # # # # - -
    - # # # # # # -
    - - # # # # # -
    - - - - - - - -

    - - - - - - - -
    - # # # # # - -
    - # - - # # # -
    - # # - - # # -
    - # # # # # # -
    - - - - - - - -

    - - - - - - - -
    - # # # # # # -
    - # # # # # # -
    - # # # # # # -
    - # # # # # # -
    - - - - - - - -

    - - - - - - - -
    - # # # # # # -
    - # - - - - # -
    - # - - - - # -
    - # # # # # # -
    - - - - - - - -

    - - - - - - - -
    - # # # # # # -
    - # # # # # # -
    - # # # # # # -
    - # # # # # # -
    - - - - - - - -

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    The assignment looks detailed enough. Where are you having problems? Do you have any specific questions?
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    I just don't understand where to begin/what to do. Add objects to the methods? It is supposed to match up with some sort of interface? I am just quite bewildered.

  13. #12
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    These objects are used by interfaces that are available in ~hutchens162/labs/life. The interfaces provide console and graphical views. You should build the methods so that they make use of the already existing functions that you wrote for earlier parts of the Life assignment.
    Looks like ~hutchens162/labs/life is a good place to look for starters.

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Make a list of the what's in the Specification section and code them one by one:
    1) Your class will provide a constructor of seven parameters, ....
    2) The class should provide a method, update, that advances the state by one time unit. This method has no parameters.
    ETC
    If you don't understand my answer, don't ignore it, ask a question.

  15. #14
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Copied the files in ~hutchens162/labs/life and now I have.
    import java.util.Scanner;
     
     
    public class Console {
     
    	/**
    	 * @param args unused
    	 */
    	public static void main(String[] args) {
    		Scanner in = new Scanner(System.in);
    		System.out.println("Please enter the size of the matrix(rows, columns) :");
    		int rows = in.nextInt();
    		int columns = in.nextInt();
    		System.out.println("Please enter random seed: ");
    		long seed = in.nextLong();
    		System.out.println("Please enter birth range (low, high) :");
    		int birthLow = in.nextInt();
    		int birthHigh = in.nextInt();
    		System.out.println("Please enter live range (low, high): ");
    		int liveLow = in.nextInt();
    		int liveHigh = in.nextInt();
    		try {
    			Life game = new Life(seed, rows, columns, birthLow, birthHigh, liveLow, liveHigh);
    			playLife(game);
    		} catch (IllegalArgumentException e) {
    			System.out.println("Inappropriate values: " + e.getMessage());
    		}
    	}
     
    	/**
    	 * Print a boolean matrix
    	 * @param world is a boolean matrix to be printed with # for true and - for false.
    	 */
    	public static void printWorld(boolean[][] matrix) {
    		for (int r=0; r<matrix.length; r++) {
    			for (int c=0; c<matrix[0].length; c++) {
    				System.out.print(matrix[r][c] ? " # " : " - ");
    			}
    			System.out.println();
    		}
    		System.out.println();
     
    	}
     
    	/**
    	 * Play the game of Life starting with a given state
    	 * @param game is the Life object that provides the current state of Life
    	 */
    	public static void playLife(Life game) {
    		printWorld(game.world());
    		for (int i=0; i<10; i++) {
    			game.update();
    			printWorld(game.world());
    		}
    	}
     
    }

    As well as
    /**
     * Graphical is the startup class and controller for 
     * the java swing version of Life.
     * @author David Hutchens
     * @date August 2008
     */
     
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
     
     
    public class Graphical extends JPanel implements ActionListener, ChangeListener {
    	private static Graphical sharedApp = null;
    	private static final long serialVersionUID = 1L;
    	private static final int squareSize = 5;
    	private static final int borderSize = 5;
     
    	private static final String runButtonText = "Run";
    	private static final String birthMinSliderName = "Birth Minimum";
    	private static final String birthMaxSliderName = "Birth Maximum";
    	private static final String liveMinSliderName = "Live Minimum";
    	private static final String liveMaxSliderName = "Live Maximum";
     
    	private Timer myTimer;
    	private JFrame theFrame;
    	private Life myLife;
    	private int birthMin, birthMax, liveMin, liveMax;
     
    	/**
    	 * Constructs the object, creating the model and view (with the
    	 * frames and widgets) and starts the timer.
    	 */
    	private Graphical() {
    		//Set the look and feel (for Macs too).
    		if (System.getProperty("mrj.version") != null) {
    			System.setProperty("apple.laf.useScreenMenuBar","true");
    		}
    		JFrame.setDefaultLookAndFeelDecorated(true);
     
    		myLife = null;
    		birthMin = 4;
    		birthMax = 6;
    		liveMin = 3;
    		liveMax = 5;
     
    		theFrame = new JFrame("Life");
    		theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		JPanel widgetPanel = setupLayout();
    		theFrame.getContentPane().add(widgetPanel, BorderLayout.CENTER);
    		//createTextItems(widgetPanel);
    		createButtons(widgetPanel);
     
    		theFrame.pack();
    		theFrame.setVisible(true);
     
    		myTimer = new Timer(1000, this);
    		myTimer.start();
     
    	}
     
    	/**
    	 * Set up the layout for the interface
    	 * @return returns the JPanel that will hold the widgets and this UI
    	 */
    	private JPanel setupLayout() {
    		JPanel widgetPanel = new JPanel();
    		widgetPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    		widgetPanel.setLayout(new BoxLayout(widgetPanel, BoxLayout.PAGE_AXIS));
    		widgetPanel.add(this);
     
    		Dimension puzzleDrawingSize = new Dimension(100*squareSize + 2*borderSize, 100*squareSize + 2*borderSize);
    		setMinimumSize(puzzleDrawingSize);
    		setPreferredSize(puzzleDrawingSize);
    		setMaximumSize(puzzleDrawingSize);
    		setBorder(BorderFactory.createLineBorder(Color.lightGray, 2));
    		return widgetPanel;
    	}
     
    	/**
    	 * Creates the buttons to control action.
    	 * @param widgetPanel is the JPanel that will hold the buttons.
    	 */
    	private void createButtons(JPanel widgetPanel) {
    		JButton runButton = new JButton(runButtonText);
    		runButton.addActionListener(this);
    		widgetPanel.add(runButton);
    		runButton.setAlignmentX(CENTER_ALIGNMENT);
    		createSlider(widgetPanel, birthMinSliderName, birthMin);
    		createSlider(widgetPanel, birthMaxSliderName, birthMax);
    		createSlider(widgetPanel, liveMinSliderName, liveMin);
    		createSlider(widgetPanel, liveMaxSliderName, liveMax);
    	}
     
    	/**
    	 * Creates a slider and adds it to the widgetPanel with a label
    	 * @param widgetPanel panel that will contain the slider
    	 * @param name of the slider
    	 * @param initialValue of the slider
    	 */
    	private void createSlider(JPanel widgetPanel, String name, int initialValue) {
    		JPanel p = new JPanel();
    		p.setAlignmentX(CENTER_ALIGNMENT);
    		p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
    		widgetPanel.add(p);
     
    		JLabel inputLabel = new JLabel();
    		p.add(inputLabel);
    		inputLabel.setText(name);
    		inputLabel.setAlignmentX(RIGHT_ALIGNMENT);
     
    		JSlider js = new JSlider(JSlider.HORIZONTAL, 0, 9, initialValue);
    		js.setName(name);
    		js.addChangeListener(this);
    		js.setMajorTickSpacing(1);
    		js.setMinorTickSpacing(1);
    		js.setPaintTicks(true);
    		js.setPaintLabels(true);
    		js.setSnapToTicks(true);
    		p.add(js);
    	}
     
    	/**
    	 * Sets the sizes based on the current world.
    	 * @parm boolean [][] world is the description of the world to be displayed
    	 */
    	public void setSizes(boolean [][] world) {
    		Dimension puzzleDrawingSize = new Dimension (world[0].length*squareSize + borderSize*2,
    				world.length*squareSize + borderSize*2);
    		setMinimumSize(puzzleDrawingSize);
    		setPreferredSize(puzzleDrawingSize);
    		setMaximumSize(puzzleDrawingSize);
    		revalidate();
    		theFrame.pack();
    	}
     
     
    	/**
    	 * Draws the painted portions when requested.
    	 * @param Graphics gc the graphics context in which to draw 
    	 */
    	public void paintComponent(Graphics gc) { 
    		if (isOpaque()) { //paint background
    			gc.setColor(getBackground());
    			gc.fillRect(0, 0, getWidth(), getHeight());
    		}
    		if (myLife == null) {
    			return;
    		}
     
    		gc.translate(borderSize, borderSize);
    		boolean [][] world = myLife.world();
    		Color liveColor = new Color(87, 207, 40);
    		Color deadColor = new Color(240, 240, 240);
    		for (int i = 0; i < world.length; i++) {
    			for (int j = 0; j < world[0].length; j++) {
    				if (world[i][j]) {
    					gc.setColor(liveColor);	
    				} else {
    					gc.setColor(deadColor); 	
    				}
    				gc.fillRect(j*squareSize, i*squareSize, squareSize, squareSize);
    			}
    		}
    		gc.translate(-borderSize, -borderSize);
    	}
     
    	/*
    	 * (non-Javadoc)
    	 * @see javax.swing.event.ChangeListener#stateChanged(javax.swing.event.ChangeEvent)
    	 */
    	public void stateChanged(ChangeEvent ce) {
    	    JSlider source = (JSlider)ce.getSource();
    	    if (!source.getValueIsAdjusting()) {
    	        int value = (int)source.getValue();
    	        if (source.getName().equals(birthMinSliderName)) {
    	        	birthMin = value;
    	        } else if (source.getName().equals(birthMaxSliderName)) {
    	        	birthMax = value;
    	        } else if (source.getName().equals(liveMinSliderName)) {
    	        	liveMin = value;
    	        } else if (source.getName().equals(liveMaxSliderName)) {
    	        	liveMax = value;
    	        } else {
    	        	System.out.println("Unknown stateChange source");
    	        }
    	    }
    	}
     
    	/**
    	 * Perform actions depending which widget was selected.
    	 * Determines which sort of widget was selected and bases action on its name.
    	 * Currently has actions for the find word button and the open puzzle menu.
    	 * @param se the selection event including the source of the event
    	 */
    	public void actionPerformed(ActionEvent se) {
    		String command = se.getActionCommand();
    		if (se.getSource() == myTimer) {
    			if (myLife != null) {
    				myLife.update();
    				repaint();
    			}
    		} else if (command.equals(runButtonText)) {
    			myLife = new Life(System.currentTimeMillis(), 100, 100, birthMin, birthMax, liveMin, liveMax);
    			setSizes(myLife.world());
    			repaint();
    		} else {
    			System.out.println("Unknown action: " + command);
    		}
    	}
     
    	/**
    	 * Creates (if necessary) and returns the singleton instance
    	 * @return the singleton shared instance
    	 */
    	public static Graphical sharedInstance() {
    		if (sharedApp == null) {
    			sharedApp = new Graphical();
    		}
    		return sharedApp;
    	}
     
    	/**
    	 * Starts the graphical interface
    	 * @param args ignored
    	 */
    	public static void main(String[] args) {
    		javax.swing.SwingUtilities.invokeLater(
    				new Runnable() {
    					public void run() {
    						sharedInstance();
    					}
    				}
    		);
     
    	}
     
    }

  16. #15
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Should I get rid of the println statements that are asking for the rows/colums/seeds/birthHigh etc? Since I am passing parameters to the construct? I also really have no idea how to increment the time nor how to use the boolean matrix in the method world to describe the current state.
    import java.util.Random;
    import java.util.Scanner;
     
     
    /**This program creates a random matrix of life that exists in specific dimensions.*/
    public class Life {
        public Life(long seed, int rows, int columns, int birthLow, int birthHigh,
    			int liveLow, int liveHigh) {
     
    	}
     
    	/**This method asks for user input and calls the initializing and printing
        methods.*/ 
        public static void main(String[] args) {
     
            Scanner console = new Scanner(System.in); /**New Scanner*/
     
            System.out.println("Number of rows?");
            int rows = console.nextInt(); /** Saves input as number of rows.*/
     
            System.out.println("Number of columns?");
            int columns = console.nextInt(); /** Saves input as number of columns.*/
     
            System.out.println("Seed number?");
            long seed = console.nextLong(); /** Saves input as number of seed.*/
     
            System.out.println("Birth minimum?");
            int birthLow = console.nextInt(); /** Saves input as minimum number for birth.*/
     
            System.out.println("Birth maximum?");
            int birthHigh = console.nextInt(); /** Saves input as maximum number for birth.*/
     
            System.out.println("Minimum Life?");
            int liveLow = console.nextInt(); /** Saves input as minimum number for death.*/
     
            System.out.println("Maximum Life?");
            int liveHigh = console.nextInt(); /** Saves input as maximum number for death.*/
     
            boolean newMatrix[][] = new boolean[rows][columns]; 
            /** Creates boolean array according to dimensions entered.*/
     
     
     
            array(newMatrix, rows, columns, seed); /** Calls the matrix initializing method.*/
     
            printArray(newMatrix, rows, columns); /** Calls the array printing method.*/
     
            System.out.println();
     
            for(int i=0; i<4; i++){
     
                changeMatrix(newMatrix, rows, columns, birthLow, birthHigh, liveLow, liveHigh);
                printArray(newMatrix, rows, columns);
                System.out.println();
            }
     
        }
     
        /** This method sets the matrix with true and false values.*/
        public static void array(boolean[][] Matrix, int rows, int columns,
                long seed) {
     
            Random generator = new Random(seed); /**Random number generated according to seed input.*/
     
            /** Loop traverses every row after first and before the last.*/
                   for (int i = 1; i < rows - 1; i++) {
                /** Loop traverses every column after first and before last.*/
                for (int j = 1; j < columns - 1; j++) {
     
                    /** Will generate a random boolean value.*/
                    boolean x = generator.nextBoolean();
     
                    /** If x is false, sets the array location as false.*/
                    if (!x) {
                        Matrix[i][j] = false;
     
                    }
     
                    /** If x is true, sets the array location as true.*/
                    else {
                        Matrix[i][j] = true;
                    }
                }
            }
        }
     
        /** This method will print the array.*/
        public static void printArray(boolean[][] Matrix, int rows, int columns) {
     
            /** These loops go through every value in each row and column.*/
            for (int k = 0; k < rows; k++) {
                for (int m = 0; m < columns; m++) {
     
                    /** If false, prints a dash(-).*/
                    if (!Matrix[k][m]) {
                        System.out.print(" - ");
                    }
     
                    /** If true, prints a pound sign(#).*/
                    else {
                        System.out.print(" # ");
                    }
                }
                System.out.println(); /** New Row.*/
            }
        }
     
        public static void changeMatrix(boolean[][] initialMatrix, int rows,
                int columns, int birthLow, int birthHigh, int liveLow, int liveHigh) {
     
            boolean matrixUpdate[][] = initialMatrix.clone();
            for (int row = 0; row < initialMatrix.length; row++) {
                matrixUpdate[row] = matrixUpdate[row].clone();
     
                /** Loop traverses all rows except the first and last.*/
                for (int i = 1; i < rows - 1; i++) {
                    /** Loop traverses all columns after the first and before the last.*/
                    for (int j = 1; j < columns - 1; j++) {
     
                        /**If initMatrix was false, look to see if life can be born.*/
                        if (!initialMatrix[i][j]) {
                            int counter = 0;
                            /** Tests neighbors for life, if true, counter is incremented by 1.*/
                            if (initialMatrix[i - 1][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i - 1][j] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i - 1][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j + 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j - 1] == true) {
                                counter = counter + 1;
                            }
                            if (initialMatrix[i + 1][j] == true) {
                                counter = counter + 1;
                            } else {
     
                            }
     
                            /** If counter is within birth range, set that value as true. */
                            if (counter >= birthLow && counter <= birthHigh) {
                                matrixUpdate[i][j] = true;
                            }
     
                        }
     
                        /** If initMatrix was true, check if life will die.*/
                        else {
     
                            int counter2 = 0;
     
                            /** The if statements tests neighboring spots
                       for life, and if life is found the counter will increase by 1.*/
                            if (initialMatrix[i - 1][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i - 1][j] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i - 1][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j + 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j - 1] == true) {
                                counter2 = counter2 + 1;
                            }
                            if (initialMatrix[i + 1][j] == true) {
                                counter2 = counter2 + 1;
                            }
                            /**If counter is beyond death range then life will be eliminated.*/
                            if (counter2 >= liveHigh || counter2 <= liveLow) {
                                matrixUpdate[i][j] = false;
                            } else {
     
                            }
                        }
                    }
                }
            }
        }
     
    	public boolean[][] world() {
    		// TODO Auto-generated method stub
    		return null;
    	}
     
    	public void update() {
    		// TODO Auto-generated method stub
     
    	}
    }

  17. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    how to increment the time
    Create a skeleton for the method and leave how to do the increment until later.

    Is the Console class to be the starting point for the program now? It has a main() method.
    If so you can get rid of your main() method.

    how to use the boolean matrix
    Your code has a boolean matrix: boolean newMatrix[][]
    what is it used for?
    If you don't understand my answer, don't ignore it, ask a question.

  18. #17
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Quote Originally Posted by Norm View Post
    Create a skeleton for the method and leave how to do the increment until later.

    Is the Console class to be the starting point for the program now? It has a main() method.
    If so you can get rid of your main() method.



    Your code has a boolean matrix: boolean newMatrix[][]
    what is it used for?
    I believe it will be used from the console class, I am not entirely sure. I am hardly experienced with java and just got thrown into the language with hardly any good verbal explanation in class. Trying to salvage any points I can for this lab.

    As for the boolean, I think it is used because it says, "The class should provide a method, world, that returns a boolean matrix that describes the current state. This method also has no parameters."

  19. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    The code you posted in post#1 has this line:
            boolean newMatrix[][] = new boolean[rows][columns];
    so your code already uses a boolean matrix.

    Again define a skeleton method and fill in the details later.

    The first objective is to get a clean compile with the Console class which calls the methods specified in the Specifications section.
    Then work through the logic for each method so it does what is needed.
    Last edited by Norm; September 17th, 2012 at 08:55 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  20. #19
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Quote Originally Posted by Norm View Post
    The code you posted in post#1 has this line:
            boolean newMatrix[][] = new boolean[rows][columns];
    so your code already uses a boolean matrix.
    That is to create an array of true/false values depending on whether or not life exists in those areas. If true it will be a '#' and false a '-'.

  21. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    I don't understand why you are having a problem with something you already have used in your code.
    If you don't understand my answer, don't ignore it, ask a question.

  22. #21
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    I just do not understand what I am supposed to write and change, this is all foreign to me I just began this class and have been looking at this all night. Extremely stressed. Due within the hour and doesn't look like it is going to be completed. Thanks for the help.

  23. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Due within the hour and doesn't look like it is going to be completed.
    You're right there. You got started too late this time. Maybe next time give it a little more time.
    If you don't understand my answer, don't ignore it, ask a question.

  24. #23
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Ahhhh I do not want to be an inconvenience and ask for the code but maybe an outline or something, I'm desperate

  25. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,321
    Thanks
    49
    Thanked 2,194 Times in 2,167 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    Does the code compile yet?
    If you don't understand my answer, don't ignore it, ask a question.

  26. #25
    Member
    Join Date
    Sep 2012
    Posts
    35
    My Mood
    Lurking
    Thanks
    9
    Thanked 0 Times in 0 Posts

    Default Re: Game of Life, help with Array Object? Quite puzzled

    When compiled from console I get this.

    Exception in thread "main" java.lang.NullPointerException
    at Console.printWorld(Console.java:41)
    at Console.playLife(Console.java:56)
    at Console.main(Console.java:30)

Page 1 of 2 12 LastLast

Similar Threads

  1. Game of Life 2-D matrix random seed boolean array PLEASE
    By Eriosblood in forum Collections and Generics
    Replies: 20
    Last Post: September 3rd, 2012, 06:10 PM
  2. [SOLVED] Pass-by-Value scheme, puzzled with passing/assigning a reference to another object
    By chronoz13 in forum Java Theory & Questions
    Replies: 10
    Last Post: June 2nd, 2012, 10:43 AM
  3. Read in file and store in 2D array start of The Game of Life
    By shipwills in forum What's Wrong With My Code?
    Replies: 3
    Last Post: March 2nd, 2011, 08:52 AM
  4. Game of Life GUI Error
    By Lavace in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 3rd, 2011, 08:15 AM
  5. Replies: 1
    Last Post: March 28th, 2009, 07:21 AM