Merge if 3 in a row

I’m trying to get if a player has 3 of the same dragon in a row, they merge together. So if slot 1, 2, 3 all have dragon 1, when then Slot 1 becomes Dragon 2, slot 2 and 3 become empty.

What I have works with that, but it’s other areas where it stops working. I can do 1,2,3 then merge, then 2,3,4, merge. but when slots 1,2 have value of 2, and slots 3,4,5 have value 1, it doesn’t get that those 3 are in a row.

Image here shoes that 3,4,5 are all the same value, but it never prints “MERGE” for them.
image
Should be

[1] = 2,
[2] = 2,
[3] = 2

in the above screenshot

local CurrentDragonIndex = 1
local InARow = 0
for slotIndex, dragonIndex in Data.Dragons do
	InARow += 1
				
	print("SLOT", slotIndex, "DRAGON", dragonIndex, "ROW", InARow, "CURRENT DRAGON", CurrentDragonIndex)
				
	if dragonIndex ~= CurrentDragonIndex then -- Reset
		print("RESET!!, Setting Current dragon", CurrentDragonIndex, "to", Data.Dragons.__Origin[slotIndex + 1])
		InARow = 0
		CurrentDragonIndex = Data.Dragons.__Origin[slotIndex + 1] -- Set to next dragon
	end
				
	if InARow == 3 then -- Can merge
		print("CAN MERGE DRAGON", CurrentDragonIndex, slotIndex)
					
		-- Remove dragons 2 and 3
		Data.Dragons[slotIndex] = nil
		Data.Dragons[slotIndex - 1] = nil

		-- Set dragon 1 to increase by 1
		Data.Dragons[slotIndex - 2] = CurrentDragonIndex + 1
			
		break
	end
end

After you merge three together, you’ll want to re-evaluate a few things back in history. This is not a simple for loop – the index can move backwards as well as forwards.

Perhaps try a while loop.

local slotIndex = 1
while slotIndex <= #Data.Dragons do
	--...
	slotIndex += 1
	--...
	if InARow == 3 then -- Can merge
		--...

		--Evaluate stuff before this new, merged value.
		slotIndex = math.max(1, slotIndex - 4);
		CurrentDragonIndex = nil;
	end
end

We go back 4 because your “current” index is now 2 back, and we need to re-check the two things before the newly-created number.


Some other things I noticed:

  1. When you detect a new dragon, don’t reset your “InARow” counter to 0 – reset it to 1. You also don’t need to set your CurrentDragonIndex to the next dragon, just set it to this one.
  2. When you clear a dragon from your list, you probably want to squash down the array so it has no gaps. Use table.remove instead of assigning the value to nil.
1 Like

Seemed to work thanks!

With regards to this

I tried

-- Remove dragons 2 and 3
table.remove(Data.Dragons, slotIndex)
table.remove(Data.Dragons, slotIndex - 1)

but it doesn’t remove them?
image

idk if it’s of how the metamethods are setup with the data, and thus I can’t simple just do table.remove, but idk

You’re not removing the dragons from Data.Dragons.__Origin, you’re removing them from Data.Dragons – that’s why they don’t seem to disappear.

I’m not entirely sure of the purpose of this __Origin table.