
Introducing Sammy the snake
Before we start making the Snake game, we need to set up our textures for the snake and the game play area. So, let's remove the default code from our GameScreen
class, leaving just our SpriteBatch
batch's clear screen calls:
public class GameScreen extends ScreenAdapter { private SpriteBatch batch; @Override public void show() { batch = new SpriteBatch(); } @Override public void render(float delta) { Gdx.gl.glClearColor(1, 0, 0, 1); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); } }
Next, let's change the color that fills the screen from red to black. We can do this by updating the glClearColor
method call to reference the r, g
, b
, a
values of the black Color
class:
Gdx.gl.glClearColor(Color.BLACK.r, Color.BLACK.g, Color.BLACK.b, Color.BLACK.a);
If you run the project now, you will find that we are back to our black screen; however, this time, the screen is being cleared every render call. If you don't want to use black, check out the other default colors LibGDX provides, failing that you can define your own! You can do this by creating your own instance of Color
with your own r
, g
, b
, a
values.
Next we will add back calls in to our batch as we did earlier:
batch.begin(); //Our rending code will live here! batch.end();
Admittedly they won't do much right now, but our texture rendering code will sit in between them. Failing to call begin()
before trying to call any other method for the SpriteBatch
class will result in a java.lang.IllegalStateException
exception being thrown.
Now, I think we are ready to start drawing our snake!
Giving the snake a face
We have two assets that we are going to use for drawing our snake, snakehead.png
and snakebody.png
. These assets will reside in a specific directory with in the project. As we are only using the desktop export of LibGDX at the moment, you will find an assets
directory in the core project. However, when we start looking at the Android export, you will find the assets
directory will move. The assets themselves are self-explanatory, one for the snakes head and one for the snakes body. Let's start with the head.
Back in our GameScreen
class, add a texture object and call it snakeHead
:
private Texture snakeHead;
Next, let's initialize the texture in the show()
method:
snakeHead = new Texture(Gdx.files.internal("snakehead.png"));
Uh oh! Looks like something new cropped up here—Gdx.files.internal
. LibGDX comes with some handy tools for handling files. Here we are just loading a file from within the project.
Now, let's render it in the render()
method:
batch.draw(snakeHead,0,0);
Hopefully, when you run the project, you will get the following output:

The default resolution that the DesktopLauncher
parameter has is 640 x 480 pixels. Currently, this is what we are rendering to. Later on, we will discuss using a viewport to allow us to handle multiple different resolutions.