Reputation: 89
I want some help on Python turtle graphics. I need to create a house which goes each time smaller in a for ... in range()
loop.
I am creating scenery with three houses composed of basic turtle shapes. Is there a way, when I create a house with basic shapes, I can use a for ... in range()
loop to change the house position and make it a little smaller in size?
What I am trying so far:
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)
Using this code, I try to draw a second house with smaller size. The goto()
command disturbs the whole shape and I have to do it everything manually but the task is to use for ... in range(4)
to draw four houses, each to be smaller and placed at a little distance.
Upvotes: 1
Views: 7975
Reputation: 41905
You need to draw in a relative, not absolute, fashion. You can do this with .goto()
and it tends to look something like:
turtle.goto(turtle.xcor() + hs * xwindow, turtle.ycor() + hs * ywindow)
That is, move relative to where you are now. However, it may be simpler to avoid .goto()
altogether and work with relative motion methods like .forward()
, .backward()
, .left()
, & .right()
. Here's a rework of your code using those relative motion methods:
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()
Notice that it can not only draw the house at different sizes, but rotate it as well, due to the relative drawing logic:
Upvotes: 2