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

2017/1/15

Multiple Rock objects are created

Salamander Salamander

2017/1/15

#
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++;
            }
        }
        
    }
}
Super_Hippo Super_Hippo

2017/1/15

#
I think you misunderstood OOP in general. Each Rock object which is in the active world will run the Rock's act method each act cycle. So usually you add the objects to the world from the world subclass and each object moves itself and checks for intersection and so on (like not using a for loop to iterate over all Rock objects from the Rock class). If you really want/need to use these for loops and do what you did there, try to explain what you want to achieve and why you are doing it as you do it.
Salamander Salamander

2017/1/15

#
What I want this code to do is to try to add rock objects and move them in constant but random directions. Every 2.5 seconds, I add a rock object to an object ArrayList and have corresponding x and y values stored (this happens in the spawn method). Then in lines 24-27, the rock objects are moved based on their given X and Y directions. The checkForVerticalWall and checkForHorizontalWall methods simply check if each object intersects a wall and changes its X or Y values accordingly. The checkForCentre method makes the rock disappear if the rock has hit the vertical wall once (the rock passes the centre at the beginning but I only want it to disappear after it has hit the back wall). However, I did not know that each rock object ran the act method individually. My question for you is if I move my spawn method to the world subclass, how will I ensure that each new Rock has its own different X and Y change values.
danpost danpost

2017/1/15

#
Ah. Maybe you are not aware that all classes have constructors (some implicit and some explicit). You can add one (go from implicit to explicit) to your Rock class to set the random x and y values of each Rock as they are being created:
// with simple int fields
private int dx, dy; // change values for x and y

public Rock()
{
    dX = Greenfoot.getRandomNumber(10)+1;
    dY = Greenfoot.getRandomNumber(6)+4;
}
Since this is the only place you will be using those random values, it is better to code it here and you can remove the 'RandomX' and 'RandomY' methods from the class.
danpost danpost

2017/1/15

#
Btw, I used 'dx' and 'dy' instead of 'rockX' and 'rockY' because the latter sounds more like location coordinates instead of change in location values. Normally, a 'd' in front of a variable indicates a change in its value and is often read as "delta". Also, by standard convention, all field and method names should begin with a lowercase letter. Classes are, by convention, what begin with uppercase letters.
Salamander Salamander

2017/1/15

#
Okay, I have implemented the changes you suggested and the code looks and performs much better. However, there are a couple things that I am still having trouble with. 1. Where would I put the code to make the Rock objects spawn every 2.5 seconds. 2. I want to make each rock disappear after it hits the horizontal wall once, then comes back to hit the centre line. I did this with the counter variable that changes from 0 to 1 whenever a rock hits the horizontal wall, then in the checkForCentre method, I will have the Rock disappear only if this counter is equal to 1. However, at the moment, the rock disappears and the whole program stops. Thanks you for all your help!
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList; 
public class Rock extends Actor
{
    private int position;
    private int counter;
    public int score = 0;
    private int dx, dy;
    long startTime = System.currentTimeMillis();
    public Rock()
    {
        dx = Greenfoot.getRandomNumber(10)+1;
        dy = Greenfoot.getRandomNumber(6)+4;
        counter = 0;
    }
    public void act() 
    {
        checkForVerticalWall();
        checkForHorizontalWall();        
        this.setLocation(this.getX() + dx, this.getY() - dy);
        checkForCentre();        
        spawn();     
    }
    private void spawn()
    {
        position = ((Cannon) getWorld().getObjects(Cannon.class).get(0)).getX();
        long curTime  = System.currentTimeMillis();
        if (curTime >= startTime + 3000) 
        {
            getWorld().addObject(new Rock(), position, 675);           
            startTime  = curTime;
        }
    }
    private void checkForVerticalWall()
    {
        Actor person;
            person = this.getOneIntersectingObject(WallVertical.class);
            if (person != null)
            {
                dx = dx * (-1);    
            }
    }
    private void checkForHorizontalWall()
    {
        Actor person;
            person = this.getOneIntersectingObject(WallHorizontal.class);
            if (person != null)
            {
                dy = dy * (-1);
                counter = 1;
            }
    }
    private void checkForCentre()
    {
        Actor person;
            person = this.getOneIntersectingObject(Centre.class);
            if (person != null && counter == 1)
            {
                getWorld().removeObject(this);
                score++;
            }      
    }
}

Super_Hippo Super_Hippo

2017/1/15

#
If the program stops, then one of the following things happened: - you clicked on Pause - Greenfoot.stop() was called - an error occured In your case, you will get a NullPointer exception in line 26 if line 59 removed the object from the world. Remove the spawn method from your Rock class. You can add an act method to your world class to add Rocks over time.
Salamander Salamander

2017/1/16

#
Thank both of you so much. All the errors are fixed and I am very grateful. I also appreciate how both of you have taken so much time to help us programming noobs with our problems. I tip my cap to both of you.
You need to login to post a reply.