-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.py
71 lines (58 loc) · 1.8 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
61
62
63
64
65
66
67
68
69
70
71
from turtle import Turtle
MOVE_DISTANCE = 20
UP = 90
LEFT = 180
DOWN = 270
RIGHT = 0
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
SHAPE = "turtle"
COLOR = "pink"
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
self.speed = MOVE_DISTANCE
def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
def reset_snake(self):
for seg in self.segments:
seg.goto(10000, 10000)
self.segments.clear()
self.create_snake()
self.head = self.segments[0]
def add_segment(self, position):
snake = Turtle(shape=SHAPE)
snake.penup()
snake.color(COLOR)
snake.setpos(position)
self.segments.append(snake)
def extend(self):
self.add_segment(self.segments[-1].position())
def move(self):
for seg_num in range(len(self.segments) - 1, 0, -1):
new_head = self.segments[seg_num - 1].heading()
new_x = self.segments[seg_num - 1].xcor()
new_y = self.segments[seg_num - 1].ycor()
self.segments[seg_num].seth(new_head)
self.segments[seg_num].goto(new_x, new_y)
self.head.forward(self.speed)
def up(self):
if self.head.heading() != DOWN:
self.head.seth(UP)
def left(self):
if self.head.heading() != RIGHT:
self.head.seth(LEFT)
def down(self):
if self.head.heading() != UP:
self.head.seth(DOWN)
def right(self):
if self.head.heading() != LEFT:
self.head.seth(RIGHT)
# def pause(self):
# if self.speed == MOVE_DISTANCE:
# self.speed = 0
# elif self.speed == 0:
# self.speed = MOVE_DISTANCE
#