#!/usr/bin/perl # mcc@grumpybumpers.com package evo; use GD::Image; # The following variables determine the program's behavior. our $size = 32; # How big is an image? our $herd = 4; # How many images do we create per generation? our $litter = 2; # How many new images are generated in each spawn event? our $select = 2; # How many spawns are generated in each selection selection event? our $mutate = 16; # How often do mutations happen? our $shades = 255; # Set this to 255 for a black-and-white image. Set it to 1 for a grayscale image. sub colors { my ($image) = @_; my @colors; if ($shades == 255) { push(@colors, $image->colorAllocate(0,0,0)); push(@colors, $image->colorAllocate(255,255,255)); } else { for my $c (0..255) { push(@colors, $image->colorAllocate($c,$c,$c)); } } return @colors; } # Generates a $size x $size random image. sub abiogenesis { my ($name) = @_; # setup the image my $image = GD::Image->new($size,$size); my @colors = colors($image); for my $x (0..$size) { for my $y (0..$size) { my $color; $color = $colors[rand @colors]; $image->rectangle($x, $y, $x, $y, $color); } } open(FH, ">$name"); print FH $image->gif(); close(FH); } # Takes in two filenames of input GIFs and a list of filenames for output GIFs. # For each output GIF name, genetically recombines the two input GIFs and saves the results. sub spawn { my ($in1, $in2, @outnames) = @_; my $male = GD::Image->newFromGif($in1); my $female = GD::Image->newFromGif($in2); for my $name (@outnames) { # setup the image my $image = GD::Image->new($size,$size); my @colors = colors($image); # and the log my $log = GD::Image->new($size,$size); my $red = $log->colorAllocate(255,0,0); my $white = $log->colorAllocate(255,255,255); my $black = $log->colorAllocate(0,0,0); for my $x (0..$size) { for my $y (0..$size) { my ($color, $logcolor); if (0 == int(rand($mutate))) { $color = $colors[rand @colors]; $logcolor = $red; } else { (my $pixel, $logcolor) = (rand() > 0.5 ? ($male, $white) : ($female, $black)); my ($g) = $pixel->rgb($pixel->getPixel($x,$y)); $color = $colors[$g/$shades]; } $image->setPixel($x, $y, $color); $log->setPixel($x, $y, $logcolor); } } open(FH, ">$name"); print FH $image->gif(); close(FH); open(FH, ">$name.log.gif"); print FH $log->gif(); close(FH); } }