This site requires JavaScript, please enable it in your browser!
Greenfoot back
Amanda92
Amanda92 wrote ...

2012/12/11

HELP understanding code needed plz

Amanda92 Amanda92

2012/12/11

#
Hello everybody I have got the code below for "the game of life" from greenfoot website but I'm having some problems understanding all the code, would it be possible to get some help in answering my questions? if it's ok I'll start with a couple of Qs then I can continue if anybody responds. Any help or comment is appreciated Here is the code for the WORLD which is the only place where the code is written & there is no actors at all:
import greenfoot.Greenfoot;
import greenfoot.GreenfootImage;
import greenfoot.MouseInfo;
import greenfoot.World;

import java.awt.Color;

import javax.swing.JOptionPane;

/**
 * The only class in 'Ninto's Game of Life'.
 * <br><i>//Made with the rules and gameplay from John Conway's 'Conway's Game of Life' </i>(C).
 * <br><i>//Inspiration from tkiesel's <a href="http://greenfootgallery.org/scenarios/663">'Conway's Game of Life'</a></i>.
 * <br><i>//Chack also <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Wikipedia's entry to 'Conway's Game of Life'</a> out</i>.
 * <br>
 * <br>This game simulates the life of a lot of cells, that are "dead"(white) or "alive"(black).
 * <br>
 * <br>Rules:
 * <ul type=1>
 * <li>Any live cell with fewer than two live neighbours dies, as if by needs caused by underpopulation.
 * <li>Any live cell with more than three live neighbours dies, as if by overcrowding.
 * <li>Any live cell with two or three live neighbours lives, unchanged, to the next generation.
 * <li>Any dead cell with exactly three live neighbours becomes a live cell.
 * </ul>
 * Controls:
 * <br>-space = run.
 * <br>-a = act once and stop.
 * <br>-c = kill all cells (clear).
 * <br>-r = randomize all cells.
 * 
 * @author Ninto
 * @version 0.1
 */
public class CellWorld extends World
{
    /**The images symbolising alive and dead cells*/
    private final GreenfootImage ALIVE, DEAD;
    /**The position of the mouse*/
    private static int mx, my;
    /**State booleans*/
    private boolean running, adding, removing;
    /**All the cells*/
    private boolean[][] cells, input;
    
    /**
     * Constructor.
     */
    public CellWorld() {
        super(48, 32, 10);
        if(JOptionPane.showConfirmDialog(null, "Do you want a visible grid?", "Question", JOptionPane.YES_NO_OPTION)== 0) {
            getBackground().setColor(Color.LIGHT_GRAY);
            getBackground().fill();
            ALIVE = new GreenfootImage(9, 9);
            DEAD = new GreenfootImage(9, 9);
        }
        else {
            ALIVE = new GreenfootImage(10, 10);
            DEAD = new GreenfootImage(10, 10);
        }
        ALIVE.fill();
        DEAD.setColor(Color.WHITE);
        DEAD.fill();
        printWelcome();
        update();
        Greenfoot.setSpeed(100);
        Greenfoot.start();
    }
    
    /**
     * Action-method.
     */
    public void act() {
        if(running) {
            for(int y=0; y<cells[0].length; y++) for(int x=0; x<cells.length; x++) {
                int n = numberOfNeighbours(x, y);
                if(cells[x][y]) {
                    if(n != 2 && n != 3) input[x][y]= false;
                }
                else if(n == 3) input[x][y]= true;
            }
        }
        for(int y=0; y<cells[0].length; y++) for(int x=0; x<cells.length; x++) cells[x][y]= input[x][y];
        checkMouse();
        update();
    }
    
    /**
     * Check input stuff.
     */
    private void checkMouse() {
        String key = Greenfoot.getKey();
        if(key != null) {
            if(key.equals("space")) running = !running;
            if(key.equalsIgnoreCase("a")) {
                running = true;
                act();
                running = false;
            }
            if(key.equalsIgnoreCase("r")) randomize();
            if(key.equalsIgnoreCase("c")) clear();
        }
        if(Greenfoot.getMouseInfo()!= null) {
            mx = Greenfoot.getMouseInfo().getX();
            my = Greenfoot.getMouseInfo().getY();
        }
        if(Greenfoot.mousePressed(null)) {
            MouseInfo mouse = Greenfoot.getMouseInfo();
            if(mouse.getButton()== 1) adding = true;
            if(mouse.getButton()== 3) removing = true;
        }
        if(Greenfoot.mouseClicked(null)) {
            MouseInfo mouse = Greenfoot.getMouseInfo();
            if(mouse.getButton()== 1) adding = false;
            if(mouse.getButton()== 3) removing = false;
        }
        if(adding && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <= cells[0].length-1) input[mx][my]= true;
        if(removing && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <=  cells[0].length-1) input[mx][my]= false;
    }
    
    /**
     * Randomize the state of all cells.
     */
    private void randomize() {
        cells = new boolean[getWidth()][getHeight()];
        input = new boolean[getWidth()][getHeight()];
        for(int y=0; y<cells[0].length; y++) for(int x=0; x<cells.length; x++) {
            cells[x][y]= Greenfoot.getRandomNumber(2)== 1;
            input[x][y]= cells[x][y];
        }
    }
    
    /**
     * Kill all cells.
     */
    private void clear() {
        cells = new boolean[getWidth()][getHeight()];
        input = new boolean[getWidth()][getHeight()];
    }
    
    /**
     * Update the background image.
     */
    private void update() {
        GreenfootImage bg = getBackground();
        for(int y=0; y<cells[0].length; y++) for(int x=0; x<cells.length; x++) {
            if(cells[x][y]) bg.drawImage(ALIVE, x*10, y*10);
            else bg.drawImage(DEAD, x*10, y*10);
        }
    }
    
    /**
     * Get the number of all alive cells around this spot.
     * 
     * @param x The x-coordinate.
     * @param y The y-coordinate.
     * @return The number of all alive cells around this spot.
     */
    private int numberOfNeighbours(int x, int y) {
        int r = x+1, l = x-1, d = y+1, u = y-1;
        if(r > cells.length-1) r = 0;
        if(l < 0) l = cells.length-1;
        if(d > cells[0].length-1) d = 0;
        if(u < 0) u = cells[0].length-1;
        int n = 0;
        if(cells[r][y]) n++;
        if(cells[l][y]) n++;
        if(cells[x][d]) n++;
        if(cells[x][u]) n++;
        if(cells[r][d]) n++;
        if(cells[r][u]) n++;
        if(cells[l][d]) n++;
        if(cells[l][u]) n++;
        return n;
    }
    
    /**
     * Build a cell-collection at the specified point.
     */
    private void build(int xx, int yy, int[][] code) {
        int width = code[0].length, height = code.length;
        if(xx<0 || xx>cells.length-width || yy<0 || yy>cells[0].length-height) return;
        for(int y=0; y<height; y++) for(int x=0; x<width; x++) input[xx+x][yy+y]= code[y][x]== 1;
    }
    
    private void printWelcome() {
        cells = new boolean[getWidth()][getHeight()];
        input = new boolean[getWidth()][getHeight()];
        int[][] message = {
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
            {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };
        build(0, 0, message);
        System.out.println("Welcome to 'Ninto's Game of Life'\n//Made with the rules and gameplay from John Conway's 'Conway's Game of Life'(c)");
    }
}
The first two questions are: 1- why are we importing: javax.swing.JOptionPane and what does it do or mean? and in declaring the variables why are we using "final" with ALIVE, DEAD and "static" with int my, my while other are boolean? 2- is there a possible short easy to understand explanation for the act method? Thanks in advance
danpost danpost

2012/12/11

#
(1) (a) importing javax.swing.JOptionPane: To run the JOptionPane that asks if the user wants to see the grid or not. (1) (b) variables declared "final": not neccessary for this scenario; but protects the objects from being changed once they are set. (c) "static" int and boolean: I do not think that mx and my should be declared here at all since they are assigned new values every time the checkMouse method is called and not used anywhere else but in that method (they should probably be declared as local variables within the method). Since I was not quite sure what you were trying to ask about, I will also add this: 'int' variables hold integer numeric values while booleans only hold a true/false value. (2) the act method: the first double 'for' loop fills an array with future values for all the cells; the other double 'for' loop changes the cell array with the new values. The 'update' method changes the screen to reflect the new cell array values. I am not sure, but 'cells = input;' may be an appropriate substitution for the second double 'for' loop.
Amanda92 Amanda92

2012/12/11

#
Thank you for your fast answer, it was helpful all understood except for the declaration for dx,, dy, where should i put them exactly coz when I tried the mouse method I got this erros (illiga start of expresstion) Now if it's ok the next questions which mostly concern the check mouse method 1- what does the mean and why are we declaring it here / String key = Greenfoot.getKey(); 2- I don't get this at all, first there is no else, second in 3 IFs are we saying same thing !null, !running? and how does running = !running and then the key "a" doing same what "space" does? this part is really confusing
if(key != null) 
        {
            if(key.equals("space")) running = !running;
            if(key.equalsIgnoreCase("a")) 
            {
                running = true;
                act();
                running = false;
            }

        }
3- I almost get the conditions for the mouse buttons the only wondering is what are ==1 & ==3, another thing is what are the differences between "clicked" and "pressed" is it important or just to make it easier when adding & removing cells in the beginning ? last thing about this method -if not too much to ask- is brief explanation for this:
if(adding && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <= cells[0].length-1) input[mx][my]= true;
        if(removing && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <=  cells[0].length-1) input[mx][my]= false;
P.S I understand the concept & idea & what is it doing I just need to understand HOW it's working
danpost danpost

2012/12/11

#
(Prev) remove line 39 and insert at line 91 'int mx, my;'. (1) String key: the 'getKey' method returns the last key pressed and release. Greenfoot does not keep a record of the key once it is returned, so to do multiple checks on its return value, it must be saved to a variable (aka field). The breakdown of the statement is 'get the last key (pressed and) released and assign its value to a new String variable using the name key'. (2) (a) (i) The first 'if': checks the value of the return of 'getKey' for 'null', before trying to check the internal 'if' conditions on that value. As I mentioned in (1) above, Greenfoot does not remember to key that is returned with 'getKey'; a second call to it (immediately) will return 'null', as will it do if no key has been (pressed and) released. (ii) The second 'if': acts as a swith; allowing the 'space' key to turn on and off the running execution of the life cycles. See (b) below for more details. (iii) The third 'if': allows the user to press the 'a' key to have one life cycle process take place. (b) running = !running: the variable 'running' holds a boolean (true/false) value; this statement says 'take the value of 'running', 'not' it, and assign this new value to 'running'; if 'running' was true, is will now be 'false', and if 'running' was false, is will now be 'true'. (c) 'a' and 'space': explained in (2)(a)(ii) and (iii) above. (3) (a) ==1 & ==3: refer to the documentation for the MouseInfo class in the greenfoot package. 'getButton' returns '1' for the left mouse button and '3' for the right mouse button. (b) 'Clicked' and 'Pressed': yes; 'Pressed' becomes 'true' when a mouse button is pressed and 'Clicked' becomes 'true' when a mouse button is released. Using the different mouse button to add and remove active cells is the programmer's choice (I would have just had one button, check for 'Click', to toggle the state of the cell). The usage of 'Pressed' and 'Clicked' in the code above is probably not the best way to handle what was being done; it will cause the action to occur repeatedly until the mouse button is released. (Last) the two statements check for which action was detected, if any (determined by which mouse button is currently down), and if the mouse is actually on a cell, before doing the appropriate action. I hope this helped.
Amanda92 Amanda92

2012/12/11

#
Hey That was so much help thanks a lot, it took me a while but finally I could wrap my head around it thanks to your explanation and to my brain. the only thing before we move on is the last two statements I understood them perfectly from your explanation but I just need to get the code itself like
 if(removing && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <=  cells[0].length-1) input[mx][my]= false;
can we plz take it in small pieces like (mx >= 0) does this mean where is the coordinate for the mouse & zero is outside the world? also (mx<=cells.length-1) does length here is the length of the world? and why -1 ?? Now the update part
/** 
     * Update the background image. 
     */  
    private void update() {  
        GreenfootImage bg = getBackground();  
        for(int y=0; y<cells[0].length; y++) for(int x=0; x<cells.length; x++) {  
            if(cells[x][y]) bg.drawImage(ALIVE, x*10, y*10);  
            else bg.drawImage(DEAD, x*10, y*10);  
        }  
    }
By the look at it we are just updating the background with the added and removed cells, my questions are: 1) Does this update is what helps the game go infinity always updating from life cycle to another? 2) The if statement are we first checking if cells are alive then draw live cell but why multiplication by 10? 3) Are the for loops just to determine where the cells that are already excited are? Is this part is the most important one? I mean is it here where the rules for the game are implemented because I don't seem to understand anything of it, it says that it gets the number of all alive cells around this spot, but what spot????
/**
     * Get the number of all alive cells around this spot.
     * 
     * @param x The x-coordinate.
     * @param y The y-coordinate.
     * @return The number of all alive cells around this spot.
     */
    private int numberOfNeighbours(int x, int y) 
    {
        int r = x+1, l = x-1, d = y+1, u = y-1;
        if(r > cells.length-1) r = 0;
        if(l < 0) l = cells.length-1;
        if(d > cells[0].length-1) d = 0;
        if(u < 0) u = cells[0].length-1;
        int n = 0;
        if(cells[r][y]) n++;
        if(cells[l][y]) n++;
        if(cells[x][d]) n++;
        if(cells[x][u]) n++;
        if(cells[r][d]) n++;
        if(cells[r][u]) n++;
        if(cells[l][d]) n++;
        if(cells[l][u]) n++;
        return n;
    }
Thanks again :)
danpost danpost

2012/12/11

#
if(removing && mx >= 0 && mx <= cells.length-1 && my >= 0 && my <=  cells[0].length-1) input[mx][my]= false;
Remember that 'mx' and 'my' are the world coordinates at which the mouse was clicked; and if you look at the conditions, they are being compared to '0' and the dimensions of the 'cells' array, which correspond to the cells in the world. In Java, counting starts at zero, and ends at one less than the number of items (which gives a total number of items equal to the number of items). Therefore, by making sure that 'mx' and 'my' are equal to or greater than zero and less than the number of elements in the array (or less than or equal to one less than the number of elements) in its dimension, we ensure that the mouse was clicked on a cell. (1) 'update' method: no; only the act method will be executed repeatedly by the running of the simulation, which can call upon other methods to execute. When a scenario compiles, only the world constructor will execute. When the scenario is started, the 'started()' method (if over-riden) will execute first, the all objects (all actor objects and the world object) will have their act methods executed, in turn, and repeatedly. This is what keeps the simulation going. (2) with the particular scenario you are getting this code from, there are no Cell objects; only images on the background image that represent the cells. The two images are created in the constructor of the world; and to place these images in the world, they must be placed at intervals apart from each other; hence the multiplication by 10. The 'if' is only checking the current state of the cell at that location by looking at the boolean value in the 'cells' array, to determine which image to draw. (3) the 'for' loops are to iterate through all the cells that are represented in the world, to draw the new image of each and every cell in the background. (Rules) The rules are not implemented here. This method is, however, used to get the information that is needed for the rules to be applied. The first four 'if's within the method implement a 'wrapping' technique where cells on one edge of the grid are considered neighbours of the cells on the opposite side of the grid.
      [l][u]   [ ][u]   [r][u]
      [l][ ]   [ ][ ]   [r][ ]
      [l][d]   [ ][d]   [r][d]
The above represents a cell () with its neighbours. If any of the cells considered to be a neighbor have an 'on' state ('true') in the 'cells' array then the count (of 'n') is incremented. Lines 76 through 79 is where the implementation of the rules is located.
jabirfatah91 jabirfatah91

2012/12/11

#
Where did u find the code from line 189 to 220???
Amanda92 Amanda92

2012/12/11

#
So if the rules are in the code below 76 to 79, can we explain it like this? first if: if the cells is inside the world then second if: if the cell doesn't have 2 or 3 neighbors dies else it lives? (this doesn't sound right :(
 if(cells[x][y]) {  
                    if(n != 2 && n != 3) input[x][y]= false;  
                }  
                else if(n == 3) input[x][y]= true; 
Hopefully the last part of code with questions is:
 /**
     * Build a cell-collection at the specified point.
     */
    private void build(int xx, int yy, int[][] code) 
    {
        int width = code[0].length, height = code.length;
        if(xx<0 || xx>cells.length-width || yy<0 || yy>cells[0].length-height)
        return;
        for(int y=0; y<height; y++) for(int x=0; x<width; x++)
        input[xx+x][yy+y]= code[y][x]== 1;
    }
building the cell after the conditions or rules are implemented? 1) here we are giving width & height for world? int width = code.length, height = code.length; if so then why are we starting at 0 but finishing at code.length not code.length-1 2) return what? 3) is the for loop here to check if there are no cells in the world ? what does x,y refer to here? 4) didn't get this one completely input= code== 1; just one last thing, as for the printWelcome method I understand for what it is used, I can even change with 1s & 0s and it's changing when I compile, the question is whether if there is something to understand more? like is "int message" here is an array to write the message inside? and what is build(0, 0, message); at last? Thanks for your patience and time spending answering my questions, really appreciate it.
Amanda92 Amanda92

2012/12/11

#
jabirfatah91, I got it from scenario here on greenfoot
danpost danpost

2012/12/12

#
First if: if activecell, then turn off if not two or three active neighbours, else (if not activecell), turn on if exactly three active neighbours. Remember, the 'cells' array hold the state of each cell (true/false). (Build method) This method has nothing to do with implemention of the rules of the Game of Life. It is only used to create the welcome message. It is called from the constructor before calling 'update' which does the displaying of the new boolean dataset representing the message. At least that what it appears to do; but I cannot for the life of me see where the world instance 'code' array is set to the 'input' array (it is not the same as the local 'code' array created by way of the parameter in the 'build' method). (1) width and height are the dimensions of the 'message' array. Since we are taking the difference between one index in one array with antoher index in another array ('cells') the 'minus one' part cancel out. The 'if' condition seems to be ensuring that the welcome message will fit within the dimensions of the cell array and exits the method if it does not. (2) the 'return;' statement causes an immediate exit from the method at the point it is executed at. If the method was not of 'void' type, but of, say, 'int' type, an integers must be included in the statement (like: return -1;). (3) the x and y interate from zero to the dimensions of the 'message' array (see (1) above), working with each element in the 'message' array. (4) the elements in the 'input' array are being set to a boolean value which is determined by the comparison (code == 1). The local 'code' array contains 'int' values of zero and one (from the 'message' array). (Last) I hope these are answered by the above.
Amanda92 Amanda92

2012/12/12

#
Thank you very much that seems about it, so just to clarify the 0,0 here
build(0, 0, message)
are the coordinate where the message should be written or what?
danpost danpost

2012/12/12

#
Yes, the (0, 0) are the top-left coordinates of the cell at which the message is to start.
Amanda92 Amanda92

2012/12/12

#
thanks a lot
You need to login to post a reply.