Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# MICROSNAKE
from microbit import *
from random import randint
def drop_food():
global food
food = [randint(0,4), randint(0,4)]
while food in snake:
food = [randint(0,4), randint(0,4)]
def draw_snake(a=4, b=2):
if len(snake) > 0:
for part in snake:
display.set_pixel(part[0], part[1], b)
display.set_pixel(snake[0][0], snake[0][1], a)
def start_game():
global snake, direct, got_food
snake = [[1,2], [0,2]]
direct = 0
got_food = False
drop_food()
draw_snake()
sleep(speed)
playing = False
death = False
while(True):
if not playing and not death:
sleep(100)
if button_a.is_pressed() and button_b.is_pressed():
playing = True
speed = 800
start_game()
if playing:
move = 0
for i in range(10):
if button_a.is_pressed():
move = 1
if button_b.is_pressed():
move = -1
sleep(speed/10)
direct = (direct + move) % 4
if got_food == True:
snake.append([0,0])
for i in range(len(snake)):
n = len(snake)-i-1;
if n > 0:
display.set_pixel(snake[n][0], snake[n][1], 0)
newx = snake[n-1][0]
newy = snake[n-1][1]
snake[n] = [newx, newy]
if direct == 0: # east
snake[0][0] += 1
elif direct == 1: # north
snake[0][1] -= 1
elif direct == 2: # west
snake[0][0] -= 1
elif direct == 3: # south
snake[0][1] += 1
snake[0][0] = snake[0][0] % 5
snake[0][1] = snake[0][1] % 5
if snake[0] in snake[1::]:
death = True
playing = False
if not death:
draw_snake()
if snake[0] == food:
display.set_pixel(food[0], food[1], 7)
got_food = True
drop_food()
else:
display.set_pixel(food[0], food[1], 5)
got_food = False
if death:
display.set_pixel(food[0], food[1], 0)
draw_snake(6, 6)
for i in range(3):
sleep(300)
draw_snake(2, 2)
sleep(300)
draw_snake(6, 6)
while len(snake) > 0:
draw_snake(0, 0)
snake = snake[:-1]
draw_snake(5, 5)
sleep(300)
death = False
@mypassengers

This comment has been minimized.

Copy link

mypassengers commented Jan 29, 2019

your code doesn`t work
Traceback (most recent call last):
File "C:/Users/Administrator/PycharmProjects/snake/snake.py", line 2, in
from microbit import *
ModuleNotFoundError: No module named 'microbit'

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.