Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Random Color

edited July 2012 in General Posts: 266

I've been using math.random to create a random background for my game every time it runs. However, sometime the random colors turn out really ugly. How would I create a pool of colors (that i create) to choose from when starting the game and math.random would choose from that pool. Any help guys?


  • edited July 2012 Posts: 8

    Create a table of colors in your setup() function like so:

    colors = {color(255, 0, 0, 255), color(0, 255, 0, 255), etc.}

    I won't give the rest away, but you should be able to find a way to access a random item from this table using math.random()...

  • edited July 2012 Posts: 176

    Tables are your friend, friend.

    @Otterified - you beat me to it, with a better explanation, too!

  • Posts: 266

    how would I use math.random to choose from the pool. I tried figuring it out by putting math.random(2) because there are two colors. However, it doesnt work and leaves me with a black background. In my draw function I put background(randomColour) and in my function set up
    I put randomColour = math.random(2). What am I doing wrong? Please reply, @jlslate or @Otterified

  • dave1707dave1707 Mod
    edited July 2012 Posts: 8,721

    After you create your table of colors, use math.random(size of table) to get your color. Do the same for the next color. You can use an if statement so you don't get the same color twice in a row.

  • Posts: 179
    function setup()
        colors = {color(0, 21, 255, 255),color(255, 0, 201, 255),color(110, 255, 0, 255)}
        bgcolor = colors[math.random(#colors)]
    function draw()
Sign In or Register to comment.