-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.py
More file actions
52 lines (41 loc) · 1.37 KB
/
snake.py
File metadata and controls
52 lines (41 loc) · 1.37 KB
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
from turtle import Turtle
STARTING_X = [(0,0), (-20,0), (-40,0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0
class Snake():
def __init__(self):
self.snake = []
self.create_snake()
self.head = self.snake[0]
def create_snake(self):
for position in STARTING_X:
self.get_segment(position)
def get_segment(self, position):
segment = Turtle(shape='square')
segment.penup()
segment.color('white')
segment.goto(position)
self.snake.append(segment)
def extend_segment(self):
self.get_segment(self.snake[-1].position())
def move(self):
for segment in range(len(self.snake)-1, 0, -1):
new_x = self.snake[segment-1].xcor()
new_y = self.snake[segment-1].ycor()
self.snake[segment].goto(new_x,new_y)
self.head.fd(MOVE_DISTANCE)
def up(self):
if self.head.heading() != DOWN:
self.head.setheading(UP)
def down(self):
if self.head.heading() != UP:
self.head.setheading(DOWN)
def left(self):
if self.head.heading() != RIGHT:
self.head.setheading(LEFT)
def right(self):
if self.head.heading() != LEFT:
self.head.setheading(RIGHT)