首页 > 解决方案 > 你如何防止一条线相交

问题描述

我一直在研究一种从一个随机点到另一个随机点随机生成一条线的代码。但是,我希望创建的线不与自身相交。如果线与自身相交,或者可能刷新随机坐标,有没有办法替换它?如果有人可以提供帮助,那就太好了!这是我创建的代码(是的,据我所知,为了让它运行,所有这些都是必需的);

#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() 

标签: pythontkinterlineintersectionshapely

解决方案


推荐阅读