-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.py
48 lines (36 loc) · 1.3 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
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
def add_segment(self, position):
new_segment = Turtle("square")
new_segment.color('white')
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)
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_x = self.segments[seg_num - 1].xcor()
new_y = self.segments[seg_num - 1].ycor()
self.segments[seg_num].goto(new_x, new_y)
self.segments[0].forward(MOVE_DISTANCE)
def up(self):
if self.segments[0].heading() != 270:
self.segments[0].setheading(90)
def down(self):
if self.segments[0].heading() != 90:
self.segments[0].setheading(270)
def left(self):
if self.segments[0].heading() != 0:
self.segments[0].setheading(180)
def right(self):
if self.segments[0].heading() != 180:
self.segments[0].setheading(0)