0
from turtle import Turtle, Screen
import time

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)
starting_positions = [(0, 0), (-20, 0), (-40, 0)]

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)

    for seg_num in range(len(segments) - 1, 0, -1):
        new_x = segments[seg_num - 1].xcor()
        new_y = segments[seg_num - 1].xcor()
        segments[seg_num].goto(new_x, new_y)

screen.exitonclick()

My problem is in the for loop on line 25. Could anyone explain why there is just one square showing on the screen rather than two because if the third item goes to the second positions coordinates, and the second item goes to the coordinates of the first position, surely there should be two squares?

Sorry if this is unclear, this is the best I can try to explain it. https://i.stack.imgur.com/ed9Ld.png

abcdefg
  • 1
  • 3

1 Answers1

0

The problem is your first (zero index) segment never moves. So fairly quickly all your segments share its position. If we move the first segment as part of the loop, then all the segments slither after it:

from turtle import Turtle, Screen

starting_positions = [(0, 0), (-20, 0), (-40, 0)]

def run():
    if game_is_on:
        for index in range(len(segments) - 1, 0, -1):
            segments[index].setposition(segments[index - 1].position())

        segments[0].forward(20)

    screen.update()
    screen.ontimer(run, 100)

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Snake')
screen.tracer(0)

segments = []

for position in starting_positions:
    turtle = Turtle('square')
    turtle.color('white')
    turtle.penup()
    turtle.goto(position)
    segments.append(turtle)

game_is_on = True

screen.update()

run()

screen.exitonclick()
cdlane
  • 40,441
  • 5
  • 32
  • 81