Hi! I am fairly new to Greenfoot and I am having quite a bit of trouble with this. In my game, these rocks are thrown in random directions and have to be dodge by the user-controlled player. The problem I have encountered is that the code creates 1 more Rock objects than the total number of rock objects in play. So if the "if statement" on line 35 runs while there is one rock in play, the code will create 2 rocks. If there are 2 rocks in play, the code will create 3 and so on. I assume that it is line 35 that creates the rock but I am not sure at this point. Any help would be appreciated. Thanks!
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
public class Rock extends Actor
{
World world = getWorld();
private ArrayList<Rock> Rocks = new ArrayList<Rock>();
private ArrayList<Integer> RockX = new ArrayList<Integer>();
private ArrayList<Integer> RockY = new ArrayList<Integer>();
private ArrayList<Integer> counter = new ArrayList<Integer>();
public int score = 0;
private int position;
private int j = 0;
private int k = 0;
long startTime = System.currentTimeMillis();
public void act()
{
checkForVerticalWall();
checkForHorizontalWall();
checkForCentre();
spawn();
if (j > 0)
{
for(int i = k; i < Rocks.size(); i++)
{
Rocks.get(i).setLocation(Rocks.get(i).getX() + RockX.get(i), Rocks.get(i).getY() - RockY.get(i));
}
}
}
private void spawn()
{
position = ((Cannon) getWorld().getObjects(Cannon.class).get(0)).getX();
long curTime = System.currentTimeMillis();
if (curTime >= startTime + 2500)
{
Rocks.add(new Rock());
counter.add(0);
RockX.add(RandomX());
RockY.add(RandomY());
getWorld().addObject(Rocks.get(j), position, 675);
j++;
startTime = curTime;
}
}
private int RandomX()
{
return Greenfoot.getRandomNumber(10) + 1;
}
private int RandomY()
{
return Greenfoot.getRandomNumber(6) + 4;
}
private void checkForVerticalWall()
{
Actor person;
for(int i = k; i < Rocks.size(); i++)
{
person = Rocks.get(i).getOneIntersectingObject(WallVertical.class);
if (person != null)
{
RockX.set(i, RockX.get(i) * (-1));
}
}
}
private void checkForHorizontalWall()
{
Actor person;
for(int i = k; i < Rocks.size(); i++)
{
person = Rocks.get(i).getOneIntersectingObject(WallHorizontal.class);
if (person != null)
{
RockY.set(i, RockY.get(i) * (-1));
counter.set(i, 1);
}
}
}
private void checkForCentre()
{
Actor person;
for(int i = k; i < Rocks.size(); i++)
{
person = Rocks.get(i).getOneIntersectingObject(Centre.class);
if (person != null && counter.get(i) == 1)
{
getWorld().removeObject(Rocks.get(i));
score++;
k++;
}
}
}
}

