Book Image

LibGDX Game Development By Example

By : James Cook
Book Image

LibGDX Game Development By Example

By: James Cook

Overview of this book

Table of Contents (18 chapters)
LibGDX Game Development By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 is eaten; therefore, we don't need any fancy timing mechanism to deal with it. Hence, the apple is not available at the start as we need to place one first. We also specify the variables that will contain the location of the apple.

Finally...