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

2012/12/8

Hi friends! Need help!

jabirfatah91 jabirfatah91

2012/12/8

#
Recently, I am working on a project named "Conway's game of life". Unluckily, I am not allowed to use the Greenfoot library function getNeighbours(…) in the Actor class. By the way, I found some some well made scenerios of "Conway's game of life" at this website, but there, the Greenfoot library function getNeighbours(…) is used. I even can't come up with good solution to make it without the library function getNeighbours(…). Can you please help me. I am going to copy+paste the codes I found from this side.
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);
    }
}
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);
    }
}
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);
    }
    
    /**
     * Apply the Game of Life rules to the current cell situation.
     */
    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;
    }   
}
vonmeth vonmeth

2012/12/8

#
Take a look at this scenario. The code you are looking for is the following:
   for(int i=1;i<499;i++)
        for(int j=1;j<499;j++)
        {
            around = 0;
            if(world[i+1][j])around++;
            if(world[i-1][j])around++;
            if(world[i][j+1])around++;
            if(world[i][j-1])around++;
            if(world[i+1][j-1])around++;
            if(world[i+1][j+1])around++;
            if(world[i-1][j+1])around++;
            if(world[i-1][j-1])around++;
            if(around<2||around>3)
                world2[i][j]=false;
            else if(around==3)world2[i][j] = true;
            else world2[i][j] = world[i][j];
        }
MatheMagician MatheMagician

2012/12/8

#
You could use
getOneObjectAtOffset(getX()+1,getY(),null);
jabirfatah91 jabirfatah91

2012/12/8

#
Hi vonmeth& MatheMagician thanks to u all. but the problem is that I must have to have Grid. The scenerio you put the link for, has no grid. You can have short look of my lab requirements. The goal of this lab is for you to create your very own simulation of life, death and the growth of a population. The simulation shall use a grid where you shall place some cells for the initial state. You shall use some specific rules for the simulation. The rules are: 1. Any live cell with fewer than two live neighbors dies, as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by overcrowding. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction Here are the requirements for the program. For Grade 3: 5. The simulation shall implement all the rules above. 6. The simulation shall continue till all cells are dead. 7. No cells can exist outside the visible grid (screen). 8. You shall populate the grid with some cells before the simulation is started. This shall be done in code. For Grade 4: 9. The grid must be implemented using an array. 10. The Greenfoot library function getNeighbours(…) in the Actor class cannot be used. For Grade 5: 11. It shall be possible to edit what cells are alive before the simulation starts. 12. Editing living/dead cells shall be done by using the mouse.
danpost danpost

2012/12/8

#
Actually, I have been working on a simple one (without 'getNeighbours').
jabirfatah91 jabirfatah91

2012/12/8

#
@Danpost I need to look on that one.
danpost danpost

2012/12/9

#
OK, what I did was I made two arrays in the world class: one to hold a reference to each cell in the world and the other to hold, for each cell, the count of nearby cells whose state is on.
Cell[][] cells = new Cell[20][20]; // my world was 20 cells wide by 20 cells high
int[][] locals = new int[20][20];
I used a double 'for' loop to populate the cell array and the world. Then, I used a double 'for' loop to change the state of some (approx. 25%) of the cells. That was it for the constructor of the world; well, other than dressing up the world with a background image gridwork (horizontal and vertical lines to seperate the individual cells). The act method in the world class does the following: (1) calls a method to set new counts of local cells whose states are on for each and every cell (2) calls a method to tell each and every cell what the count for that cell was Method one interates through the cell array. For each cell, the locals count is zeroed and all possible cells around it are check for an on state. Each 'on' (true) state found increments the locals count. Method two interates through the cell array, also. This time calling a method in the Cell class on each cell, supplying the cells with its locals count. The Cell class was pretty straight-forward. It has one instance boolean field to hold its state. The constructor just sets the image to a not-quite grid-sized transparent image. There is no act method; but there are four very short methods to complete the class: 'private void updateImage()', 'public boolean getState()', 'public void setState(boolean)', and 'public void setState(int). 'updateImage()' either clears or fills the image depending upon the state of the cell. 'getState()' just returns the state of the cell (true=on; false=off) 'setState(boolean)' is used to force a change in the state of the cell (calls 'updateImage' to reflect the new state). 'setState(int)' is used to change the state depending on the locals count supplied (also calls 'updateImage') That was it.
vonmeth vonmeth

2012/12/9

#
Thank you danpost! I thought I'd try my hand at creating it and was able to make one from following the instructions you posted. If you use the code I copied in my first post, it will end up ignoring the bordering cells. Fixing it so you don't ignore the bordering cells requires making sure it doesn't cause ArrayIndexOutOfBounds exception. This proves easy when altering the code I copied above a bit to use a 'for' loop for checking the locals.
You need to login to post a reply.