Reputation: 1323
I'm trying to build a checkers game and I'm currently trying to implement the moving of the pieces.
To do this I decided I'd keep a list of where the pieces should be:
blackPieces
whitePieces
Then when a movement is made I would:
However, I'm stuck at step 3, with the following Groovy code I simply get a ConcurrentModificationException
def children = board.getChildren()
for (child in children) {
if (child instanceof Circle) {
board.getChildren().remove(child)
}
}
Is there a way to do this without redrawing the entire scene?
Appreciate any help!
Upvotes: 1
Views: 1990
Reputation: 1880
There is even an easier way, thanks to groovy's removeAll method that takes a closure.
board.getChildren().removeAll{ it instanceof Circle }
Upvotes: 2
Reputation: 55
You shouldn't use instanceof
. What you should do is program against an interface, isntead of against an implementation. By this I mean have all of the black and white piece implement an interface, maybe Piece
. Then have your GridPane populated by classes that implement Piece
. In your Piece
interface you could have a method, maybe isCircle()
that does the obvious check. Now you can use your solution, but using the isCircle()
method.
Upvotes: 1
Reputation: 1323
Wow so randomly browsing Groovy cheat sheets and Collection methods I put together this solution.
def pieces = board.getChildren().findAll { it instanceof Circle } // gets all the pieces
board.getChildren().removeAll(pieces) // removes them
win.
Upvotes: 0