tags:

views:

56

answers:

4

I have a function that shrinks the size of a "Food bank" (represented by a rectangle in my GUI) once some of the food has been taken. I have the following function check for this:

public boolean tryToPickUpFood(Ant a)
    {
        int xCoord = a.getLocation().x;
        int yCoord = a.getLocation().y;
        for (int i = 0; i < foodPiles.size(); i++)
        {
            if (foodPiles.get(i).containsPoint(xCoord, yCoord))
            {
                foodPiles.get(i).decreaseFood();
                return true;
            }
        }
        return false;
    }

Where decreaseFood shrinks the rectangle..

public void decreaseFood()
    {
        foodAmount -= 1;
        shrinkPile();
    }

    private void shrinkPile()
    {
        WIDTH -=1;
        HEIGHT = WIDTH;
    }

However, whenever one rectangle shrinks, ALL of the rectangles shrink. Why would this be?

edit:

Food piles are being added like such:

addFoodPile(new Food(new Point(200,200)));
addFoodPile(new Food(new Point(400,340)));

public void addFoodPile(Food fp)
    {
        foodPiles.add(fp);
    }
+3  A: 

Because the same food pile is in each element of the array? If you are populating it like

FoodPile foodPile = new FoodPile();
for (int i = 0; i < count; i++) {
    foodPiles.add(foodPile)
    }

you should do this instead:

for (int i = 0; i < count; i++) {
    FoodPile foodPile = new FoodPile();
    foodPiles.add(foodPile)
    }

also, this loop:

for (int i = 0; i < foodPiles.size(); i++)
{
    if (foodPiles.get(i).containsPoint(xCoord, yCoord))
    {
        foodPiles.get(i).decreaseFood();
        return true;
    }
}

can be more readable if you use foreach syntax:

for (FoodPile foodPile : foodPiles)
{
    if (foodPile.containsPoint(xCoord, yCoord))
    {
        foodPile.decreaseFood();
        return true;
    }
}
Carl Manaster
I thought that as well, but it's foodPiles.add(new Food(new Point(200,200))); and several statements like this
Charlie
A: 

I'm guessing you thought you were adding lots of separate piles into the List but actually you were adding a reference to the same one over and over. Check that part of your code.

Sean Owen
A: 

From the code you have shown, it seems like the problem lies in where and how often the tryToPickUpFood() is used. Unless you've used the same reference of foodPiles, as pointed in the other answers

qtips
+2  A: 

This might be your problem -

private void shrinkPile()
{
    WIDTH -=1;
    HEIGHT = WIDTH;
}

In the standard Java naming convention, all uppercase names are used for static variables - since you haven't shown their declaration, I can't be sure - but it's certainly suspicious and a place to look.

Nate
This was it. Wow, completely slipped. Huge thanks.
Charlie