MCPcopy Index your code
hub / github.com/geekcomputers/Python / Snake

Class Snake

Snake Game Using Turtle/snake.py:12–72  ·  view source on GitHub ↗

This class creates a snake body and contains methods for movement and extension.

Source from the content-addressed store, hash-verified

10UP, DOWN, LEFT, RIGHT = 90, 270, 180, 0
11
12class Snake:
13 """ This class creates a snake body and contains methods for movement and extension. """
14 def __init__(self):
15 self.segments = []
16 self.create_snake()
17 self.head = self.segments[0]
18
19 def create_snake(self):
20 """ Creates the initial snake body. """
21 for position in STARTING_POSITIONS:
22 self.add_segment(position)
23 self.segments[0].color(colors.FIRST_SEGMENT_COLOR)
24
25 def add_segment(self, position):
26 """ Adds a new segment to the snake. """
27 new_segment = Turtle(shape="square")
28 new_segment.penup()
29 new_segment.goto(position)
30 new_segment.color(colors.BODY_COLOR)
31 self.segments.append(new_segment)
32
33 def extend(self):
34 """ Adds a new segment to the snake's tail. """
35 self.add_segment(self.segments[-1].position())
36 self.segments[0].color(colors.FIRST_SEGMENT_COLOR)
37
38 def move(self):
39 """ Moves the snake forward by moving each segment to the position of the one in front."""
40 for i in range(len(self.segments) - 1, 0, -1):
41 x = self.segments[i - 1].xcor()
42 y = self.segments[i - 1].ycor()
43 self.segments[i].goto(x, y)
44 self.head.forward(MOVE_DISTANCE)
45
46 def reset(self):
47 """Hides the old snake and creates a new one for restarting the game."""
48 for segment in self.segments:
49 segment.hideturtle()
50 self.segments.clear()
51 self.create_snake()
52 self.head = self.segments[0]
53
54 def up(self):
55 """Turns the snake's head upwards, preventing it from reversing."""
56 if self.head.heading() != DOWN:
57 self.head.setheading(UP)
58
59 def down(self):
60 """Turns the snake's head downwards, preventing it from reversing."""
61 if self.head.heading() != UP:
62 self.head.setheading(DOWN)
63
64 def left(self):
65 """Turns the snake's head to the left, preventing it from reversing."""
66 if self.head.heading() != RIGHT:
67 self.head.setheading(LEFT)
68
69 def right(self):

Callers 1

main.pyFile · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected