如何在python海龟图形中找到顶点?

问题描述

我在 python 中使用乌龟模块生成分形树。要计算树的分形维数,我需要知道树顶点的 y 坐标。我使用 pyautogui.position() 通过将鼠标指向树的顶部来手动查找树的高度。这需要很长时间,因此我的问题来了:

是否有内置函数可以在海龟中找到图形的最大高度?如果没有,是否有其他方法可以找到它?我附上了下面制作的图片的例子。提前致谢。

Example of generated fractal tree

enter image description here

解决方法

设置一个变量来跟踪最大 Y 位置,在绘制函数期间更新它,然后在这些函数完成分形后将其归零。

#! /usr/bin/python3

from turtle import Turtle,Screen
turtle,screen  = Turtle(),Screen()

##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

screen.setup( width = 600,height = 600 )
screen.title('Maximum Recursion')
turtle.speed( 0 )

maxY = 0  ##  empty forward-declaration

def recursive_draw( step,length ):
    global maxY

    turtle.forward( length )
    turtle.right( 7 )

    if turtle.ycor() > maxY:  maxY = turtle.ycor()  ##  update when needed

    if step > 0:  recursive_draw( step -1,length *0.8 )

for i in range( 50,130 ):
    turtle.penup()
    turtle.setheading( i )
    turtle.setpos( 0,-300 )
    turtle.pendown()
    recursive_draw( 20,i )

turtle.hideturtle()
print( maxY )

screen.exitonclick()

##  eof  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~