Pregunta

I am working on a matching game (in Java) where the player throws and object and the system will check if it matches any adjacent pieces on the board. I currently am able to get it to check one adjacent piece (using rectangle intersection), but if I don't return; after the if/else block (thereby preventing it from checking more than one adjacent piece), it will throw a java.util.ConcurrentModificationException exception. I haven't been able to figure out any way of doing this.

I am using iterators to loop through all the pieces and check if they intersect with the thrown piece. This check is done after the piece hits something (also checked by rectangle intersection).

Below is a code snippet of the problem area:

Iterator<Food> it3 = foods.iterator();
    while(it3.hasNext()) {
        Food f2 = it3.next();
        if(t.checkAll().intersects(f2.getBounds())) { // check for matches
            if(t.getNutritionType() == f2.getNutritionType() || t.getType() == 0) {
                app.log("Throw intersects with like food.");
                int numMatches = 2; // hard-coded until multiple matching works
                player.addNutrient(f2.getNutritionType(), 1);
                player.addCalories(10*numMatches);

                // move food to cart and add to matched
                f2.fallToCart(600, 540);
                matched.add(f2);

                // remove from food arraylist
                it.remove();
                it3.remove();
                return;
            } else {
                app.log("Throw intersects with unlike food.");
                t.stop();
                Food n = new Food(t.getType());
                n.setX(t.getX());
                n.setY(t.getY());
                foods.add(n);
                it.remove();
                return;
            }
        }
    }

Note that it is the 'thrown' iterator and it2 is the first collision check with pieces to stop the throw. Throws are throws and foods are game pieces.

I'm sorry if what I wrote is confusing. I'd be more than happy to clarify anything. Basically my question comes down to how to iterator for matches multiple times (either separately or at once), as matches can be on any side of the throw and more than one object can match.

¿Fue útil?

Solución

Without being able to understand your code (see my comments), I can tell you where your problem is. If you read what a ConcurrentModificationException actually is, you will get to the part where it explains

[...] if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception.

You are iterating with it3 and then calling it3.remove().

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top