-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake.py
76 lines (63 loc) · 2.08 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
72
73
74
75
76
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 0
DOWN = 1
LEFT = 2
RIGHT= 3
class Snake:
def __init__(self):
self.segments = []
self.create_snake()
self.head = self.segments[0]
self.orientation = RIGHT
def create_snake(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
def move(self):
for seg in range(len(self.segments) - 1, 0, -1):
self.segments[seg].goto(self.segments[seg - 1].xcor(), self.segments[seg - 1].ycor())
self.segments[0].forward(MOVE_DISTANCE)
def move_up(self):
if self.orientation == RIGHT:
self.segments[0].left(90)
self.orientation = UP
elif self.orientation == LEFT:
self.segments[0].right(90)
self.orientation = UP
def move_down(self):
if self.orientation == RIGHT:
self.segments[0].right(90)
self.orientation = DOWN
elif self.orientation == LEFT:
self.segments[0].left(90)
self.orientation = DOWN
def move_left(self):
if self.orientation == UP:
self.segments[0].left(90)
self.orientation = LEFT
elif self.orientation == DOWN:
self.segments[0].right(90)
self.orientation = LEFT
def move_right(self):
if self.orientation == UP:
self.segments[0].right(90)
self.orientation = RIGHT
elif self.orientation == DOWN:
self.segments[0].left(90)
self.orientation = RIGHT
def add_segment(self,position):
new_seg = Turtle("square")
new_seg.color("white")
new_seg.penup()
new_seg.goto(position)
self.segments.append(new_seg)
def extend(self):
self.add_segment(self.segments[-1].position())
def reset_snake(self):
for segment in self.segments:
segment.goto(1000,1000)
self.segments.clear()
self.create_snake()
self.head = self.segments[0]
self.orientation = RIGHT