-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake_game.py
91 lines (75 loc) · 2.98 KB
/
snake_game.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
import pygame
import math
import random
from snake import snake
pygame.init()
clock = pygame.time.Clock()
score = 0
x_max = 600
y_max = 600
length_squares = 20
line_width = 2
square_size = math.floor(x_max / length_squares)
FPS = 15
apple_coordinate = (random.randint(1, length_squares - 1), random.randint(1, length_squares - 1))
size = (x_max, y_max)
screen = pygame.display.set_mode(size)
snk = snake()
still_running = True
while still_running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
still_running = False
snk.move() # Move body, not head
curr_head_pos = snk.get_head()
keys = pygame.key.get_pressed()
# Update direction of head from key press
if (keys[pygame.K_UP] and not (snk.get_dir() == 'down')):
snk.set_dir('up')
elif (keys[pygame.K_DOWN] and not (snk.get_dir() == 'up')):
snk.set_dir('down')
elif (keys[pygame.K_LEFT] and not (snk.get_dir() == 'right')):
snk.set_dir('left')
elif (keys[pygame.K_RIGHT] and not (snk.get_dir() == 'left')):
snk.set_dir('right')
# Use snake head direction to update position of head
if snk.get_dir() == 'up':
snk.set_head((curr_head_pos[0], curr_head_pos[1] - 1))
elif snk.get_dir() == 'down':
snk.set_head((curr_head_pos[0], curr_head_pos[1] + 1))
elif snk.get_dir() == 'left':
snk.set_head((curr_head_pos[0] - 1, curr_head_pos[1]))
elif snk.get_dir() == 'right':
snk.set_head((curr_head_pos[0] + 1, curr_head_pos[1]))
curr_head_pos = snk.get_head()
# Check to see if snake head is going to hit a wall, end game if true
if snk.is_crashing_into_wall(length_squares) or snk.is_eating_body():
print("Score: {}".format(score))
snk.reset()
score = 0
# Check if snake head is in space with apple
if curr_head_pos == apple_coordinate:
snk.grow_body()
score = score + 1
while True:
apple_coordinate = (random.randint(0, length_squares - 1), random.randint(0, length_squares - 1))
if not snk.is_new_apple_in_body(apple_coordinate):
break
# Render
screen.fill("black")
# Drawing apple
x = square_size*apple_coordinate[0]
y = square_size*apple_coordinate[1]
pygame.draw.rect(screen, 'red', [x, y, square_size, square_size])
# Drawing snake
for i in range(snk.get_length()):
x = square_size*(snk.body[i][0][0])
y = square_size*(snk.body[i][0][1])
pygame.draw.rect(screen, 'green', [x, y, square_size, square_size])
# Drawing grid play area
for i in range(1,length_squares):
pygame.draw.line(screen, 'white', [square_size*(i), 0], [square_size*(i), y_max], line_width)
pygame.draw.line(screen, 'white', [0, square_size*(i)], [x_max, square_size*(i)], line_width)
pygame.display.flip()
pygame.quit()