0

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

Dips
  • 147
  • 1
  • 2
  • 14
  • 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 May 16 '16 at 14:51
  • 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 May 16 '16 at 14:58
  • @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 May 16 '16 at 14:58
  • Here's language-neutral descriptions of different approaches to this: http://stackoverflow.com/q/196017/936986. – Oleg V. Volkov May 16 '16 at 15:01

2 Answers2

1

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.

Piglet
  • 27,501
  • 3
  • 20
  • 43
  • The objects will destroy afterwards eventually. I should of added that as they reach a certain spot, they are destroyed and a new R/G/B blocks are spawned. Im not sure as to why I said 3 random objects too. What I meant is that I have 3 objects that are 3 solid colours already made, I just didn't want the same colours in the row of 3 – Dips May 16 '16 at 14:09
0

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
Maicon Feldhaus
  • 226
  • 2
  • 8