Created
March 7, 2020 14:27
-
-
Save basile-henry/61d3c7ab6c9d4b7e5f380b0be55aa32e to your computer and use it in GitHub Desktop.
Snake MicroBit
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 * | |
| import random | |
| def create_dots(dots): | |
| s = "" | |
| for y in range(5): | |
| for x in range(5): | |
| if (x, y) in dots: | |
| s += '9' | |
| else: | |
| s += '0' | |
| s += ":" | |
| return Image(s) | |
| UP = 0 | |
| RIGHT = 1 | |
| DOWN = 2 | |
| LEFT = 3 | |
| THRESH = 512 | |
| class Snake: | |
| def __init__(self, size=2, start=(2,2)): | |
| self.body = [start for _ in range(size)] | |
| self.direction = UP | |
| def eat(self, food_pos): | |
| if self.body[0] == food_pos: | |
| self.body += [self.body[-1]] | |
| return True | |
| return False | |
| def move(self): | |
| (x, y) = self.body[0] | |
| if self.direction == UP: | |
| y = (y - 1) % 5 | |
| elif self.direction == RIGHT: | |
| x = (x + 1) % 5 | |
| elif self.direction == DOWN: | |
| y = (y + 1) % 5 | |
| elif self.direction == LEFT: | |
| x = (x - 1) % 5 | |
| self.body = [(x, y)] + self.body[:-1] | |
| return self.body[0] in self.body[1:] | |
| def turn(self): | |
| if self.direction in [UP, DOWN]: | |
| dx = accelerometer.get_x() | |
| if dx > THRESH: | |
| self.direction = RIGHT | |
| elif dx < -THRESH: | |
| self.direction = LEFT | |
| elif self.direction in [RIGHT, LEFT]: | |
| dy = accelerometer.get_y() | |
| if dy > THRESH: | |
| self.direction = DOWN | |
| elif dy < -THRESH: | |
| self.direction = UP | |
| def new_pos(): | |
| return (random.randint(0, 4), random.randint(0, 4)) | |
| snake = Snake() | |
| food = new_pos() | |
| while not snake.move(): | |
| print(food) | |
| for i in range(8): | |
| dots = snake.body[:] | |
| if i % 2 == 0: | |
| dots += [food] | |
| display.show(create_dots(dots)) | |
| sleep(100) | |
| snake.turn() | |
| if snake.eat(food): | |
| food = new_pos() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment