Random Choice

Actionscript:
  1. function randomChoice(...args:Array):*{
  2.     return args[int(Math.random()*args.length)];
  3. }
  4.  
  5. // choose randomly from a number of different values
  6. var val:* = randomChoice(10, "Hello", "0xFF0000", 1000);
  7.  
  8. // choose a random color (in this case red, green or blue)
  9. var randColor:uint = randomChoice(0xFF0000, 0x00FF00, 0x0000FF);
  10.  
  11. trace(val);
  12. trace(randColor);

The function randomChoice() takes any number of arguments and spits one of them back randomly. Just a handy function to have around... I especially like to use this function to choose from a handful of colors.

This entry was posted in functions, random. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted November 2, 2008 at 10:34 am | Permalink

    Nice one, will come in pretty handy. I always used Math.random() * 0xFFFFFF for random colors but this is nicer because you can set the colors you want to choose from. Obviously you could also create an array and use a random number generated then point to that ID, but who wants to do all that? :P This is much sleeker.

  2. Posted November 2, 2008 at 1:00 pm | Permalink

    Thanks Matt. Yeah, this:

    var col:uint = Math.random()*0xFFFFFF;

    is a great snippet. You can also try using the bitwise operators to pull out the rgb values. Like this:

    var red:uint = (Math.random() * 0xFF ) << 16;
    var green:uint = (Math.random() * 0xFF ) << 8;
    var blue:uint = (Math.random() * 0xFF );

    That gives you a little more control.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*