I am trying to create a basic Snake game. I have a very basic 2D Java Game Engine.Here is how all the Update's and Rendering happen:
I have an ArrayList of GameObjects which is a class I created and has two abstract methods called "update" and "render" (And also some variables which have nothing to do with the question but telling it may decrease confusion when answering it). I create objects inside the game class like in the example code below and then add these to the ArrayList. Then I basically use an enhanced for loop to update and render all the objects in the ArrayList.
I basically want to create an object in a method while the game is running (A body part will be created everytime a "food" is eaten).
When I use the following code to create a body part inside a method, I get an error for each variable I use in the "render" part saying
Cannot refer to a non-final variable body inside an inner class defined in a different method
GameObject body = new GameObject(DOT_SIZE, DOT_SIZE, food.boardPosX, food.boardPosY) {
@Override
void update() {
//MOVE PART
}
@Override
void render(Graphics g) {
g.fillRect(body.pixelPosX, body.pixelPosY, body.pixelSizeX, body.pixelSizeY);
}
};
Also If I don't put anything into the rendering method and basically leave everything empty and try to add this "head" to the ArrayList of GameObjects in the same method I get the java.util.ConcurrentModificationException exception.
Further information:
The objects which exist from the very beginning (the head and the food) are;
- created in the Game class (and not in any kind of methods)
- added to the
ArrayListofGameObjectsin a method called in the constructor of theGameclass.
EDIT - More Information:
- When I make body final, I get an error saying
The local variable body may not have been initialized.
The question is:
- Where and how should I define the "body" object.
- Where and how should I add it to the ArrayList of objects.
Thanks for your consideration.