Python Turtle: Two ends of a 180 arc do not coincide?

Viewed 153

I am trying an exercise which asks me to draw the letters of the alphabets using turtle in Python. So far I think I have a decent understanding of how to draw lines, curves, and shapes using forward/backward distance and turning angles.

I am trying to draw the letter 'B', and here is my design:

Figure 1:
Figure 1

Note that all the black lines are equal in distance, and the diameter of the arc is also equal to 1 black line. Here is the incomplete function I have:

def arc(t, r, angle, n):
    arc_length = 2*math.pi*r*(angle/360)
    def polyline(t, length, n):
        for i in range(n):
            t.fd(length/n)
            t.lt(angle/n)
    polyline(t, arc_length, n)

def draw_b(t):
    t.fd(30)
    arc(t, 30, 180, 10)
    t.fd(30)
    t.lt(90)
    t.fd(30)
    t.bk(60)

It should give me 2 exactly parallel lines connected by the bottom arc, but instead I get this:

Figure 2:
Figure 2

Ignoring the incomplete top part, how can I fix this problem where the 2 ends of the arc clearly do not coincide, hence leaving a short "tail"? Have I done something wrong?

1 Answers

You can use range(n+1) to draw extra fd() at the end but then you will have to turn back t.lt(-angle/n). Or keep range(n) and draw extra fd() without lt() after loop.

def polyline(t, length, n):
    for i in range(n):
        t.fd(length/n)
        t.lt(angle/n)
    t.fd(length/n)   # <--- extra `fd()` without `lt()`

import turtle
import math

def arc(t, r, angle, n):
    length = 2*math.pi*r*(angle/360)
    for i in range(n):
        t.fd(length/n)
        t.lt(angle/n)
    t.fd(length/n)

def draw_b(t):
    for _ in range(2):
        t.fd(30)
        arc(t, 30, 180, 10)
        t.fd(30)
        t.lt(90)
        t.fd(60)
        t.bk(60)
        t.lt(90)

draw_b(turtle.Turtle())

EDIT: in previons version I use fd() N+1 times, and lf() N times, but it looks better when there is lf() with angle/2, next fd() and lf() N times, and finally lf() with -angle/2. If you draw only arc with 3 segments then you will see it looks better.

import turtle
import math

def arc(t, r, angle, n):
    length = 2*math.pi*r*(angle/360)

    t.lt((angle/n)/2)

    for i in range(n):
        t.fd(length/n)
        t.lt(angle/(n))

    t.lt((-angle/n)/2)

def draw_b(t):
    for _ in range(2):
        t.fd(30)
        arc(t, 30, 180, 10)
        t.fd(30)
        t.lt(90)
        t.fd(60)
        t.bk(60)
        t.lt(90)

t = turtle.Turtle()
arc(t, 30, 180, 3)
#draw_b(t)

for n=3

first version draws 4 segments

enter image description here

second version draws 3 segments

enter image description here


BTW: gallery with other images created with turtle.

Codes for image are on other pages but pages are not translated into English, yet.

Related