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;
zzspectrez

In reply to Recursive H by zzspectrez

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.