Search code examples
actionscript-3randomflashdevelop

Random hexidecimal color generator in AS3


I wanted to create the ability to have "random" (pseudo-random) colors generated and came up with this code intended to create all and any color.

I'm very new to programming and wanted to see if anyone on S.O. had any comments or criticisms, the code works great. Only problem is the colors occasionally being too similar making it difficult to differentiate bewteen them.

I know this is likely a very brute force fashion of coding but its what I thought of.

Hexidecimal generator

public class colorGenerator 
{
    public var color:int;
    private var randomnumber:Number;
    private var first:String = "";
    
    public function colorGenerator():void
    {
        var colorstring:String = "0x";
        var transfer:String = "0x";
        
        for ( var i:uint = 0; i < 6; i++)
        {
            randomhex();
            
            colorstring += first;   
        }
        
        transfer = colorstring;
        color = int(transfer);
    }
    
    public function randomhex():void
    {
        randomnumber = Math.random();
    
    
        if ( -1 < randomnumber < ((.99 / 16) * 1))
            first = "0";
            
        else if ( ((.99/16)*1) < randomnumber < ((.99/16)*2))
            first = "1";
            
        else if ( ((.99/16)*2)< randomnumber < ((.99/16)*3))
            first = "2";
            
        else if ( ((.99/16)*3)< randomnumber < ((.99/16)*4))
            first = "3";
            
        else if ( ((.99/16)*4)< randomnumber < ((.99/16)*5))
            first = "4";
            
        else if ( ((.99/16)*5)< randomnumber < ((.99/16)*6))
            first = "5";
            
        else if ( ((.99/16)*6)< randomnumber < ((.99/16)*7))
            first = "6";
            
        else if ( ((.99/16)*7)< randomnumber < ((.99/16)*8))
            first = "7";
            
        else if ( ((.99/16)*8)< randomnumber < ((.99/16)*9))
            first = "8";
            
        else if ( ((.99/16)*9)< randomnumber < ((.99/16)*10))
            first = "9";
            
        else if ( ((.99/16)*10)< randomnumber < ((.99/16)*11))
            first = "A";
            
        else if ( ((.99/16)*11)< randomnumber < ((.99/16)*12))
            first = "B";
            
        else if ( ((.99/16)*12)< randomnumber < ((.99/16)*13))
            first = "C";
            
        else if ( ((.99/16)*13)< randomnumber < ((.99/16)*14))
            first = "D";
            
        else if ( ((.99/16)*14)< randomnumber < ((.99/16)*15))
            first = "E";
            
        else if ( ((.99/16)*15)< randomnumber < 2)
            first = "F";
        }
    }

I then just assign the hexidecimal value to a variable in another class

var acolor:colorGenerator = new colorGenerator;
var COLOR:uint = acolor.color

Thanks for any comments!


Solution

  • This should work as well.

    Math.random() * 0xFFFFFF;