-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsnake.py
More file actions
87 lines (65 loc) · 2.25 KB
/
snake.py
File metadata and controls
87 lines (65 loc) · 2.25 KB
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
import pygame
from pygame.locals import *
import random
WINDOW_SIZE = (600, 600)
PIXEL_SIZE = 10
def collision(pos1, pos2):
return pos1 == pos2
def off_limits(pos):
if 0 <= pos[0] < WINDOW_SIZE[0] and 0 <= pos[1] < WINDOW_SIZE[1]:
return False
else:
return True
def random_on_grid():
x = random.randint(0, WINDOW_SIZE[0])
y = random.randint(0, WINDOW_SIZE[1])
return x // PIXEL_SIZE * PIXEL_SIZE, y // PIXEL_SIZE * PIXEL_SIZE
pygame.init()
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption('Snake')
snake_pos = [(250, 50), (260, 50), (270, 50)]
snake_surface = pygame.Surface((PIXEL_SIZE, PIXEL_SIZE))
snake_surface.fill((255, 255, 255))
snake_direction = K_LEFT
apple_surface = pygame.Surface((PIXEL_SIZE, PIXEL_SIZE))
apple_surface.fill((255, 0, 0))
apple_pos = random_on_grid()
def restart_game():
global snake_pos
global apple_pos
global snake_direction
snake_pos = [(250, 50), (260, 50), (270, 50)]
snake_direction = K_LEFT
apple_pos = random_on_grid()
while True:
pygame.time.Clock().tick(15)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
quit()
elif event.type == KEYDOWN:
if event.key in [K_UP, K_DOWN, K_LEFT, K_RIGHT]:
snake_direction = event.key
screen.blit(apple_surface, apple_pos)
if collision(apple_pos, snake_pos[0]):
snake_pos.append((-10, -10))
apple_pos = random_on_grid()
for pos in snake_pos:
screen.blit(snake_surface, pos)
for i in range(len(snake_pos) - 1, 0, -1):
if collision(snake_pos[0], snake_pos[i]):
restart_game()
break
snake_pos[i] = snake_pos[i - 1]
if off_limits(snake_pos[0]):
restart_game()
if snake_direction == K_UP:
snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] - PIXEL_SIZE)
elif snake_direction == K_DOWN:
snake_pos[0] = (snake_pos[0][0], snake_pos[0][1] + PIXEL_SIZE)
elif snake_direction == K_LEFT:
snake_pos[0] = (snake_pos[0][0] - PIXEL_SIZE, snake_pos[0][1])
elif snake_direction == K_RIGHT:
snake_pos[0] = (snake_pos[0][0] + PIXEL_SIZE, snake_pos[0][1])
pygame.display.update()