-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake.py
59 lines (46 loc) · 1.73 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
from turtle import Turtle
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVEDISTANCE = 20
class Snake():
def __init__(self) -> None:
self.segments = []
self.current_dir = 'right'
self.createSegments()
def createSegments(self):
for position in STARTING_POSITIONS:
self.add_segment(position)
self.head = self.segments[0]
def add_segment(self, position):
"""
this method is to add new segment"""
new_segment = Turtle("square")
new_segment.color("green")
new_segment.penup()
new_segment.goto(position)
self.segments.append(new_segment)
def moveSnake(self):
for i in range(len(self.segments) - 1, 0, -1):
x_new = self.segments[i - 1].xcor()
y_new = self.segments[i - 1].ycor()
self.segments[i].goto(x_new, y_new)
self.head.forward(MOVEDISTANCE)
def turn_up(self):
if self.current_dir == 'right' or self.current_dir == 'left':
self.head.setheading(90)
self.current_dir = 'up'
def turn_right(self):
if self.current_dir == 'up' or self.current_dir == 'down':
self.head.setheading(0)
self.current_dir = 'right'
def turn_down(self):
if self.current_dir == 'left' or self.current_dir == 'right':
self.head.setheading(270)
self.current_dir = 'down'
def turn_left(self):
if self.current_dir == 'up' or self.current_dir == 'down':
self.head.setheading(180)
self.current_dir = 'left'
def extend(self):
""""
This method is to extend the body of the snake when it get food"""
self.add_segment(self.segments[-1].position())