0
votes

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

2
You could append colors used into a table and then when spawning a new object, check if it exists in the table first. While the color picked exists, pick a new color, when it doesn't exists, spawn. - Brett Comardelle
That sounds like it could work, but how would I loop it again once the 3 colours display objects are destroyed? would I need to remove them from the table again ? - Dips
@Brett, uh-huh. And when you have only one left to spawn get stuck rerolling random and rechecking until it manages to hit that last number, right? - Oleg V. Volkov
Here's language-neutral descriptions of different approaches to this: stackoverflow.com/q/196017/936986. - Oleg V. Volkov

2 Answers

1
votes

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.

0
votes

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