Snake
Full code
1# Snake game for mPython
2# MIT license,Copyright (c) 2019 labplus@Tangliufeng
3
4from mpython import *
5import random, time
6
7WIDTH, HEIGHT = 127, 63
8
9
10class Direction():
11 """
12 Snake direction, including up/down/left/right
13 """
14
15 UP = 0
16 DOWN = 1
17 LEFT = 2
18 RIGHT = 3
19
20
21class GameState():
22 """
23 Game state
24 """
25 PLAYING = 0
26 PAUSE = 1
27 WIN = 2
28 FAIL = 3
29
30
31class Snake():
32 """
33 Snake
34
35 Build snake
36
37 :param cube(int): grid size, default 4
38 """
39
40 def __init__(self, cube=4):
41
42 self.cube_width = cube
43 self.grid_width_num, self.grid_height_num = WIDTH // self.cube_width, HEIGHT // self.cube_width
44 self.snake_body = []
45 self.snake_body.append((int(self.grid_width_num // 2 * self.cube_width),
46 int(self.grid_height_num // 2 * self.cube_width))) # Add snake "head"
47 self.food_pos = self.generate_food()
48 self.direction = Direction.LEFT
49
50 def draw_grids(self):
51 """
52 Draw grid
53 """
54 for i in range(self.grid_width_num + 1):
55 oled.vline(self.cube_width * i, 0, HEIGHT, 1)
56
57 for i in range(self.grid_height_num + 1):
58 oled.hline(0, self.cube_width * i, WIDTH, 1)
59
60 def draw_body(self):
61 """
62 Draw snake
63 """
64 for sb in self.snake_body:
65 # pygame.draw.rect(screen, WHITE, (sb[0], sb[1], CUBE_WIDTH, CUBE_WIDTH))
66 oled.fill_rect(sb[0], sb[1], self.cube_width, self.cube_width, 1)
67
68 def generate_food(self):
69 """
70 Randomly generate food
71 """
72 self.food_pos = (random.randint(0, self.cube_width - 1), random.randint(0, self.grid_height_num - 1))
73 return self.food_pos
74
75 def draw_food(self):
76 """
77 Draw food
78 """
79 oled.fill_rect(self.food_pos[0] * self.cube_width, self.food_pos[1] * self.cube_width, self.cube_width,
80 self.cube_width, 1)
81
82 def grow(self):
83 """
84 Check if snake ate food, if so grow the snake body
85 """
86 if self.snake_body[0][0] == self.food_pos[0] * self.cube_width and \
87 self.snake_body[0][1] == self.food_pos[1] * self.cube_width:
88 return True
89
90 return False
91
92 def refresh(self):
93 """
94 Update snake body position
95 """
96 for i in range(len(self.snake_body) - 1, 0, -1):
97 self.snake_body[i] = self.snake_body[i - 1]
98
99 def move(self):
100 """
101 Move snake body
102 """
103 if self.direction == Direction.UP:
104 self.snake_body[0] = (self.snake_body[0][0], self.snake_body[0][1] - self.cube_width)
105
106 elif self.direction == Direction.DOWN:
107 self.snake_body[0] = (self.snake_body[0][0], self.snake_body[0][1] + self.cube_width)
108
109 # top += cube_width
110 elif self.direction == Direction.LEFT:
111
112 self.snake_body[0] = (self.snake_body[0][0] - self.cube_width, self.snake_body[0][1])
113
114 # left -= cube_width
115 elif self.direction == Direction.RIGHT:
116 self.snake_body[0] = (self.snake_body[0][0] + self.cube_width, self.snake_body[0][1])
117
118
119class Game():
120 """
121 Snake game control
122 """
123
124 def __init__(self, fps=8):
125 self.snake = Snake()
126 self.get_body = self.snake.snake_body
127 self.state = None
128 self.fps = fps
129 self.handles_cb = None
130
131 def is_win(self):
132 """
133 Check if won
134 """
135 return len(self.get_body) == WIDTH * HEIGHT - 1
136
137 def is_fail(self):
138 """
139 Check if lost
140 """
141 if not 0 <= self.get_body[0][0] < WIDTH or not 0 <= self.get_body[0][1] < HEIGHT:
142 return True
143
144 return False
145
146 @property
147 def score(self):
148 """
149 Game score
150 """
151 return len(self.get_body) - 1
152
153 def handles_accele(self, threshold=0.2):
154 """
155 mPython Board accelerometer control
156 """
157 x = accelerometer.get_x()
158 y = accelerometer.get_y()
159 if y <= 1 and y >= -1:
160 if abs(y) > threshold:
161 if y > 0:
162 self.snake.direction = Direction.LEFT
163 else:
164 self.snake.direction = Direction.RIGHT
165 if x <= 1 and x >= -1:
166 if abs(x) > threshold:
167 if x > 0:
168 self.snake.direction = Direction.DOWN
169 else:
170 self.snake.direction = Direction.UP
171
172 def handles_callback(self, f):
173 """
174 Game control callback, externally customizable
175 """
176 self.handles_cb = f
177
178 def run(self):
179 """
180 Game run
181 """
182 self.state = GameState.PLAYING
183 update_time = time.ticks_ms()
184
185 while self.state == GameState.PLAYING: # Game state is PLAYING
186
187 self.handles_cb() # Game control callback
188
189 # Display frame refresh, update block positions
190 if time.ticks_diff(time.ticks_ms(), update_time) > (1000 // self.fps):
191
192 last_pos = self.get_body[-1] # Save last tail position; if snake ate food, grow at tail
193
194 self.snake.refresh() # Update snake body position
195 self.snake.move() # Change head position
196
197 if self.snake.grow(): # Check if snake ate food, if so grow and generate new food
198 self.snake.generate_food()
199 self.get_body.append(last_pos)
200
201 oled.fill(0) # Clear screen
202 self.snake.draw_body() # Draw snake body
203 self.snake.draw_food() # Draw food
204
205 oled.show() # Display takes effect
206 update_time = time.ticks_ms() # Refresh frame time
207
208 if self.is_fail(): # Check if lost
209 self.state = GameState.FAIL
210 break
211 if self.is_win(): # Check if won
212 self.state = GameState.WIN
213 break
214
215 if self.state == GameState.FAIL: # Lost, display score
216 oled.fill(0)
217 oled.text('Game over!', 25, 20)
218 oled.text('Score:%d' % self.score, 25, 32)
219 oled.show()
220
221 if self.state == GameState.WIN: # Won!
222 oled.fill(0)
223 oled.text('You win!', 25, 20)
224 oled.show()
225
226
227if __name__ == '__main__':
228 game = Game(fps=8)
229 game.handles_callback(game.handles_accele)
230 game.run()