Making Levels and Fixing Sectors

I’ve been making some playable levels so I can publish another demo. All of the levels before now have had programs spawning with only one sector, the head, and only gaining sectors when they move. This has made it easy to add sectors to the back of an array so they can be removed when a program is attacked.

Some of the levels I’m making have programs spawning with many sectors. I initially solved this by adding sectors to my two dimensional level data array, then adding those sectors to each program’s sector array when I iterate through the level data to build the level. This worked, but was flawed. It would usually add sectors in the wrong order, meaning if a program was attacked before it had replaced all its sectors by moving, it could be left with floating sectors not connected to the rest of the program:

The purple sector to the right of the yellow program is part of the purple program on the right. It can be attacked and functions just the same as the other sectors, but isn’t attached to the program. This might create a mess of floating sectors that detracts from the game.

My solution is to use my Dijkstra function to work out how far each sector is from the program’s head, then arrange them so the furthest get removed first. It looks like this (bear in mind the program’s head was in the top-right corner when it spawned):