Random

Hello. I’m trying to generate a random color, but always white on the screen. Why?

local width  = display.contentWidth / 10

local r = width

local red, green, blue

while ( width <= display.contentWidth ) do

      math.randomseed( os.time() )

      

      red   = math.random( 0, 255 )

      green = math.random( 0, 255 )

      blue  = math.random( 0, 255 )

      

      display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ):setFillColor( red, green, blue )

      

      width = width + r

      

 end

  1. Please use the <> code formating tool for future posts.

formatyourcode.jpg

  1. It isn’t necessary (or even a good idea) to re-seed over and over.  Just do that once at the top of main.lua

  2. Colors are in the range [0.0, 1.0]

    red = math.random() green = math.random() blue = math.random()

  1. Not a good practice:

    display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ):setFillColor( red, green, blue )

This is better, more legible, and more easily maintained:

local tmp = display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ) tmp:setFillColor( red, green, blue )

Finally, I would do this:

math.randomseed( os.time() ) local mRand = math.random local width = 0 -- or whatever local r = 100 -- or whatever while ( width \<= display.contentWidth ) do local tmp = display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ) tmp:setFillColor( mRand(), mRand(), mRand() ) width = width + r end

Thank you so much for taking the time!  :slight_smile:

  1. Please use the <> code formating tool for future posts.

formatyourcode.jpg

  1. It isn’t necessary (or even a good idea) to re-seed over and over.  Just do that once at the top of main.lua

  2. Colors are in the range [0.0, 1.0]

    red = math.random() green = math.random() blue = math.random()

  1. Not a good practice:

    display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ):setFillColor( red, green, blue )

This is better, more legible, and more easily maintained:

local tmp = display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ) tmp:setFillColor( red, green, blue )

Finally, I would do this:

math.randomseed( os.time() ) local mRand = math.random local width = 0 -- or whatever local r = 100 -- or whatever while ( width \<= display.contentWidth ) do local tmp = display.newRect ( width - r, 0, display.contentWidth / 10, display.contentHeight / 10 ) tmp:setFillColor( mRand(), mRand(), mRand() ) width = width + r end

Thank you so much for taking the time!  :slight_smile: