Advertisement
JkSoftware

snake.py

Dec 5th, 2021
758
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from turtle import Turtle
  2. STARTING_POSITIONS = [(0,0), (-20,0), (-40,0)]
  3. MOVE_DISTANCE = 20
  4.  
  5.  
  6. class Snake:
  7.     def __init__(self):
  8.         self.segments = []
  9.         self.create_snake()
  10.         self.head = self.segments[0]
  11.  
  12.     def create_snake(self):
  13.         for position in STARTING_POSITIONS:
  14.             self.add_segment(position)
  15.  
  16.     def move(self):
  17.         for seg_num in range(len(self.segments) - 1, 0, -1):
  18.             new_x = self.segments[seg_num - 1].xcor()
  19.             new_y = self.segments[seg_num - 1].ycor()
  20.             self.segments[seg_num].goto(new_x, new_y)
  21.         self.head.forward(MOVE_DISTANCE)
  22.  
  23.     def up(self):
  24.         if self.head.heading() != 270:
  25.             self.head.setheading(90)
  26.  
  27.     def down(self):
  28.         if self.head.heading() != 90:
  29.             self.head.setheading(270)
  30.  
  31.     def right(self):
  32.         if self.head.heading() != 180:
  33.             self.head.setheading(0)
  34.  
  35.     def left(self):
  36.         if self.head.heading() != 0:
  37.             self.head.setheading(180)
  38.  
  39.     def extend(self):
  40.         self.add_segment(self.segments[-1].position())
  41.  
  42.     def add_segment(self, position):
  43.         new_segment = Turtle("square")
  44.         new_segment.color("white")
  45.         new_segment.penup()
  46.         new_segment.goto(position)
  47.         self.segments.append(new_segment)
Advertisement
Advertisement
Advertisement
RAW Paste Data Copied
Advertisement