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

2012/12/7

Hi friends! Please explain some codes.

hkrhässleholm hkrhässleholm

2012/12/7

#
I am about to do a project "Conway's game of life". This codes are from an existing scenerio of "Conway's game of life" at this website. I am gonna mention the codes of World class of this scenerio (http://www.greenfoot.org/scenarios/1336)
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;

/**
 * The Grid consists of the lines and cells of the CA.
 * 
 * @David Brown
 * @03/16/2010
 */
public class CellularAutomata extends World
{
    private GreenfootImage  myGrid;
    private Cell[][]        myCells;
    private int             myWidth, myHeight, myCellSize;
    
    /**
     * Constructor for objects of class Grid. Calls methods to draw the 
     * grid lines, to create the array of cells and to place 23
     * Fibonacci ants onto the grid.
     * 
     */
    public CellularAutomata()
    {    
        super(50, 50, 10);
        myHeight = getHeight();
        myWidth = getWidth();
        myCellSize = getCellSize();
        drawGrid();
        createCells();
    }
   

    /**
     * Tell each cell to save its last state in preparation for the
     * next time step.
     */
    public void act() 
    {
        for(int i = 0; i < myHeight; i++)
            for(int j = 0; j < myWidth; j++)
                myCells[i][j].saveLastState();
    }    
    /**
     * Draw the lines of the cell grid.
     */
    private void drawGrid() {
        myGrid = getBackground();
        myGrid.setColor(Color.red);
        
        int endY = myCellSize * myHeight;
        int endX = myCellSize * myWidth;
        
        for (int i = 0; i < endX; i += myCellSize)
            myGrid.drawLine(i, 0, i, endY);
        for (int i = 0; i < endY; i += myCellSize)
            myGrid.drawLine(0, i, endX, i);
    }
    /**
     * Create the array of cells and turn some of them on.
     */
    private void createCells() {
        myCells = new Cell[myHeight][myWidth];
        for (int i = 0; i < myHeight; i++)
            for (int j = 0; j < myWidth; j++) {
                Cell c = new GameOfLifeCell(myCellSize);
                myCells[i][j] = c;
                setInitCellState(c);
                addObject(c, i, j);
            }
    }
    
    /**
     * Overridden in subclassed automata. This default routine does nothing.
     */
    public void setInitCellState(Cell c) {
       if (Greenfoot.getRandomNumber(4) == 0)
           c.setState(true);
    }
}
Now I need to understand: 1. Why "saveLastState" is used and what does it do? 2. Explain the parameter here. Specially what does( i, 0, i, endY) do? myGrid.drawLine(i, 0, i, endY); 3. Explain the parameter here. Specially what does (0, i, endX, i) do? myGrid.drawLine(0, i, endX, i); 4. Explain the part: Cell c = new GameOfLifeCell(myCellSize); myCells = c; setInitCellState(c); addObject(c, i, j); *Why GameOfLifeCell is used? & *what does "addObject(c, i, j);" do? * What does setInitCellState method do? 5. Why the getRandomNumber(4) is used and what "c.setState(true);" does?
danpost danpost

2012/12/7

#
(1) Either the old state must be saved and used to determine the new state of all the cells while changing their state, or the new state of all cells must be saved as they are calculated before any of the cells are changed to their new state. We cannot change the states of the cells as we calculate them without keeping a record of the previous or future state because a change in one cell can alter the future state of another and produce erroneous results. (2) and (3) see the 'drawLine' method in the GreenfootImage class documentation. In (2), we are drawing the vertical lines from lefft to right; and in (3), we are drawing the horizontal lines from top to bottom. (4) The first line creates a new 'GameOfLifeCell' object that can be on or off. The fill color of the object represents the on/off state of the cell. The next line places a reference to the cell in an two-dimensional array representing the grid. This array does appear to be extra effort as everything can be accomplished without it. At any rate, the location in the array corresponds to the location within the grid that the cell is placed two lines down. That line places cell 'c' in the world at the (x, y) grid location of (i, j); where i and j are interated through with 'for' loops. Apparently, the programmer decided to use a world grid-size of one; but manually coded it to act like it had a grid-size of 'myCellSize'. The 'setInitCellState(c)' statement calls a method that will turn the supplied cell 'c' on twenty-five percent of the time, on average. This method is called for all cells created, giving the initial randomization of the whole grid. (5) the 'c.setState(true);' part of the statement is what tells the particular cell to turn on. The cells, when created, by default are turned off (their state value is set to false, and its image reflects that state). The random number part returns a random number between zero and three inclusive ( one number from the set { 0, 1, 2, 3 } ). Asking if the value is equal to zero ( '==0' -- or equal to any one of the four) give it a one in four chance of being that number; which basically sets the initial state of approximately 25 percent of the cells on for a random start.
vonmeth vonmeth

2012/12/7

#
1. saveLastState is a method of Cell. "Save the previous state in preparation for the next time step" 2. drawLine is a GreenfootImage method. drawline( x1, y1, x2, y2). x1 and y1 is where the line starts and x2 and y2 is where it ends. This will draw vertical lines. (0,Top of Screen Y) to (0, End of Screen Y) first iteration. (Size of Cell, Top of Screen Y) to (Size of Cell, End of Screen Y) second iteration. 3. Same as above, but draws the horizontal lines. 4.
Cell c = new GameOfLifeCell(myCellSize); // Create a cell of a certain size
                myCells[i][j] = c;                       // Add a reference to this cell in the myCells array. Used above in the act method.
                setInitCellState(c);                   // Set whether the cell is white or black
                addObject(c, i, j);                     // Add the cell to the world
*Why GameOfLifeCell is used? GameOfLifeCell is a subclass of Cell. It has the "rules" for how the Cell is suppose to act. See this for yourself: edit "new GameOfLifeCell(myCellSize);" on line 65 to "new Cell(myCellSize);" then run the game. What happens? *what does "addObject(c, i, j);" addObject adds the Cell to the world. It was created but not yet placed. The first time the For loop is ran, it would be "addObject(Cell, 0, 0)" which would place that cell at x=0, y=0. Next time, it would place it at x=0, y=1, then x=0, y=2, and so on. *What does setInitCellState method do? First it gets a random number, 0 through 3. If the number is 0 (25% chance), it calls setState with the parameter true. setState is a Cell method.
    public void setState(boolean state) {
        myState = state;
        showState();
    }
    private void showState() {
        if (myState) 
            myBody.setColor(Color.black);
        else 
            myBody.setColor(Color.white);
        myBody.fillRect(1, 1, myBodySize, myBodySize);
    }
hkrhässleholm hkrhässleholm

2012/12/8

#
Hi thanks all for better explanation. But a little thing makes me confused always... myGrid.drawLine(i, 0, i, endY); Why the character "i" is used and what is the value for that? What the hell, I don't get actually.
vonmeth vonmeth

2012/12/9

#
hkrhässleholm wrote...
Hi thanks all for better explanation. But a little thing makes me confused always... myGrid.drawLine(i, 0, i, endY); Why the character "i" is used and what is the value for that? What the hell, I don't get actually.
It is a value it gets from the For loop. So the the for loop says "for (int i = 0; i < endY; i += myCellSize)" The first time it runs, it would output. myGrid.drawLine(0, 0, 0, endY); as you can see in the for statement, it initialized "i" to "0". As "i" is still "<" endY, it adds myCellSize to "i", or 10, and then runs again and again till "i" is greater than endY. myGrid.drawLine(10, 0, 10, endY); myGrid.drawLine(20, 0, 20, endY); myGrid.drawLine(30, 0, 30, endY); myGrid.drawLine(40, 0, 40, endY);
danpost danpost

2012/12/9

#
It has, since the early days of higher level languages, been somewhat of a standard to use letters starting at 'i' for variables that represent integers. However, any variable name that conforms to Java could have been used. In this case, it is being used in a 'for' loop. The 'i+=myCellSize;' in the 'for' command controls the value of 'i' as the looping occurs. Each time it finishes the execution of the 'for' block, 'i' will be increased by the cellsize. What is happening, in reality, is that 'i' is acting as a changing x-coordinate in the world (maybe a better name for it might be 'worldX'; or 'lineX' since it determines where the line is drawn).
hkrhässleholm hkrhässleholm

2012/12/9

#
Thanks dear friends. I get that. I would like to mention more codes to understand. These are from the Cell class of actor.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.List;

/**
 * These are the cells of the CA. They save their last states to allow
 * for parallel reevaluation of neighboring cells.
 * 
 * @David Brown 
 * @03/16/2010
 */
public class Cell  extends Actor
{
    Boolean         myFirstTime = true;
    Boolean         myState, myLastState;
    GreenfootImage  myBody;
    int             myNumNeighbors;
    int             myBodySize;
    Cell []         myNeighbors;
    
    /**
     * Create the cell body's image and initialize state.
     */
    public Cell(int cellSize) {
        super();
        myState = myLastState = false;
        myBody = new GreenfootImage(cellSize, cellSize);
        setImage(myBody);
        myBodySize = cellSize - 2;
        showState();
    }
    
    /**
     * On first execution, find and save neighboring cell references.
     * After that, apply cell rule and show cell state.
     */
    public void act() 
    {
        if (myFirstTime) {
            List neighbors = getNeighbours(1, true, Cell.class);
            myNumNeighbors = neighbors.size();
            myNeighbors = new Cell[myNumNeighbors];
            for(int i = 0; i < myNumNeighbors; i++)
                myNeighbors[i] = (Cell)neighbors.get(i);
            myFirstTime = false;
         }
         applyRule();
         showState();
    }
    
    /**
     * Save the previous state in preparation for the next time step.
     */
    public void saveLastState() {
        myLastState = myState;
    }
    
    /**
     * Set the state of the cell.
     */
    public void setState(boolean state) {
        myState = state;
        showState();
    }
    
    /**
     * Get the state of the cell.
     */
    public boolean getState() {
       return(myState);
    }

    /**
     * Flip the state of the cell.
     */
    public void flipState() {
        setState(!myState);
    }
    
    /**
     * Count the surrounding cells that were on in the previous time step.
     */
    public int countNeighbors() {
        int sum = 0;
        for(int i = 0; i < myNumNeighbors; i++) 
            if (myNeighbors[i].myLastState)
                sum++;
        return(sum);
    }
    
    /**
     * Apply cell rule for timestep. Subclasses should override this method
     * which does nothing.
     */
    public void applyRule() {
    }
    
    /**
     * Draw the body of the cell based on the state.
     */
    private void showState() {
        if (myState) 
            myBody.setColor(Color.black);
        else 
            myBody.setColor(Color.white);
        myBody.fillRect(1, 1, myBodySize, myBodySize);
    }
}
1. In this line: myBody = new GreenfootImage(cellSize, cellSize); why the parameters (cellSize, cellSize); are used two twice? 2. What does the line" myBodySize = cellSize - 2;" do? 3. Explain this part: if (myFirstTime) { List neighbors = getNeighbours(1, true, Cell.class); myNumNeighbors = neighbors.size(); myNeighbors = new Cell; for(int i = 0; i < myNumNeighbors; i++) myNeighbors = (Cell)neighbors.get(i); myFirstTime = false; } a) What does the (myFirstTime) do? b) List neighbors = getNeighbours(1, true, Cell.class); - what do they do? c) myNeighbors = (Cell)neighbors.get(i);- in this line what are the (Cell)& (i); for? 4. I can see that these 5 methods- saveLastState(), setState, getState(), flipState() & countNeighbors() were not declared anywhere. Then how do they work? 5) what does the method flipState() do? 6) What is the role of countNeighbors() method? And why sum is used? 7) Explain the line- myBody.fillRect(1, 1, myBodySize, myBodySize);
vonmeth vonmeth

2012/12/9

#
1. GreenfootImage GreenfootImage(int width, int height). Needs to know the width and height. 2. Set the size of myBodySize to two smaller than what cellSize is. Later used in showState, so when filling the image (through fillRect), it isn't completely filled. 3.a. Checks whether myFirstTime is true or false. When ran the first time, it is true, and later set to false inside that if block so it doesn't run again on the next act cycle. b. Gets a list of all the surronding cells that are 1 away, including diagonals. getNeighbors is a method of Actor getNeighbours(int distance, boolean diagonal, java.lang.Class cls) c. (Cell) is for casting. Basically saying that the object that is being referenced is a Cell. The array expects a Cell. We know a Cell will be passed on, the compiler doesn't. I think I explained that correclty. get() is a method of the List class. The 'for' loop (where the i comes from) is iterating through the neighbors List and placing each reference of the Cells surronding it into the myNeighbors Array. 4. They are declared. For instance, saveLastState() is declared on line 54. 5. It flips the current state. So if the state is true, it becomes false, and vice versa. It does this by passing the myState variable flipped (through the use of the NOT operator) to setState(). 6. countNeighbors() method is used to get the number of Cells surronding that cell that are currently on. It iterates through the myNeighbors Array that we had populated earlier in the act method. Each iteration, it checks if that cell is on or off (true or false). If it is on (true), it adds one to sum. Sum is used to keep a count of how many around the cell that are on (true). 7. drawRect. Basically draws a square that is not quite the full size of the Cell. Needs to be like that, or they would cover up the grid lines.
hkrhässleholm hkrhässleholm

2012/12/9

#
Hi helpful friend, thanks. I will be back with more question. but for now, have fun& goodnight!
hkrhässleholm hkrhässleholm

2012/12/11

#
Hi friends, I am back again! I am going to show the codes for "GameOfLifeCell" and it's a subclass from "Cell". import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class GameOfLifeCell here. * * @author (your name) * @version (a version number or a date) */ public class GameOfLifeCell extends Cell { public GameOfLifeCell (int cellSize){ super (cellSize); } public void applyRule(){ int numNeighborsOn=countNeighbors(); boolean state=myState; if(numNeighborsOn<2) state=false; else if (numNeighborsOn>3) state=false; else if(numNeighborsOn==3) state=true; myState=state; } /** * Act - do whatever the GameOfLifeCell wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ //public void act() { // Add your action code here. } } Now, we know that there are 4 rules of game of life and the rule- "Any live cell with two or three live neighbors lives on to the next generation" is one of them. My question is that 1) Where the rule is used or applied in these codes? 2) "The simulation shall continue till all cells are dead"- is one of my requirement of this project. Okay, if so, then when my all cells will die? I can't find them die! 3) If they die actually then where is the method for that? 4) Why the "GameOfLifeCell" is a subclass of "Cell"? 5) I am still now confused about this line -"myBodySize=cellSize-2;" in "Cell" class. 6) I want to know more about the "flipState" method! Which role does it play? 7) I can see that every time I reset the game, the cells are placed at any random location. Where is the method for settng the cells randomly?
vonmeth vonmeth

2012/12/12

#
1) The rules are applied in the applyRule method. First it calls countNeighbors (which we went over last time), to get a count of the number of alive cells around the cell. Next the rules come into play. "if(numNeighborsOn) < 2)" Is the number of neighbors that are alive, less than 2? If so, it dies (state=false) It satisfies this rule: "1. Any live cell with fewer than two live neighbours dies, as if caused by under-population." "else if (numNeighborsOn > 3)" Is the number of neighbors that are alive, greater than 3? If so, it dies (state=false) It satisfies this rule: "3. Any live cell with more than three live neighbours dies, as if by overcrowding." Those two parts combined (combined, meaning the cell was not set to false by those 'if' statements, and it would have to have 2 or 3 alive neighbors to do so), will satisfy this rule: "2. Any live cell with two or three live neighbors lives on to the next generation" You could satisfy all three of those rules with one 'if' statement. "if(numNeighborsOn != 2 && numNeighborsOn != 3) state = false;" "else if(numNeighborsOn == 3) Is the number of neighbors that are alive, equal to 3? If so, it lives (state=true) It satisfies this rule: "4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction." 2 & 3) Dying is cell's state being set to false. True equals life. False equals death. 4) There really is not reason for it. Only reason I could see why would be if the creator wanted different types of Cell's, with different rules. 5) Try a test. Try removing the minus two from "myBodySize=cellSize-2;" so it becomes "myBodySize=cellSize;" What do you observe? What happens if you subtract 5 instead of 2? 6) flipState plays no actual role in the program, as I don't believe it is ever called. But remember, state equals life or death for the cell. It flips the cell to life(true) if it is dead(false) and to death(false) if it is alive(true). 7) View the comments I added to the code
private void createCells() {  
        myCells = new Cell[myHeight][myWidth];  
        for (int i = 0; i < myHeight; i++)  
            for (int j = 0; j < myWidth; j++) {  
                Cell c = new GameOfLifeCell(myCellSize);  
                myCells[i][j] = c;  
                setInitCellState(c); // do we want this cell, that we just placed down, to be true (alive) or false (dead). By default, they are dead
                addObject(c, i, j);  
            }  
    }  	

public void setInitCellState(Cell c) {  
       if (Greenfoot.getRandomNumber(4) == 0) // get a random number between 0 and 3. If the random number is 0, set that cell to true (alive)
           c.setState(true);  				  
    }  
}  
You need to login to post a reply.