The Snake Micro:Bit!

The snake micro:bit is a faithful adaptation of the original video game classic, snake! It is simple, clean, and fun, resulting in a joyful experience for anyone who plays it!

The Code!

//Global Variables

let snake_init = [1,0,0,0]

let snake_sprite: game.LedSprite[] = []

let head=[snake_init[0],snake_init[1]]

let snake_grow = false

let direction = 4;

let direction_movement = [[0, -1], [-1, 0], [0, 1], [1, 0]]

let apple_exist = true

let apple_x = 0;

let apple_y = 0;

let apple:game.LedSprite|null

let score = 0

let movement = direction_movement[Math.abs(direction) % 4]

let delay = 1000

/*Action Methods - Start*/

function make_snake(list2: number[]) {

let snake_sprite: game.LedSprite;

for (let i = 0; i < list2.length; i++) {

if (i % 2 == 0) {

snake_sprite = game.createSprite(list2[i], list2[i + 1])

}

}

}

function move_forward() {

if (direction == -1) {

direction = 3

}

movement = direction_movement[direction % 4]

head[0]=head[0]-movement[0]

head[1]=head[1]-movement[1]

for (let i = 0; i < snake_sprite.length; i++) {

if (head[0] == snake_sprite[i].x() && head[1] == snake_sprite[i].y()) {

game.pause()

basic.showString("You Died! Score: ")

basic.showNumber(score)

}

}

snake_sprite.unshift(game.createSprite(head[0], head[1]));

if (snake_grow == false) {

snake_sprite.pop().delete();

}

else {

snake_grow = false

}

}

function spawn_apple() {

apple_x = Math.floor(Math.random()*5);

apple_y = Math.floor(Math.random() * 5);

while (!check_if_apple_sprite_location_is_available()){

apple_x = Math.floor(Math.random() * 5);

apple_y = Math.floor(Math.random() * 5);

}

apple = game.createSprite(apple_x, apple_y)

apple.setBrightness(100)

}

function check_if_apple_sprite_location_is_available(){

for (let i = 0; i < snake_sprite.length; i++) {

if (apple_x == snake_sprite[i].x() && apple_y == snake_sprite[i].y()) {

return false;

}

}

return true;

}

function eat_apple() {

if (apple.isTouching(snake_sprite[0])) {

apple_exist = false

apple.delete()

snake_grow = true

spawn_apple()

score = score + 1

pause(500)

delay = delay - 100

}

}

/*Action Methods - End*/

/*Event Handler - Begin*/

input.onButtonPressed(Button.A, function () {

direction = direction - 1

})

input.onButtonPressed(Button.B, function () {

direction = direction + 1

})

/*Event Handler Methods - End*/

/*Game Initialization*/

snake_sprite.push(game.createSprite(snake_init[0], snake_init[1]))

snake_sprite.push(game.createSprite(snake_init[0], snake_init[1]))

spawn_apple()

/*Game Loop*/

basic.forever(function on_forever() {

move_forward()

basic.pause(delay)

eat_apple()

if (score >= 9) {

game.pause()

basic.showString("You Won!")

}

if (head.indexOf(5) != -1 || head.indexOf(-1) != -1) {

game.pause()

basic.showString("You Died! Score: ")

basic.showNumber(score)

}

})