'Changing Turtle Speed

I'm writing a random-walk turtle program and I'm having an issue changing the speed. If I define the turtle (pen) speed outside of the while-loop the turtle speed isn't set and the turtles run a default speed 3. However, if I set the speed inside the while-loop the speed sets correctly. Whats weird is that I can set the turtle shape outside of the while-loop without issue.

Any ideas what is going on?

Luke

from turtle import Turtle, Screen, left, position, right
import turtle
import random
from time import time
from lib import collision



#print("Enter Number of Pins")
total_pens = 2
pen_list = []

for pen in range(total_pens):
    pen = Turtle()
    pen.shape("circle")
  # pen.speed(0)   # I want to set the speed here
    pen_list.append(pen)


_screen = Screen()
_screen.title("Random-Walk")
x_max = 100
y_max = 100
turtle.setworldcoordinates(-x_max, -y_max, x_max, y_max)
wall_position = {"top":y_max, "bottom":-y_max, "left": -x_max, "right":x_max}

pencolor_list = ["red", "blue", "green"]
rotation_list = [0, 90, -90]
travel_range = range(0,100,10)

start_time = time()/60
runtime = 1

while True:
    for pen in pen_list:
        pen.speed(0)  # setting the speed only works here.
        pen.pencolor(random.choice(pencolor_list))
        rotation_direction = random.choice(rotation_list)
        if rotation_direction == 90:
            pen.left(90)
        elif rotation_direction == -90:
            pen.right(90)
        elif rotation_direction == 0:
            pass
        turtle_heading = pen.heading()
        turtle_position = pen.position()
        move_distance = random.choice(travel_range)
        travel_length = collision(wall_position, turtle_position, turtle_heading, move_distance)

        if travel_length[1] > 0:
            pen.forward(travel_length[0])
            pen.left(180)
            pen.forward(travel_length[1])
        else:
            pen.forward(travel_length[0])
        
    end_time = time()/60
    if (end_time - start_time) > runtime:
        break
    else:
        pass

turtle.done()


Solution 1:[1]

I think I know whats going on. The "turtle.setworldcoordinates(-x_max, -y_max, x_max, y_max)" statement is resetting the speed of the turtles for whatever reason.

Solution 2:[2]

I moved the for loop that you want to set speed in to right before the while loop and it controls speed correctly. I think it has something to do with the screen.reset() in the turtle.setworldcoordinates() function.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luke Autry
Solution 2 Austin Heard