Adding the apple

Next up, we need to get our snake eating something. Let's get our apple implemented.

We will need to get our apple to do the following things:

  • Randomly being placed on the screen, not on the snake!
  • Only place one if there isn't an apple on the screen already
  • Disappear when it collides with the snake's head

Right! Let's add the texture:

    private Texture apple;

Then, let's amend our show() method and add the code to instantiate the apple texture:

    apple = new Texture(Gdx.files.internal("apple.png"));

Let's add a flag to determine if the apple is available:

    private boolean appleAvailable = false;
    private int appleX, appleY;

This will control whether or not we want to place one. In the Snake game, the next apple appears after the current apple ...

Get LibGDX Game Development By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.