We need a model layer to define what objects will exist within our game. We can define any object but since we’re working on the snake game it makes sense to start with the essentials: snake and apple. Feel free to add more objects such as bonuses if you think it would make the game more interesting.
This is the seventh part of the “Kotlin Game Development” series and it’s better if you read it in chronological order:
- Part 1 - Introduction
- Part 2 - Creating a Scene
- Part 3 - Controller Input
- Part 4 - Game Loop
- Part 5 - Game Factory
- Part 6 - Main Menu
- Part 7 - Model (you are here)
- Part 8 - Game Scene
- Part 9 - Finalizing The Game
How can we represent a snake? As you may already know the traditional snake looked like a chain of blocks that constantly moves in a specific direction. Each part of the snake has it’s own position and this position changes when the snake moves.
Let’s create a new class and call it SnakeBodyPart:
This class represents one piece of the snake. Usually the snake is quite short when the game starts but it grows longer as it eats apples. Each apple consumed by our snake adds one more part to it’s body. The only thing we want to know about each body part is it’s position.
Do we need something else except the list of body parts to describe the snake? It turns out the snake is a bit smarter than the sum of it’s parts. At least, it should have a direction and it should be able to move according to the selected direction.
Let’s create a Snake class that will coordinate the movement of all of the body parts:
This class handles the creation of the snake at the specific location as well as moving it in any specific direction. The only missing part is the Direction enum:
Note that we have 2 helper methods to calculate how a particular direction affects x and y coordinates of the snake. For instance, the UP direction will produce deltaY = -1 and deltaX = 0.
The apple model is very simple. The only thing we need to know is the position of an apple which can be described as a pair of integers (x and y):
Now we have a model which describes all objects that can exist in our game’s world. In the next piece we will place those objects on the game screen and make them interact with the player and with each other.