-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
from turtle import Turtle | ||
STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] | ||
MOVE_DISTANCE = 20 | ||
UP = 90 | ||
DOWN = 270 | ||
LEFT = 180 | ||
RIGHT = 0 | ||
|
||
|
||
class Snake: | ||
|
||
def __init__(self): | ||
self.segments = [] | ||
self.create_snake() | ||
self.head = self.segments[0] | ||
|
||
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 reset(self): | ||
for seg in self.segments: | ||
seg.goto(1000, 1000) | ||
self.segments.clear() | ||
self.create_snake() | ||
self.head = self.segments[0] | ||
|
||
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.head.forward(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) |