Level generation system

Essentially, this system is for a game where the amount of “XP” a user has determines their level. Instead of having to manually bind each level to a certain amount of XP, I have created a system where the nth level’s XP requirement is 2n² + 50n-1:

function LevelModule.getLevels(amountOfLevels)
	local levels = {}
	for i = 1, amountOfLevels do
		local nthLevel = 2*(i^2) + (50*i)-1
		levels[i] = nthLevel
	end
	
	return levels
end

This works perfectly so far, however are there any improvements I could make? Is this a performant method to achieve what I am trying to do?

1 Like

This looks like a valid way to calculate the required XP for each level. It appears that you are using a polynomial function to calculate the required XP, which is a common approach to calculating levels in games.

One potential improvement you could make is to add some error handling to your function in case the input is not valid. For example, you may want to check that the value of amountOfLevels is a positive integer before proceeding with the calculation. You could do this by adding a check at the beginning of the function like this:

if type(amountOfLevels) ~= "number" or amountOfLevels % 1 ~= 0 or amountOfLevels < 1 then
  error("amountOfLevels must be a positive integer")
end

This will throw an error if the input is not a positive integer, which will help prevent any unexpected behavior in your code.

In terms of performance, this function should be sufficient for most purposes. The time complexity of this function is O(n), which means that the amount of time it takes to run the function will increase linearly with the number of levels. For small values of amountOfLevels , the function should run very quickly. However, if you are expecting to have a very large number of levels (e.g. millions or billions), you may want to consider using a more efficient algorithm to calculate the required XP.

Thank you for the feedback! I will definitely add in the error handling, and thank you for your information with regard to the time complexity.

np! tell me if there is something wrong and I will try to fix it

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