Created
March 23, 2017 21:09
-
-
Save MightyPork/604e35bbfae89d231a1e2240977acccf to your computer and use it in GitHub Desktop.
microbit-snake
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Add your Python code here. E.g. | |
| from microbit import * | |
| from random import randint as rnd | |
| FREE=0 | |
| UP=1 | |
| RIGHT=2 | |
| DOWN=3 | |
| LEFT=4 | |
| FOOD=5 | |
| class Coord: | |
| def __init__(self, y, x): | |
| self.x = x | |
| self.y = y | |
| def move(self, dir): | |
| if dir == UP: | |
| if self.y > 0: | |
| self.y -= 1 | |
| if dir == DOWN: | |
| if self.y < 4: | |
| self.y += 1 | |
| if dir == LEFT: | |
| if self.x > 0: | |
| self.x -= 1 | |
| if dir == RIGHT: | |
| if self.x < 4: | |
| self.x += 1 | |
| board = [ | |
| [FREE,FREE,FREE,FREE,FREE], | |
| [FREE,FREE,FREE,FREE,FREE], | |
| [FREE,FREE,FREE,FREE,FREE], | |
| [FREE,FREE,FREE,FREE,FREE], | |
| [FREE,FREE,FREE,FREE,FREE] | |
| ]; | |
| def bget(coord): | |
| return board[coord.y][coord.x] | |
| def bset(coord, val): | |
| board[coord.y][coord.x] = val | |
| def put_food(): | |
| while True: | |
| x = rnd(0,4) | |
| y = rnd(0,4) | |
| if board[y][x] == FREE: | |
| board[y][x] = FOOD | |
| break | |
| board[2][0] = RIGHT | |
| board[2][1] = RIGHT | |
| head = Coord(2,1) | |
| tail = Coord(2,0) | |
| put_food() | |
| while True: | |
| for y in range(0,5): | |
| for x in range(0,5): | |
| n = board[y][x] | |
| brt = 0 | |
| if n == FOOD: | |
| brt = 3 | |
| elif x==head.x and y == head.y: | |
| brt = 9 | |
| elif n >= 1 and brt <= 4: | |
| brt = 6 | |
| display.set_pixel(x,y, brt) | |
| sleep(500) | |
| # handle input, move head | |
| dire = bget(head) | |
| if button_a.was_pressed(): | |
| dire -= 1 | |
| if dire == 0: | |
| dire = 4 | |
| if button_b.was_pressed(): | |
| dire += 1 | |
| if dire == 5: | |
| dire = 1 | |
| bset(head, dire) | |
| head.move(dire) | |
| if head.x < 0 or head.x > 4 or head.y < 0 or head.y > 4: | |
| break | |
| oldh = bget(head) | |
| if oldh != FREE and oldh != FOOD: | |
| break | |
| bset(head, dire) | |
| if oldh == FOOD: | |
| put_food() | |
| else: | |
| tt = bget(tail) | |
| bset(tail, FREE) | |
| tail.move(tt) | |
| while True: | |
| if button_a.was_pressed() or button_b.was_pressed(): | |
| reset() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment