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

2017/2/24

Help with costumes

Avecinat Avecinat

2017/2/24

#
Hey, i am new to greenfoot and i am working on a small project. there are cells surrounded with 8 other cells. These cells can be alive or dead and have different costumes (alive.png and box.png). How can i set it up so each cell can detect the amount of cells that are alive around it? Thanks :)
Super_Hippo Super_Hippo

2017/2/24

#
Are the cells actors? If yes, save a variable to show if a cell is alive or not (you could also compare the image but I usually prefer using a variable (int or boolean).
private boolean alive;

public Cell(boolean a)
{
    alive = a;
    setImage(alive ? "alive.png" : "box.png");
}

//to get the number of cells which are alive:
int numAlive = 0;
for (Cell c : getNeighbours(1, true, Cell.class))
{
    if (c.alive) numAlive++;
}
//use numAlive here for something
Just in case it is not working: (I am never really sure about this without testing)
//to get the number of cells which are alive:
int numAlive = 0;
for (Object obj : getNeighbours(1, true, Cell.class))
{
    Cell c = (Cell) obj;
    if (c.alive) numAlive++;
}
//use numAlive here for something
When creating a cell:
new Cell(true) //alive
//or
new Cell(false) //dead
You need to login to post a reply.