Skip to content

Instantly share code, notes, and snippets.

@derpydm derpydm/microBitsnake.py Secret
Created Nov 29, 2019

Embed
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
else:
direction -= 1
if button_b.is_pressed():
if direction == 3:
direction = 0
else:
direction += 1
sleep(100)
# 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")
break
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
else:
snake.pop()
# undraw previous points
display.clear()
# set food coord
display.set_pixel(food[0],food[1],9)
# draw snake
for coord in snake:
display.set_pixel(coord[0],coord[1],4)
sleep(400)
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.