Python: Drawing a heart

 In Python, there is a library called turtle. It is used for drawing pictures in a very nice way. In this exercise, this library will be used to draw a perfect heart with "I love you" inside.

Let's see a brief explanation about the turtle library.


from turtle import *

getscreen()





As you can see from the figure above, in Python turtle is the cursor shown in the middle of the screen. Its position is x = 0 and y = 0. Notice that the turtle is pointing to the right, meaning if we want it to move forward in the same direction, we need to write the function forward(). It is also possible to change the screen background color.


#Choosing the background-color

bgcolor('light blue')

#Moving the turtle forward

forward(100)


As seen, the turtle has been moved 100 pixels in the same direction it was pointing initially (to the right). Now, if we want the turtle to point out in a different direction and move in that direction, we should write:


#Turning the turtle to the left at 50°

left(50)

#Moving the turtle backward

forward(-150)




If we consider the horizontal line as 0°, the cursor changed direction, it has been moved 50° to the left and then moved backward 150 pixels. Now, we are ready to draw the heart.


#Drawing

#Choosing the color of the figure

color('red')

#Filling the figure with the color defined above

begin_fill()

#Drawing lines of width 3

pensize(3)

#Turning the turtle to the left at 50°

left(50)

#Moving the turtle a distance of 133 pixel

forward(133)

#Making the turtle describe a circle of length 50 and radius 200

circle(50,200)

#Turning the turtle to the right at 140°

right(140)

#Making the turtle describe a circle of length 50 and radius 200

circle(50,200)

#Moving the turtle a distance of 133 pixel

forward(133)

#Ending fill

end_fill()



But, how to write "I love you" inside the heart? Imagine you have finished drawing your heart on a piece of paper, If you do not pick up the pencil, you will draw a line from where you are to where you want to start writing. 

In Python, we should do the same. We should pick up the turtle, move it to where we want to continue drawing or start writing, and then pick down the turtle. For this purpose the functions penup(), goto(), and pendown() are needed.


#Writing

penup()

goto(0,100)

pendown()

style = ('Courier', 15, 'bold')

color('white')

write('I love you!', font=style, align='center')




Note, that the cursor can be seen and makes the final draw in some way not very beautiful. In order to hide it, the function hideturtle() is needed. Then, the final code will look like this:





Congratulations! You can now surprise your lover with a few lines of code!

Comments

Post a Comment

Popular posts from this blog

Python: Tracking any phone number

Python: Pandas DataFrame data manipulation