#!/usr/bin/perl -w use strict; # Script to print a random color #rrggbb that probably looks good on a black background # by Grant Birchmeier # # version 1.0. - sometime in mid-2007 # # I'm using this script with the following alias for xterm: # alias xterm='/usr/openwin/bin/xterm -vb -sb -sl 1000 -bg black -fg `random_color_for_black_bg.pl` -bd `random_color_for_black_bg.pl`' # # # FUNCTION validateColor - given a color, judges whether it is acceptable # Args: takes 3 ints (0-255) as args, represents rgb values # Returns: T/F (1/0) if color is valid sub validateColor { my ($my_r, $my_g, $my_b) = @_; # This is a hacked-together algorithm that assigns weights to each # color and compares the sum to a threshold. # If the sum is less than the threshold, it's rejected. # SPECIAL RULE: if green is too low, red has to be pretty high (blue doesn't help at all) if( ($my_g < 0x55) && ($my_r <= 0xEE) ){ return 0; } # SPECIAL RULE: high green or high red always is acceptable if( ($my_g >= 0xEE) || ($my_r >= 0xEE) ){ return 1; } my $threshold = 300; my $r_weight = 1; my $g_weight = 1; my $b_weight = -.2; #blue doesn't really help the brightness at all! my $sum = ($r_weight * $my_r) + ($g_weight * $my_g) + ($b_weight * $my_b); if($sum >= $threshold){ return 1; } return 0; } # FUNCTION getRandomFgColor - return a random color that satisfies validateColor() # ARGS: none # RETURNS: a string #rrggbb sub getRandomFgColor { # If $counter random colors haven't validated, give up and return "lightgrey". my $counter = 20; my ($r,$g,$b) = (0,0,0); do { $r = int rand 256; # returns a random integer where 0 <= x < 256 $g = int rand 256; $b = int rand 256; $counter--; }while( !validateColor($r,$g,$b) && ($counter >= 0) ); if ($counter == 0){ return "lightgrey"; } #print hex string #rrggbb from integers return sprintf("#%02x%02x%02x", $r,$g,$b); } ################################################################################# # MAIN ################################################################################# print getRandomFgColor();