Thursday, November 13, 2014

Program to draw Tangram figures in SVG

The Tangram is an ancient Chinese game consisting in 7 geometrical flat pieces which must be put together to form a given figure, usually printed in paper. The solution for a given problem can be in another page, for example, this is how you form a square with the Tangram pieces:


I wrote a program in Perl called draw-tangram to create images of Tangram figures. To create a figure you need to write a description of the position of the pieces in a text file, in a simple format created for the program. Then you can choose to create images for the problem or the solution. For example:


To make this figure I first wrote the following instructions in a text file:

<3/4> a-b-c-d-a <0,6,4,2> [1,1,1,1];
<3/4> b-e-f-c-b <7,6,3,2> [0:1,1,0:1,1];
<3/4> f-g-h-f <3,6,1> [1,0:1,1];
<1/2> h-i-j-h <4,7,2> [2,0:2,2];
<1/2> i-k <7> [1];
<1/2> k-l-m-k <7,5,2> [1,1,0:1];
<1/2> k-o-n-k <3,5,0> [2,2,0:2];
<1/2> n-q <1> [0:1];
<1/2> q-s-r-q <1,4,7> [0:1,2,0:1];

Numbers between < and > are angles and numbers between [ and ] are lengths. The program helps you to create this because without parameters it prints the names of the points of the figure. To run the program you need Perl installed, and then you can write, for example:

perl draw-tangram.pl figure.txt

Then you can open the generated SVG file in a web browser to see the result. After that, you can use a program for editing vector graphics like Inkscape if you want a PNG or JPEG image. Enjoy it!