游戏的每次迭代我都希望它将生命时间减少1

时间:2016-03-14 19:53:17

标签: java object arraylist

所以我有一个arraylist存储有关宇宙的不同物体(行星,彗星,星等)。而不是这样做:

planet.decreaseLifeTime(1);
star.decreaseLifeTime(1);
comet.decreaseLifeTime(1);

游戏的每次迭代我希望它将生命时间减少1.我试过这个但它不起作用:

private ArrayList<SpaceObject> universeEntities;

public void reduceLifeTime() {
    for (SpaceObject entity: universeEntities) {
        entity.decreaseLifeTime(1);
        if(entity.getLifeTime() <= 0) {
            erase(entity);
            System.out.println("This entity has been erased");
        }

        System.out.println("life time: " + entity.getLifeTime());
    }
}

添加对象如下:

planet = new Planet(500, 500, -2, -2, 25, Color.BLUE, this);
universeEntities.add(planet);

2 个答案:

答案 0 :(得分:1)

如果erase(entity)正在修改Universentities列表,那么java会生气。

您可以将要删除的SpaceObject存储在单独的列表中,然后在for循环后将其删除。

您可以在不使用迭代器的情况下遍历universeEntities 例如数字指数

答案 1 :(得分:1)

根据您对reduceLifeTime方法的实现,问题可能在于调用erase方法(取决于它的实现方式)。

如果erase方法只是尝试通过调用ArrayList的remove方法从universeEntities集合中删除项目,它只会破坏迭代器。

考虑重新实现您的方法:

public void reduceLifeTime() {
    Iterator<SpaceObject> iterator = universeEntities.iterator();
    while (iterator.hasNext()) {
        SpaceObject object = iterator.next();
        object.decreaseLifeTime(1);

        if(object.getLifeTime() <= 0) {
            iterator.remove();
            System.out.println("This entity has been erased.");
        }

        System.out.println(String.format("Life time: %d", object.getLifeTime()));
    }
}

完全正常工作的样本:

public class Test {
    private ArrayList<SpaceObject> universeEntities = new ArrayList<SpaceObject>();

    public Test() {
        universeEntities.add(new Planet());
        universeEntities.add(new Planet());
    }

    public void reduceLifeTime() {
        Iterator<SpaceObject> iterator = universeEntities.iterator();
        while (iterator.hasNext()) {
            SpaceObject object = iterator.next();
            object.decreaseLifeTime(1);

            if(object.getLifeTime() <= 0) {
                iterator.remove();
                System.out.println("This entity has been erased.");
            }

            System.out.println(String.format("Life time: %d", object.getLifeTime()));
        }
    }

    public static void main(String[] args) {
        Test test = new Test();

        while(true) {
            test.reduceLifeTime();
            // Endless loop. Need a quit condition.
        }
    }

    public static class SpaceObject {
        protected int life = 0;

        public SpaceObject(int life) {
            this.life = life;
        }

        public void decreaseLifeTime(int value) {
            this.life -= value;
        }

        public int getLifeTime() {
            return life;
        }
    }

    public static class Planet extends SpaceObject {
        public Planet() {
            super(10);
        }
    }
}

如果您不想使用迭代器,则可以收集应在某种集合中删除的项目,从reduceLifeTime方法返回,然后使用removeAll删除。