-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
485 lines (334 loc) · 15.2 KB
/
main.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import utime
from random import randint
import picodisplay as display
# picodisplay boilerplate code
width = display.get_width()
height = display.get_height()
display_buffer = bytearray(width * height * 2)
display.init(display_buffer)
backlight_intensity = 0.6
display.set_backlight(backlight_intensity)
# initialize global variables for game
tile_size = 12 # size in pixels of square tiles
grid_w, grid_h = 20, 11 # 20*11 tiles
# color data
snake_color = (0, 200, 0)
food_color = (200, 0, 0)
wall_color = (200, 0, 200)
title_color = (255, 255, 0)
score_color = (255, 255, 255)
class SnakeNode:
def __init__(self, position=None, direction=None, next=None):
self.pos = position
self.dir = direction
self.next = next
class Snake:
def __init__(self):
center_of_grid = grid_w//2, grid_h//2
self.direction = (0, 0)
self.head = SnakeNode(center_of_grid, self.direction)
def push(self, new_head):
new_head.next, self.head = self.head, new_head
def pop(self):
current_node = self.head
previous_node = None
# loop through entire list of SnakeNodes
while current_node.next != None:
previous_node = current_node
current_node = current_node.next
# loop ends: final node in current_node, penultimate node in previous_node
# if there is a previous_node (i.e. this is not the head node)
if previous_node != None:
previous_node.next = None # clear pointer to final node
def contains(self, position):
current_node = self.head
while current_node != None:
if current_node.pos == position:
return True
current_node = current_node.next
return False
def move(self):
# unpack direction and position of head node
x_dir, y_dir = self.direction
head_x, head_y = self.head.pos
# update position according to direction
head_x += x_dir
head_y += y_dir
# keep position within grid boundaries
head_x %= grid_w
head_y %= grid_h
# create and return new head node
new_head_position = head_x, head_y
new_node = SnakeNode(new_head_position, self.direction)
return new_node
def show(self):
snake_red, snake_green, snake_blue = snake_color
display.set_pen(snake_red, snake_green, snake_blue)
current_node = self.head
while current_node != None:
if current_node != self.head:
x1, y1 = current_node.pos
x2, y2 = previous_node.pos
invisible = (abs(x1-x2)>1)or(abs(y1-y2)>1)
if not invisible:
x1 *= tile_size
y1 *= tile_size
x2 *= tile_size
y2 *= tile_size
x1 += tile_size//2
y1 += tile_size//2
x2 += tile_size//2
y2 += tile_size//2
self.line(x1, y1, x2, y2)
else:
# draw circle for snake head
grid_x, grid_y = current_node.pos
canvas_x = (tile_size * grid_x)
canvas_y = (tile_size * grid_y)
center_x = canvas_x+(tile_size//2)
center_y = canvas_y+(tile_size//2)
radius = (tile_size-4)//2
display.circle(center_x, center_y, radius)
previous_node = current_node
current_node = current_node.next
def moving(self):
return self.direction != (0, 0)
def update_direction(self, pressed):
x_dir, y_dir = self.direction
if pressed['A']:
if self.direction[0] == 0:
x_dir = -1
y_dir = 0
elif pressed['Y']:
if self.direction[0] == 0:
x_dir = 1
y_dir = 0
elif pressed['B']:
x_dir = 0
if self.direction[1] == 0:
y_dir = 1
elif pressed['X']:
x_dir = 0
if self.direction[1] == 0:
y_dir = -1
self.direction = x_dir, y_dir
def line(self, x1, y1, x2, y2):
start_x = min(x1, x2)
start_y = min(y1, y2)
line_thickness = 4
offset = line_thickness//2
start_x -= offset
start_y -= offset
# for horizontal lines
if x1 == x2:
line_width = offset * 2
line_height = offset + abs(y1-y2) + offset
# for vertical lines
elif y1 == y2:
line_width = offset + abs(x1-x2) + offset
line_height = offset * 2
display.rectangle(start_x, start_y, line_width, line_height)
class Game:
def __init__(self):
self.pressed = {}
self.frameCount = 0
self.score = 0
self.target_score = 5
self.base_refresh = 0.01
self.countdown = 20
self.cooldown = self.countdown
self.slow, self.fast = 12, 2
self.level_number = 0
self.total_levels = 4
self.game_state = {"title_screen": 0,
"level_name": 1,
"lives_left": 2,
"playing": 3,
"show_score": 4,
"game_over": 5}
self.state = self.game_state['title_screen']
# initialize current level
def init_level(self):
self.level = Level(self.level_number)
self.snake = Snake()
self.food = Food(self.snake, self.level)
self.score = 0
# update game data
def tick(self):
self.frame_skip = int(self.map_to_range(self.score, 0, 50, self.slow, self.fast))
if self.frameCount % self.frame_skip == 0:
self.update_inputs()
self.draw_background()
if self.state == self.game_state['playing']:
self.draw_game_objects()
self.snake.update_direction(self.pressed)
new_head = self.snake.move()
if new_head.pos == self.food.pos:
self.score += 1
self.snake.push(new_head)
self.food.reset_position(self.snake, self.level)
elif (self.snake.moving() and (self.snake.contains(new_head.pos) or self.level.check_walls(new_head.pos))):
self.cooldown = self.countdown
self.state = self.game_state['show_score']
else:
self.snake.push(new_head)
self.snake.pop()
else:
self.cooldown -= 1
self.show_game_text()
if self.cooldown < 0:
self.cooldown = self.countdown
if self.state == self.game_state['title_screen']:
self.lives_left = 3
self.level_number = 0
self.state = self.game_state['level_name']
elif self.state == self.game_state['level_name']:
self.init_level()
self.state = self.game_state['lives_left']
elif self.state == self.game_state['lives_left']:
self.state = self.game_state['playing']
elif self.state == self.game_state['show_score']:
if self.score > self.target_score:
self.level_number += 1
self.level_number %= self.total_levels
else:
self.lives_left -= 1
if self.lives_left == 0:
self.state = self.game_state['game_over']
else:
self.state = self.game_state['level_name']
elif self.state == self.game_state['game_over']:
self.state = self.game_state['title_screen']
display.update()
self.frameCount += 1
utime.sleep(self.base_refresh)
# user input button methods
def update_inputs(self):
self.pressed['A'] = display.is_pressed(display.BUTTON_A)
self.pressed['B'] = display.is_pressed(display.BUTTON_B)
self.pressed['X'] = display.is_pressed(display.BUTTON_X)
self.pressed['Y'] = display.is_pressed(display.BUTTON_Y)
def any_button(self, pressed):
return self.pressed['A'] or self.pressed['B'] or self.pressed['X'] or self.pressed['Y']
# graphics methods
def draw_background(self):
display.set_pen(0, 0, 0)
display.clear()
def draw_game_objects(self):
self.food.show()
self.level.show()
self.snake.show()
def show_game_text(self):
title_red, title_green, title_blue = title_color
display.set_pen(title_red, title_green, title_blue)
if self.state == self.game_state['title_screen']:
display.text("PiCo", int(width/6), int(height/16), 10, 8)
display.text("Snake", int(width/16), int(height/2), 10, 8)
elif self.state == self.game_state['level_name']:
display.set_pen(150, 255, 255)
display.text("Level", int(width/12), int(height/16), 10, 8)
display.set_pen(255, 255, 255)
display.text(str(self.level_number), int(7*width/16), int(height/2), 10, 8)
elif self.state == self.game_state['lives_left']:
display.set_pen(0, 255, 0)
display.text("Lives", int(width/12), int(height/16), 10, 8)
if self.lives_left == 3:
display.set_pen(220, 220, 0)
elif self.lives_left == 2:
display.set_pen(220, 110, 0)
elif self.lives_left == 1:
display.set_pen(220, 0, 0)
display.text(str(self.lives_left), int(14*width/16), int(height/2), 10, 8)
elif self.state == self.game_state['show_score']:
self.draw_game_objects()
display.set_pen(255, 255, 255)
display.text("SCORE", int(width/16), int(height/16), 10, 8)
display.text(str(self.score), int(2*width/5), int(height/2), 10, 8)
elif self.state == self.game_state['game_over']:
self.draw_game_objects()
display.set_pen(255, 255, 255)
display.text("Game", int(width/6), int(height/16), 10, 8)
display.text("Over", int(width/16), int(height/2), 10, 8)
def debug_pattern(self):
alternate_color = False
for j in range(grid_h):
for i in range(grid_w):
if alternate_color:
display.set_pen(0, 0, 255)
else:
display.set_pen(255, 0, 255)
tile_x = i * tile_size
tile_y = j * tile_size
display.rectangle(tile_x, tile_y, tile_size, tile_size)
alternate_color = not alternate_color
alternate_color = not alternate_color
# simple range mapping method
def map_to_range(self, val, min_1, max_1, min_2, max_2):
if val <= min_1:
return min_2
elif val >= max_1:
return max_2
else:
diff_1 = max_1 - min_1
ratio_1 = (val-min_1)/diff_1
diff_2 = max_2 - min_2
ratio_2 = (ratio_1*diff_2) + min_2
return ratio_2
class Food:
def __init__(self, snake, level):
self.reset_position(snake, level)
# sets new position for Food
def reset_position(self, snake, level):
new_pos = randint(0, grid_w-1), randint(0, grid_h-1)
# re-calculate if random position inside snake or walls
while snake.contains(new_pos) or level.check_walls(new_pos):
new_pos = randint(0, grid_w-1), randint(0, grid_h-1)
self.pos = new_pos
def show(self):
food_x, food_y = self.pos
food_red, food_green, food_blue = food_color
display.set_pen(food_red, food_green, food_blue)
# calculate center of tile on canvas
tile_x = (tile_size * food_x) + tile_size//2
tile_y = (tile_size * food_y) + tile_size//2
radius = (tile_size-2)//2
display.circle(tile_x, tile_y, radius)
class Level:
def __init__(self, level_number):
self.load_level(level_number)
# a Level consists of walls (co-ordinates of immovable blocks)
def load_level(self, level_number):
self.walls = []
# level data loaded from file level-*.txt
filename = "level-" + str(level_number) + ".txt"
f = open(filename, "r")
lines = f.readlines()
# each '0' on a line represents a wall
for y, line in enumerate(lines):
for x, char in enumerate(line):
if 0 <= x < grid_w and 0 <= y < grid_h and char == '0':
wall_pos = x, y
self.walls.append(wall_pos)
f.close()
# check if position is in walls
def check_walls(self, pos):
for wall in self.walls:
if pos == wall:
return True
return False
# draw wall graphics
def show(self):
wall_red, wall_blue, wall_green = wall_color
for wall in self.walls:
grid_x, grid_y = wall
tile_x = grid_x * tile_size
tile_y = grid_y * tile_size
display.set_pen(wall_red, wall_blue, wall_green)
display.rectangle(tile_x, tile_y, tile_size, tile_size)
display.set_pen(wall_red//2, wall_blue//2, wall_green//2)
display.rectangle(tile_x+2, tile_y+2, tile_size-4, tile_size-4)
# initialize game
game = Game()
# run game loop
while True:
game.tick()