Reputation: 1
I am having trouble recursively drawing squares. My question is what length should be passed to my draw_squares function when I recursively call it. I cant seem to get it to fit correctly within the original square. Find example of output attached. Output example
draw_squares(side_size, depth):
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
turtle.forward(side_size)
turtle.left(90)
if depth > 1:
turtle.penup()
turtle.left(90)
turtle.forward(side_size * 1 / 2)
turtle.right(90)
turtle.pendown()
else:
pass
#Draw diagonal squares within original square
def draw_squares2(side_size, depth):
if depth > 1 and depth % 2 == 0:
turtle.right(45)
draw_squares(side_size * 1/3, depth - 1)
Upvotes: 0
Views: 2811
Reputation: 41872
The problem as posed isn't recursive, but it could be. I wrote an example approach below using stamping which, while not directly translatable to your drawing approach, should give you ideas but not a solution:
from turtle import Turtle, Screen
colors = ["navy", "gold"]
STAMP_UNIT = 20
def draw_figure(turtle, side_size, depth):
turtle.turtlesize(side_size / STAMP_UNIT)
turtle.color(colors[depth % 2], "white")
turtle.stamp()
if depth < 1:
return
turtle.forward(side_size / 4)
turtle.left(45)
draw_figure(turtle, side_size / 2 / 2**0.5, depth - 1)
turtle.right(45)
turtle.backward(side_size / 2)
turtle.left(45)
draw_figure(turtle, side_size / 2 / 2**0.5, depth - 1)
turtle.right(45)
turtle.forward(side_size / 4) # return to starting point
yertle = Turtle(shape="square", visible=False)
yertle.penup()
draw_figure(yertle, 240, 3)
screen = Screen()
screen.exitonclick()
At depth 3 we get:
But setting the depth to 1 gets us the original figure in question:
Upvotes: 1
Reputation: 77847
First, you're not drawing squares recursively here: draw_squares2 calls only draw_squares, which never calls itself or its parent. A recursive function calls itself, either directly or indirectly. It looks like you're working toward a recursive solution (moving the turtle to the middle of one side), but you're not there yet.
Among other things, I note that the picture you linked to your posting doesn't seem to match the code above. Still ...
The problem you have is, as others have pointed out, basic geometry: what is the side length of a square inscribed in another square at a 45-degree angle? The length you need is sqrt(2) / 2 times the length of the parents square's side.
Keep track of how you use this value; your program is susceptible to multiplying and dividing things by 2. Consider using print statements at critical points to trace your computations.
Upvotes: 2