Luke Vincent
Luke Vincent

Reputation: 1323

removing all nodes of a type within a GridPane

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:

  1. update the relevant list
  2. loop through all the children of the GridPane
  3. remove all the checkers pieces i.e. all Nodes of type Circle
  4. add new pieces according to relevant list

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

Answers (3)

tylerwal
tylerwal

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

Sean_J
Sean_J

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

Luke Vincent
Luke Vincent

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

Related Questions