Bad Astronomy has a explanation of the phases of the moon which I recommend.
Algorithm
Lunar Phase: Since with Lunar phases, we are seeing the projection of the light
from the Sun on the Moon from an angle, the circular full moon is rotated, and the
shape caused by rotating a circle is an ellipse, which is what is used to draw the
"dark" side of the moon.
Eclipse: While the Moon is in reality much smaller than the sun, it is also much closer
and the two have roughly the same angular size in the Earth's sky. For the purpose
of this applet, they are treated as two overlapping circles.