【问题标题】:Python turtle prevent line intersection?Python乌龟防止线交叉?
【发布时间】:2019-08-07 16:14:52
【问题描述】:

我有一个简单的海龟程序,它以模糊的随机模式绘制线条;我将其用于我自己的艺术目的(我喜欢这种模式)。

但是,我想防止线重叠,即我想防止海龟在已经存在的线上绘制,以防止它制作盒子。但是,我没有看到任何方法可以提取海龟在文档中绘制的线条,以及诸如此类的问题:

Turtle line intersection, coordinates

Turtle graphics drawing over itself

没什么用。

和这个不同:

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

因为我没有使用网格,并且使用网格不会以我想要的方式生成线条,或者网格必须非常精细。

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)

【问题讨论】:

  • 我无法让您的代码运行 NameError: name 'tree' is not defined
  • 哦,是的,对不起,我更改了代码,我错误地留下了一个已删除的函数名称
  • 您的问题不清楚您是要防止线 intersection 还是 overlap 或两者兼而有之。
  • 交叉点需要重叠,是吗?重叠同样需要相交。在我看来,阻止一个就是阻止另一个。

标签: python intersection turtle-graphics


【解决方案1】:

海龟图形没有内存。您必须跟踪您在自己的 python 数据结构中绘制的所有线,然后在绘制每条新线时查看它是否与之前的一条线相交。不幸的是,这是 O(n^2);但是有一些方法可以通过快速拒绝许多遥远的线路来使其更快,例如参见quadtrees

【讨论】:

  • 如果你只是想让它工作,不要担心四叉树——只需将每条新(潜在)线与所有旧线相交。如果你只做 1000 行,那已经足够快了。
  • 我可能会这样做,但我仍然会尝试实现四叉树,为了学习和所有这些,哈哈
  • 另一个有趣的问题是当你的新线相交时你会怎么做?您可能会遇到您选择的新行没有“好”的情况。似乎是一个有趣的项目!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
相关资源
最近更新 更多