如何防止直线与自身相交

2024-06-16 09:28:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在编写一个代码,该代码随机生成一条从一个随机点到另一个随机点的线。但是,我希望创建的直线不与其自身相交。如果直线与自身相交,是否有方法替换该直线,或者可能刷新随机坐标?如果有人能帮忙,那就太好了!这是我创建的代码(是的,据我所知,所有这些都是运行所必需的)

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

Tags: ortheimportmastercreaterandomrandintxc