Simple example of using GD and recursion. Tested on Windows with Activestate Perl.
My attempt at solving this simple task: http://www.cs.princeton.edu/courses/archive/spring04/cos126/assignments/htree.html
If you are curious, I dont go to princeton. (In fact I dont go to school!) I'm just looking for stupid little things to implement in perl for fun and profit. (IE still learning)
use GD;
use strict;
use warnings;
sub WIDTH { 600 };
sub HEIGHT { 600 };
sub DEPTH { 3 };
my $outfile = 'test.png';
my $img;
my @colors;
sub drawh {
my ($x1,$y1,$x2,$y2,$color) = @_;
my $imgsize = ($x2-$x1);
my $brdinc = ($imgsize/4);
$img->line( $x1+$brdinc,$y1+$brdinc,$x1+$brdinc,$y2-$brdinc,$colors[
+$color]);
$img->line( $x1+$brdinc,$y1+($brdinc*2),$x2-$brdinc,$y1+($brdinc*2),
+$colors[$color]);
$img->line( $x2-$brdinc,$y1+$brdinc,$x2-$brdinc,$y2-$brdinc,$colors[
+$color]);
}
sub recurseit {
my ($depth,$x1,$y1,$x2,$y2,$color) = @_;
if ($depth) {
drawh($x1,$y1,$x2,$y2,$color);
--$depth;
return unless $depth;
my $size = (($x2-$x1)/2);
my $color = rand @colors;
recurseit($depth,$x1,$y1,$x1+$size,$y1+$size,$color);
recurseit($depth,$x1,$y2-$size,$x1+$size,$y2,$color);
recurseit($depth,$x1+$size,$y1,$x2,$y1+$size,$color);
recurseit($depth,$x1+$size,$y2-$size,$x2,$y2,$color);
}
}
$img = GD::Image->new(WIDTH,HEIGHT) || die "Could not create new
+image object: $!\n";
my $white = $img->colorAllocate(255,255,255);
$colors[0] = $img->colorAllocate(0,0,0);
$colors[1] = $img->colorAllocate(255,0,0);
$colors[2] = $img->colorAllocate(0,0,255);
recurseit(DEPTH,0,0,(WIDTH)-1,(HEIGHT)-1, rand @colors);
open (PNG, ">$outfile") || die "Couldn't open file: $!\n";
binmode PNG;
print PNG $img->png;
close PNG;