-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.py
126 lines (103 loc) · 2.77 KB
/
snake.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
from microbit import *
from random import randrange
EMPTY = 0
SNAKE = 2
APPLE = 4
game_board = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 2, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
]
# map to be the same as the led matrix
def get_board_state(x, y):
return game_board[y][x]
def set_board_state(x, y, value):
game_board[y][x] = value
def move(snake, x, y):
# (tail_x, tail_y) = snake[-1]
tail_x = snake[-1][0]
tail_y = snake[-1][1]
print("--- move")
print("head: (", x, ", ", y, ")")
print("tail: (", tail_x, ", ", tail_y, ")")
set_board_state(tail_x, tail_y, EMPTY)
snake = snake[:-1]
set_board_state(x, y, SNAKE)
snake.insert(0, [x, y])
return snake
def new_apple():
while True:
apple_x = randrange(5)
apple_y = randrange(5)
if get_board_state(apple_x, apple_y) == EMPTY:
set_board_state(apple_x, apple_y, APPLE)
break
def reset():
for i in range(5):
for j in range(5):
set_board_state(i, j, EMPTY)
set_board_state(2, 2, SNAKE)
new_apple()
return [[2, 2]]
def main():
x = 2
y = 2
prev_x = 2
prev_y = 2
snake = [[x, y]]
new_apple()
while True:
print("x: ", accelerometer.get_x())
print("y: ", accelerometer.get_y())
accel_x = accelerometer.get_x()
accel_y = accelerometer.get_y()
prev_x = x
prev_y = y
if accel_y < -100:
if y > 0:
y = y - 1
else:
y = 4
elif accel_y > 100:
if y < 4:
y = y + 1
else:
y = 0
elif accel_x < -100:
if x > 0:
x = x - 1
else:
x = 4
elif accel_x > 100:
if x < 4:
x = x + 1
else:
x = 0
if prev_x != x or prev_y != y:
if get_board_state(x, y) == APPLE:
set_board_state(x, y, SNAKE)
snake.insert(0, [x, y])
new_apple()
elif get_board_state(x, y) == EMPTY:
snake = move(snake, x, y)
elif get_board_state(x, y) == SNAKE:
display.show(Image.SKULL)
sleep(3000)
snake = reset()
x = 2
y = 2
prev_x = 2
prev_y = 2
for i in range(5):
for j in range(5):
b_state = get_board_state(i, j)
if b_state == SNAKE:
display.set_pixel(i, j, 4)
elif b_state == APPLE:
display.set_pixel(i, j, 7)
else:
display.set_pixel(i, j, 0)
sleep(1000)
main()