Why are the hearts in turtle appearing slanted?

Question:

import turtle

t = turtle.Turtle()

def heart(x):
    t.penup()
    t.goto(x, -100)
    t.pendown()

    t.color('black','red')
    t.begin_fill()
    t.left(45)
    t.forward(100)
    t.circle(50, 180)
    t.right(90)
    t.circle(50, 180)
    t.forward(100)
    t.end_fill()


for i in range(3):
    if i==1:
        x=-250
        heart(x)
    elif i==2:
        #continue
        x=0
        heart(x)
    else:
        #continue
        x=250
        heart(x)


t.hideturtle()
turtle.done()

This program is supposed to draw three hearts in a straight line
I’ve made a loop that sets the initial position of the heart. It’s supposed to draw the heart in one position and move to the next position. While the pointer is moving over the next position, the hearts are appearing slanted.

Asked By: ryan mathew

||

Answers:

Your heart function assumes the turtle’s heading is 0, but in the course of drawing a heart, heading changes due to left/right calls.

One solution is to reset heading with t.setheading(0) at the start of the function.

Also, your loop/if combo is overcomplicated. I suggest either removing the ifs or removing both the loop and the ifs and using 3 separate heart calls. Here’s a simplified version:

import turtle

def heart(x):
    t.penup()
    t.goto(x, -100)
    t.pendown()
    t.color("black", "red")
    t.setheading(0)
    t.begin_fill()
    t.left(45)
    t.forward(100)
    t.circle(50, 180)
    t.right(90)
    t.circle(50, 180)
    t.forward(100)
    t.end_fill()


t = turtle.Turtle()
t.hideturtle()

for x in range(-250, 251, 250):
    heart(x)

turtle.exitonclick()

Consider making size and y values parameters for heart, and optionally t. As is, it’s a bit on the hardcoded side.

Answered By: ggorlen