Creating a complex table sorting system

Context

I’m currently scripting a turn-based combat system where each player can choose to make 3 (or more) actions per turn, and each action has a priority value. Instead of using some other factor like a “Speed” stat, moves will simply be performed in order of highest priority to least priority.

The Issue

Now this normally would be simple, however I also want moves with identical priorities to be ordered randomly. For example, say we logged two battle participants’ actions here.

local participantActions = {
	{"Action1", 5}, -- ActionName, priority
	{"Action2", 5},
	{"Action4", 3},
	{"Action3", 4},
	{"Action5", 5},
}

sortActions(participantActions) --> sorted list; 

In this example, I would like actions 3 & 4 to be swapped accordingly, however actions 1, 2, & 5 should be in random positions in the top three.

  • This is mainly meant to be resemble Pokemon’s turn-based battling system, where moves do not have priorities, moreso the Pokemon themselves all have speed stats. Whichever Pokemon with the highest Speed stat moves first, except for when multiple Pokemon have identical Speed stats, in which case who goes first is chosen randomly.
1 Like
local function sortActions()
	local randomNumbers = {}
	
	-- assign each action a random number we can use for when multiple actions share the same priority
	for _, action in participantActions do
		randomNumbers[action] = math.random()
	end
	
	table.sort(participantActions, function(a, b)
		if a[2] == b[2] then
			return randomNumbers[a] > randomNumbers[b]
		end
		return a[2] > b[2]
	end)
end

sortActions()
2 Likes

thank you so much, I cant believe I didn’t think of this

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.