Skip to content

Instantly share code, notes, and snippets.

@derpydm derpydm/ Secret
Created Nov 29, 2019

What would you like to do?
Microbit Snake
A caveat:
- movement will be pretty slow because microbit only supports singlethreaded workloads,
so we have to update the screen and detect movement in 1 loop
# Importing of libraries
from microbit import *
from random import randint
#initialise snake, this is its coordinates as 1 dot right now
#we will add more points to this snake variable to signify it growing in size
snake = [[2,2]]
food = [randint(1,4),randint(1,4)]
directions = [[1,0],[0,1],[-1,0],[0,-1]] # in order: right up left down
direction = 0
# main loop
while True:
# check if buttons are pressed
if button_a.is_pressed():
if direction == 0:
direction = 3
direction -= 1
if button_b.is_pressed():
if direction == 3:
direction = 0
direction += 1
# check if win
if len(snake) > 6:
display.scroll("You win!")
# determine next block
next_block = [(snake[0][0] + directions[direction][0]) % 5, (snake[0][1] + directions[direction][1]) % 5]
# if collision occurs
if next_block in snake:
display.scroll("Game Over")
snake = [next_block] + snake
# if snake eats food we generate a new food and keep the snake as is (because snake length will grow by 1)
if food in snake:
while food in snake:
food = [randint(1,4),randint(1,4)]
#if not, remove old square snake was on
# undraw previous points
# set food coord
# draw snake
for coord in snake:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.