
# Hearts.py
# Andrew Davison, ad@coe.psu.ac.th, July 2023
"""
 Use turtle graphics to generate a series of colored hearts
 which are saved in hearts.png.

 Also used as an example of how to call a Python script 
 from Java by using ProcessBuilder (see CallPython.java).

"""


from math import *
from turtle import Turtle
from PIL import Image 
import os

colors = ["red", "orange", "yellow", "green", "blue", "purple", "violet"]


def hearts(ttl):
    # draw 50 hearts in different colors
    ttl.speed(0)
    for i in range(1, 50):
        color(ttl, i)
        at(ttl, 0, i * -5)
        heart(ttl, i * 10, 45)


def color(ttl, i):
    # cycle through the colors list to set the pen
    ttl.pencolor(colors[i % len(colors)])


def at(ttl, x, y):
    # move the turtle to (x,y), pointing up screen
    ttl.penup()
    ttl.home()
    ttl.forward(x)
    ttl.left(90)
    ttl.forward(y)
    ttl.pendown()


def heart(ttl, size, angle):
    # a heart is made from 2 arcs and 2 straight lines
    ttl.width(10)
    radius = size * sin(radians(angle))/  \
                   (1 + sin(radians(90-angle)))
    ttl.right(angle)
    ttl.forward(size)   # line
    ttl.circle(radius, 180 + angle)  # arc
    ttl.right(180)
    ttl.circle(radius, 180 + angle)  # arc
    ttl.forward(size)   # line
    ttl.left(180 - angle)



# main
t = Turtle()
screen = t.getscreen()
screen.setup(800, 800)

hearts(t)

# save the generated image
fileName = 'hearts'
canvas = screen.getcanvas()
print("Generating", fileName+'.eps')
canvas.postscript(file= fileName+'.eps', width=800, height=800)

img = Image.open(fileName + '.eps') 
print("Generating", fileName+'.png')
img.save(fileName + '.png')
img.close()

print("Deleting", fileName+'.eps')
os.remove(fileName+'.eps')

