user1597438
user1597438

Reputation: 2231

Setting x-position of objects in Corona using for loop

In my game class, I call two objects from another class (objA and objB) like so:

for i=1, countA do
pos.x = pos.x + 15
objA = objClass:new("objClass", group, pos)
wArray[i]=i
end

for j=1, countB do
pos.x = pos.x + xPoint
objB = objClass:new("objCLass", group, pos)
end

I need the for loop because I want to add random number of these objects on my game class. My problem with this is, I want to position a and b simultaneously on my game. For example: objA - objA - objB - objB - objA or objB - objA - objB - objB. However, given my current code, the pattern I end up getting would be all objA first before adding all objB objects.

I know the simple answer would be to just use a single for loop but the problem I see with that is that I need to have at least 1 objA and 1 objB in my game. I can't have all objB or all objA. What would be the best approach to get them to position randomly together? Thanks in advance.

Upvotes: 0

Views: 175

Answers (2)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23767

-- Prepare your counters (just an example)
local countA = math.random(3)  -- 1,2,3
local countB = math.random(5)  -- 1,2,3,4,5

-- Generate permutation
repeat
   if math.random(1-countB, countA) > 0 then 
      countA = countA - 1
      -- Do something with objA
   else
      countB = countB - 1
      -- Do something with objB
   end
until countA + countB == 0

Upvotes: 1

Alex
Alex

Reputation: 96

If you want to randomly choose between As and Bs you could try something like

local ab = {}

for i = 1,countA+countB do
    ab[i] = i<=countA and "A" or "B"
end

for i = 1,countA+countB do
    local idx = math.random(#ab)
    local choice = table.remove(ab,idx)

    if choice=="A" then
        pos.x = pos.x + 15
        objA = objClass:new("objClass", group, pos)
    else
        pos.x = pos.x + xPoint
        objB = objClass:new("objClass", group, pos)
    end
end

Upvotes: 2

Related Questions