Reputation: 145
Im looking to spawn 3 objects (Red,Green,Blue) in seperate columns but should not duplicate. So somehow Im looking for it to check the colours in the other columns and place the one thats left over.
So if Blue and Red are already spawned, the last column will be a Green etc.
Should I need to specify specific orders inside a table and then everytime I spawn I just choose a random order from within that table, or is there a better way?
Cheers
Upvotes: 0
Views: 120
Reputation: 226
You can create a list of colors and shuffle it. Something like that:
math.randomseed( os.time() )
local colors = {
{ 1,0,0 }, -- red
{ 0,1,0 }, -- green
{ 0,0,1 }, -- blue
}
local function shuffleTable( t )
local rand = math.random
assert( t, "shuffleTable() expected a table, got nil" )
local iterations = #t
local j
for i = iterations, 2, -1 do
j = rand(i)
t[i], t[j] = t[j], t[i]
end
end
shuffleTable( colors )
local px = display.contentCenterX
local py = display.contentCenterY - 200
for i = 1, #colors do
local rect = display.newRect( px, py + 100 * i, 200, 100 )
rect.fill = colors[i]
end
Upvotes: 0
Reputation: 28954
You will always have to make sure you use the colour only once. How and when you do that is completely irrelevant.
Of course creating objects randomly is not very efficient as you would risk to create some you cannot use.
So best would be to create 3 different objects and remove one of them randomly every time or to spawn an object using a random colour, removed from a colour list.
Upvotes: 1