【问题标题】:Python Turtle graphics scale size and positionPython Turtle 图形缩放大小和位置
【发布时间】:2018-03-26 08:57:01
【问题描述】:

我想要一些有关 Python 海龟图形的帮助。我需要在for ... in range() 循环中创建一个每次都变小的房子。

我正在用三个由基本乌龟形状组成的房子来创造风景。有没有办法,当我创建一个有基本形状的房子时,我可以使用for ... in range() 循环来改变房子的位置,让它变得更小一点?

到目前为止我正在尝试什么:

def house(turtlename,hs,xroof,xdoor,xwindow,ywindow):
 housesquare(turtlename,hs)
 turtlename.pu()
 turtlename.goto ((int(hs*xroof),int(hs*1)))
 turtlename.pd()
 housetriangle(turtlename,hs)
 turtlename.pu()
 turtlename.goto((int(hs*xdoor),0 ))
 turtlename.pd()
 housedoor(turtlename,hs*0.7,hs*0.3)
 turtlename.pu()
 turtlename.goto((int(hs*xwindow), int(hs*ywindow)))
 turtlename.pd()
 housesquare(turtlename,hs*0.3)

使用此代码,我尝试绘制第二个尺寸较小的房子。 goto() 命令扰乱了整个形状,我必须手动完成所有操作,但任务是使用 for ... in range(4) 绘制四个房子,每个房子要小一些,并放置一点距离。

【问题讨论】:

  • 如果你们帮我创建一个房子,女巫每次循环都会变小。这将是一个很大的帮助

标签: python turtle-graphics


【解决方案1】:

您需要以相对而非绝对的方式进行绘画。您可以使用.goto() 来执行此操作,它往往看起来像:

turtle.goto(turtle.xcor() + hs * xwindow, turtle.ycor() + hs * ywindow)

也就是说,相对于你现在所在的位置移动。但是,完全避免.goto() 并使用.forward().backward().left().right() 等相对运动方法可能更简单。下面是使用这些相对运动方法对您的代码进行的修改:

from turtle import Turtle, Screen

def housesquare(turtle, width):
    for _ in range(4):
        turtle.forward(width)
        turtle.left(90)

def housetriangle(turtle, base):
    for _ in range(3):
        turtle.forward(base)
        turtle.left(120)

def housedoor(turtle, height, width):
    for _ in range(2):
        turtle.forward(width)
        turtle.left(90)
        turtle.forward(height)
        turtle.left(90)

def house(turtle, hs, xroof, xdoor, xwindow, ywindow):
    housesquare(turtle, hs)

    turtle.penup()
    turtle.left(90)
    turtle.forward(hs)
    turtle.right(90)
    turtle.forward(hs * xroof)
    turtle.pendown()
    housetriangle(turtle, hs)

    turtle.penup()
    turtle.right(90)
    turtle.forward(hs)
    turtle.left(90)
    turtle.forward(hs * xdoor)
    turtle.pendown()
    housedoor(turtle, hs * 0.7, hs * 0.3)

    turtle.penup()
    turtle.backward(hs * xdoor)
    turtle.forward(hs * xwindow)
    turtle.left(90)
    turtle.forward(hs * ywindow)
    turtle.right(90)
    turtle.pendown()
    housesquare(turtle, hs * 0.3)

    turtle.penup()
    turtle.backward(hs * xwindow)
    turtle.left(90)
    turtle.backward(hs * ywindow)
    turtle.right(90)
    turtle.pendown()

screen = Screen()
yertle = Turtle()

size = 100

for factor in range(1, 4):

    house(yertle, size / factor, 0.0, 0.2, 0.6, 0.4)

    yertle.penup()
    yertle.forward(1.5 * size / factor)
    yertle.right(15)
    yertle.pendown()

yertle.hideturtle()

screen.exitonclick()

注意,它不仅可以绘制不同大小的房子,还可以旋转它,这是由于相对的绘制逻辑:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-20
    • 2017-11-09
    • 2014-01-26
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多