Reputation: 31
I have been trying to solve this for the past few days. It actually works but not in the way I want. The problem is that it starts spiraling from the top left (picture 1) rather than from the bottom right (picture 2), which is what I want. I'm a beginner, and I'm not aware of many of turtle's methods or functions, so please answer my question with your code for better understanding:
import turtle
tur=turtle.Turtle()
tur.penup()
tur.setpos(-250,250)
dot_distance=15
def spiral(r,c):
#r=row,#c=col
ri=0;ci=0
#ri=row_index,ci=col_index
while(ri<r and ci<c):
for i in range(c-1,ci-1,-1):
tur.dot()
tur.forward(dot_distance)
r-=1
tur.right(90)
for i in range(r-1,ri-1,-1):
tur.dot()
tur.forward(dot_distance)
ci+=1
tur.right(90)
for i in range(ci,c):
tur.dot()
tur.forward(dot_distance)
ri+=1
tur.right(90)
for i in range(ri,r):
tur.dot()
tur.forward(dot_distance)
c-=1
tur.right(90)
spiral(20,20)
Actual output is the 1st picture, but I want it like the 2nd picture, where it starts spiraling from bottom right rather than top left:
Upvotes: 1
Views: 468
Reputation: 27567
This code will make a turtle spiral around, leaving a dot trail behind, and the resulting image will be perfectly in the center of the screen:
from turtle import Turtle
tur = Turtle()
tur.setheading(180)
tur.penup()
dot_distance = 10
def spiral(r,c):
tur.setpos(c*dot_distance/2, -r*dot_distance/2)
r -= 1
while r+1 and c:
for _ in range(c):
tur.forward(dot_distance)
tur.dot()
c -= 1
tur.right(90)
for _ in range(r):
tur.forward(dot_distance)
tur.dot()
r -= 1
tur.right(90)
spiral(20,20)
Output:
You can see that after each line is drawn, I decrement the variable (r
or c
) by 1,
so this while loop: while r+1 and c:
tells python that while there are still any dots left for each variable,
continue drawing lines.
Upvotes: 0
Reputation: 41872
Simply fixing the starting direction isn't enough, we also need to fix the starting position. And while we're at it, polish up your code:
from turtle import Screen, Turtle
DOT_DISTANCE = 15
def spiral(row, col):
while col > 0 < row:
for _ in range(col):
turtle.forward(DOT_DISTANCE)
turtle.dot()
row -= 1
turtle.right(90)
for _ in range(row):
turtle.forward(DOT_DISTANCE)
turtle.dot()
col -= 1
turtle.right(90)
screen = Screen()
turtle = Turtle()
turtle.speed('fastest') # because I have no patience
turtle.penup()
turtle.setpos(150, -150)
turtle.setheading(180)
spiral(20, 20)
turtle.hideturtle()
screen.exitonclick()
Upvotes: 1
Reputation: 1299
You're just missing tur.setheading(180)
after tur.setpos()
From the docs:
Set the orientation of the turtle to to_angle: Some common angles in degrees
0: East
90: North
180: West
270: South
Upvotes: 1