Skip to main content

Collision Detection

Your game is progressing nicely. Only two more things and you're done: Growing the snake and "Game Over". For the first, you need to check if the snake collides with the fruit. For the second, you need to check if the snake collides with itself.

Collision Detection with the Fruit#

Collision detection can be one of the harder to understand concepts of game development. Lucky for you, this is not the case this time. This game is using a 20x20 grid. Each cell can either be occupied or free. To check this, you can compare the X and Y values of the 2 entities that are checked.

A simple

if (snake.body[0].equals(fruit)) {    // Snake's head hits the fruit}

is enough already to check if the snake eats the fruit. And to make the snake "grow", simply increase the length of the snake using the push function of the array. Now it remains the question what values should this new piece have. The easiest would be to add the current last piece:

let tail = snake.body[snake.body.length - 1]snake.body.push(new Point(tail.x, tail.y))

Once this done, simply relocate the fruit:

fruit.X = rnd(20)fruit.Y = rnd(20)

In its final form, it could look like this:

    if (frameCount % 15 == 0) {        snake.update()
        if (snake.body[0].equals(fruit)) {            let tail = snake.body[snake.body.length - 1]            snake.body.push(new Point(tail.x, tail.y))            fruit.x = rnd(20)            fruit.y = rnd(20)        }    }

Now you're almost done. Only "Game Over" is left to finish this game.

Collision Detection with Itself#

For the player to have any sense of "danger", the game needs a possibility for the player to lose. Usually the snake can't touch itself or it dies. For this, just loop through the body and check if the piece and the head have the same coordinates. Just like with the fruit. But it might be a good idea to move this to its own function:

    isDead(): bool {        const head = this.body[0]        for (let i = 1, len = this.body.length; i < len; i++) {            if (this.body[i].equals(head)) {                return true            }        }
        return false    }

Now you can call this function to check if the snake died in this frame:

    if (frameCount % 15 == 0) {        snake.update()
        if (snake.isDead()) {            // Do something        }
        if (snake.body[0].equals(fruit)) {            let tail = snake.body[snake.body.length - 1]            snake.body.push(new Point(tail.x, tail.y))            fruit.x = rnd(20)            fruit.y = rnd(20)        }    }

What you do, is up to you. You could stop the game and show the score. Or you could simply reset the game. Up to you.