-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.py
82 lines (69 loc) · 1.92 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
import pygame
import time
from snake import Snake, Food, losing_message, score_message
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
BLACK = (0, 0, 0)
pygame.init()
clock = pygame.time.Clock()
# Create screen
SCREEN_HEIGHT = 400
SCREEN_WIDTH = 600
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# Create an initially stationary snake
snake = Snake((SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2))
food = Food(SCREEN_WIDTH, SCREEN_HEIGHT)
direction = [0, 0]
# Instantiate score
score = 0
# Run until the user asks to quit
running = True
is_survived = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
# Check whether snake changes direction by key pressing
keys_pressed = pygame.key.get_pressed()
if keys_pressed[K_UP]:
direction = [0, -1]
elif keys_pressed[K_DOWN]:
direction = [0, 1]
elif keys_pressed[K_LEFT]:
direction = [-1, 0]
elif keys_pressed[K_RIGHT]:
direction = [1, 0]
snake.change_direction(direction)
# Check whether snake eats, move the snake and see if they survive
if snake.get_head_pos() == food.get_pos():
snake.grow()
del food
food = Food(SCREEN_WIDTH, SCREEN_HEIGHT)
score += 1
else:
is_survived = snake.move_and_survive(SCREEN_WIDTH, SCREEN_HEIGHT)
if not is_survived:
running = False
# Draw things on screen
screen.fill(BLACK)
snake.draw(screen)
food.draw(screen)
score_message(score, screen, SCREEN_WIDTH, SCREEN_HEIGHT)
pygame.display.update()
# Dictates snake speed
clock.tick(10)
# Done! Time to quit.
losing_message("You lost", screen, SCREEN_WIDTH, SCREEN_HEIGHT)
pygame.display.update()
time.sleep(2)
pygame.quit()