【问题标题】:Python: 3 branched treePython:3个分支树
【发布时间】:2019-08-12 23:02:41
【问题描述】:

What i want it to look like

results

我想出了如何制作一棵树,但它有时会产生随机设计。相反,我想知道如何制作一棵三枝树,所有东西都统一。谢谢!

import turtle
import random

turtle.speed(0)
turtle.hideturtle()
turtle.tracer(0,0)

def draw_line(x,y,angle,length,color,size):
    turtle.up()
    turtle.goto(x,y)
    turtle.seth(angle)
    turtle.color(color)
    turtle.pensize(size)
    turtle.down()
    turtle.forward(length)


def draw_tree(x,y,angle,length,color,size,thiccness,n):
    if n == 0:
       return
    if n <= 3:
       color = 'lime green'
    draw_line(x,y,angle,length,color,size)
    cx = turtle.xcor()
    cy = turtle.ycor()
    draw_tree(cx,cy,angle-thiccness+random.uniform(-8,8),length/(1.3+random.uniform(-.2,.2)),color,size*(0.8+random.uniform(-.1,.1)),thiccness,n-1)
    draw_tree(cx,cy,angle+thiccness+random.uniform(-8,8),length/(1.3+random.uniform(-.2,.2)),color,size*(0.8+random.uniform(-.1,.1)),thiccness,n-1)

draw_tree(0,-350,90,150,'brown',10,30,10)
turtle.update()

【问题讨论】:

  • 您能否提供制服随机设计的示例图片,以便我们查看从您的角度来看,问题是什么?

标签: python drawing turtle-graphics


【解决方案1】:

我不得不说我喜欢你的程序当前生成的树,因为它们更像是真正的树,而且每一棵树都不一样。如果我们从您的代码中删除随机元素,并添加一个中间分支,那么我们将获得您想要的一棵统一树,并且只有您想要的一棵统一树:

from turtle import Screen, Turtle, Vec2D

THICKNESS = 30

def draw_line(position, angle, length, size, color):
    turtle.penup()
    turtle.goto(position)
    turtle.setheading(angle)
    turtle.color(color)
    turtle.pensize(size)
    turtle.pendown()
    turtle.forward(length)

def draw_tree(position, angle, length, size, color, n):
    if n == 0:
        return

    if n <= 3:
        color = 'green'

    draw_line(position, angle, length, size, color)

    position = turtle.position()
    length /= 1.4
    size *= 0.7

    draw_tree(position, angle - THICKNESS, length, size, color, n - 1)
    draw_tree(position, angle, length, size, color, n - 1)
    draw_tree(position, angle + THICKNESS, length, size, color, n - 1)

screen = Screen()
screen.tracer(False)

turtle = Turtle(visible=False)

draw_tree(Vec2D(0, -350), 90, 150, 10, 'brown', 9)

screen.update()
screen.tracer(True)
screen.exitonclick()

【讨论】:

  • 泰!还有 Vec2D 是什么意思?以及为什么我们必须从海龟进口
  • @mbach21,Vec2D 是海龟对位置的表示——你不需要使用它,如果需要,只需使用元组 (0, -350)。我们没有必须使用from turtle import ...,但它强制使用turtle 的面向对象API,而不是功能API。将两者混合往往会导致问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多