0

I have a simple turtle program that draws lines in a vaguely random pattern; I'm using this for my own artistic purposes (I like the pattern).

However, I would like to prevent line overlap, i.e. I want to prevent the turtle from drawing over a line that already exists, in order to prevent it from making boxes. However, I don't see any method to extract what lines the turtle has drawn in the docs, and questions such as these:

Turtle line intersection, coordinates

Turtle graphics drawing over itself

Aren't really helpful.

It is distinct from this one:

Python: how to make a turtle never cross over a line

Because I am not using a grid, and using a grid wouldn't produce the lines in the way I would want, or the grid would have to be INCREDIBLY fine grained.

import turtle
import random

turtle_actor = turtle.Turtle()

rect = turtle.Screen()
dims = rect.screensize()
x_max = dims[0]
y_max = dims[1]
x_min = x_max*-1
y_min = y_max*-1
turtle_actor.speed(0)

def position_check():
     global turtle_actor
     global y_max
     global x_max
     global y_min
     global x_min
     if turtle_actor.xcor() < x_min or turtle_actor.xcor() > x_max or turtle_actor.ycor() < y_min or turtle_actor.ycor() > y_max:
          turtle_actor.penup()
          turtle_actor.goto((random.randrange(x_min,x_max),random.randrange(y_min,y_max)))
          turtle_actor.pendown()

def recurse(length,n):
     global turtle_actor
     global y_max
     global x_max
     global y_min
     global x_min
     if n < 1:
          return
     l_use = length/random.choice([2,2,2,3,4,5,7,1])
     turtle_actor.forward(l_use)
     position_check()
     turtle_actor.left(random.choice([0,90,-90,180]))
     position_check()
     turtle_actor.left(random.choice([0,90,-90,180]))
     position_check()
     turtle_actor.backward(l_use)
     position_check()
     recurse(length,n-1)
     return  


recurse(50,1000)
CapnShanty
  • 529
  • 8
  • 20

1 Answers1

2

Turtle graphics has no memory. You'll have to keep track of all the lines you draw in your own python data structure, and then when drawing each new line see if it intersects one of the previous lines. Unfortunately that's O(n^2); but there are ways to make it faster by rejecting many distant lines quickly, for instance see quadtrees.

GaryO
  • 5,873
  • 1
  • 36
  • 61
  • 1
    If you just want to get it working, don't worry about quadtrees -- just intersect each new (potential) line against all the old ones. If you're only doing 1000 lines, it'll be plenty fast enough. – GaryO Aug 07 '19 at 16:55
  • I may do that, but I'll also still try to implement a quadtree as well, for the sake of learning and all that lol – CapnShanty Aug 07 '19 at 16:58
  • 1
    Another interesting question will be what do you do when your new line does intersect? You could get into a situation where no new line you choose is "good". Seems like a fun project! – GaryO Aug 07 '19 at 16:58