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

Increasing the length of the snake


We have the snake eating the apple; however, there aren't any consequences to this. As a part of the game, we need to make the snake increase the length of his body for each apple he eats. Our requirements for this are as follows:

  • Add a body part to the snake when it eats an apple

  • As the snake moves, the body parts should follow

  • There will be multiple body parts

First, let's create a class that will contain the length of the snake's body. This can take the form of an inner class for now:

    private class BodyPart {

        private int x, y;
        private Texture texture;

        public BodyPart(Texture texture) {
            this.texture = texture;
        }

        public void updateBodyPosition(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public void draw(Batch batch) {
            if (!(x == snakeX && y == snakeY)) batch.draw(texture, x, y);
        }
    }

As you can see, it contains the x and y components...