-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.py
60 lines (58 loc) · 2.33 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
import pygame as pg
from random import randrange
WINDOW = 1000
TILE_SIZE = 50
RANGE = (TILE_SIZE // 2, WINDOW - TILE_SIZE // 2, TILE_SIZE)
get_random_position = lambda: [randrange(*RANGE), randrange(*RANGE)]
snake = pg.rect.Rect([0, 0, TILE_SIZE - 2, TILE_SIZE - 2])
snake.center = get_random_position()
length = 1
segments = [snake.copy()]
snake_dir = (0, 0)
time, time_step = 0, 110
food = snake.copy()
food.center = get_random_position()
screen = pg.display.set_mode([WINDOW] * 2)
clock = pg.time.Clock()
dirs = {pg.K_UP: 1, pg.K_DOWN: 1, pg.K_LEFT: 1, pg.K_RIGHT: 1}
while True:
for event in pg.event.get():
if event.type ==pg.QUIT:
exit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_UP and dirs[pg.K_UP]:
snake_dir = (0, -TILE_SIZE)
dirs = {pg.K_UP: 1, pg.K_DOWN: 0, pg.K_LEFT: 1, pg.K_RIGHT: 1}
if event.key == pg.K_DOWN and dirs[pg.K_DOWN]:
snake_dir = (0, TILE_SIZE)
dirs = {pg.K_UP: 0, pg.K_DOWN: 1, pg.K_LEFT: 1, pg.K_RIGHT: 1}
if event.key == pg.K_LEFT and dirs[pg.K_LEFT]:
snake_dir = (-TILE_SIZE, 0)
dirs = {pg.K_UP: 1, pg.K_DOWN: 1, pg.K_LEFT: 1, pg.K_RIGHT: 0}
if event.key == pg.K_RIGHT and dirs[pg.K_RIGHT]:
snake_dir = (TILE_SIZE, 0)
dirs = {pg.K_UP: 1, pg.K_DOWN: 1, pg.K_LEFT: 0, pg.K_RIGHT: 1}
screen.fill('black')
#check borders selfeating
self_eating = pg.Rect.collidelist(snake, segments[:-1]) != -1
if snake.left < 0 or snake .right > WINDOW or snake.top < 0 or snake.bottom > WINDOW or self_eating:
snake.center, food.center = get_random_position(), get_random_position()
length, snake_dir = 1, (0, 0)
segments = [snake.copy()]
#check food
if snake.center == food.center:
food.center = get_random_position()
length += 1
#draw food
pg.draw.rect(screen, 'red', food)
#draw snake
[pg.draw.rect(screen, 'green', segment) for segment in segments]
#move snake
time_now = pg.time.get_ticks()
if time_now - time > time_step:
time = time_now
snake.move_ip(snake_dir)
segments.append(snake.copy())
segments = segments[-length:]
pg.display.flip()
clock.tick(60)