I'm a CS teacher, and we wrote some Python code in class to have a turtle draw a random walk. Someone asked if we could draw a new turtle that will trace the route (from starting point to ending point) that will take the minimum path. Current code is below.
I suspect we'll have to start a list of coordinates and then create some kind of tree. I'm sure there's already a library to do this, just not sure.
import turtle
import random
import time
from math import sqrt
leo = turtle.Turtle()
leo.speed(0)
leo.color("green")
leo.dot(6) # mark the starting location
leo.color("black")
directions = ['N', 'S', 'E', 'W']
steps = 100
step_size = 10
start = time.time()
for i in range(steps):
heading = random.choice(directions)
if heading == 'N':
leo.setheading(90)
elif heading == 'S':
leo.setheading(270)
elif heading == 'E':
leo.setheading(0)
else:
leo.setheading(180)
leo.forward(step_size)
(x,y) = leo.position()
distance = sqrt( x**2 + y**2 )
end = time.time()
leo.color("red") # mark the end location
leo.dot(6)
leo.hideturtle()
# drawing the final distance: start to end
raph = turtle.Turtle()
raph.color("blue")
raph.goto(x,y)
raph.hideturtle()
print("Total time:", end - start)
print("Total steps:", steps)
print("Total distance:", distance / step_size)
The approach is to:
1- Generate a random walk and paint it on the canvas
2- use that random walk to generate a lattice (a graph of coordinates and their connections to their neighbors.
2- use the start and end points to search the lattice for the shortest path. Here, using Breadth First Search, but you could use other searches.
3- paint the shortest path on the canvas, over the lattice
Here is an example of a walk, with the shortest path superimposed upon it:
The code used to generate it:
(extended from the code you posted)