1

I have been working on a code that randomly generates a line from one random point to another. However, I would like to have the line created not intersect itself. Is there a way to have the line replaced if it intersects itself, or to possibly refresh the random coordinates? If someone could help that would be great! Here is the code I have created (and yes as far as i know, all of it is necessary in order for it to run at all);

#imports
from tkinter import * 
import random
from random import randint
import math

import pip 
import shapely
from shapely.geometry import LineString

#setting up the canvas
master = Tk()
master.geometry("500x500")
master.title("Sprouts")

w = Canvas(master, width=500, height=500, bg="white")
w.pack()

#creating the circle
def create_circle(x, y, r, w): #center coordinates, radius
    x0 = x - r
    y0 = y - r
    x1 = x + r
    y1 = y + r
    return w.create_oval(x0, y0, x1, y1)

#creating coordinate variables
xC = random.randint(10,490)
yC = random.randint(10,490)
xC2 = random.randint(10,490)
yC2 = random.randint(10,490)

L1C1 = random.randint(10,490)
L1C2 = random.randint(10,490)
L1C3 = random.randint(10,490)
L1C4 = random.randint(10,490)

#displaying the circle
c1 = create_circle(xC, yC, 5, w)
c2 = create_circle(xC2, yC2, 5, w)

#displaying the line #implementing the curve
Line1 = LineString([(xC, yC), (xC2, yC2)]
                 or [(xC, yC), (L1C1, L1C2), (xC2, yC2)]
                or [(xC,yC), (L1C1, L1C2), (L1C3, L1C4), (xC2, yC2)])

Line1show = w.create_line(xC, yC, xC2, yC2 or
                            xC, yC, L1C1, L1C2, xC2, yC2 or
                            xC, yC, L1C1, L1C2, L1C3, L1C4, xC2, yC2,
                            smooth='1',width="2")

#defining the intersects variable
intersection1 = Line1.intersection(Line1)

if Line1 == intersection1:
    print('try again') #this is a filler so the code functions 
    #either replace Line1, or use another method to prevent intersection

w.mainloop() 
  • In terms of preventing intersection, [self-avoiding walks](https://en.wikipedia.org/wiki/Self-avoiding_walk) are a rich subject that we don't know a ton about. – Kyle Parsons Aug 02 '21 at 21:01
  • what do you mean by intersect itself? – Vulwsztyn Aug 02 '21 at 21:03
  • By intersect itself, I mean how portions of the line1 cross over itself before reaching the final destination – Eithan Ackerman Aug 02 '21 at 21:20
  • Does this answer your question? [How can I check if two segments intersect?](https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect) – Woodford Aug 02 '21 at 21:22
  • unfortunately https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect was not of assistance, because I am trying to figure out how to prevent the intersection rather than simply detect it. – Eithan Ackerman Aug 03 '21 at 21:21

0 Answers0