X How to detect amount of actions completed in time period

I am making an achievement/badge that is awarded to players in case they do some specific action X times in under Y duration.
For example: do something 10 times in under 20 seconds, and then I award the badge to the player(s) who do it. The players can start doing the actions at any time, so there is no start-now-and-go-for-X-time event to make this easier to code.

I have been thinking about how should I go about coding this, but I am not an experienced coder so probably overcomplicating it in my head.

I could have something like a table/array, where I would record every time (when the players do the action) the [player, time], then occasionally order the table by players, go through it all, count how many times there is an entry for a specific player, if it is more then the required count then I could check the 1st time and compare it to the time of the required amount and if that is lower than the time requirement then award the badge.
Then remove the entries for the player from the table who has been awarded + also the entries for players who have not achieved the required count, to avoid the table growing all the time.

Is this a good way to think about it?
Do you have any better ideas to solve this?

Thanks in advance for any guidance you could provide on how to go about this!

I could give you a general approach for what you are trying to achieve.

local completionTimes = (0); -- // For each completion, you will add 1.

local TIME = (10);
task.delay(TIME, function()
	if (completionTimes > 10) then
		-- // Completed
		-- // Failed to complete in time.
1 Like
local currTime = tick()
local achievementCount = 0

while task.wait() do
	newTime = tick()
	timeDifference = newTime - currTime
	if timeDifference <= 600 and achievementCount >= 10 then --equal to or more than 10 achievements in less than 10 minutes then
		--do something

Thanks @ComplexMetatable , @Forummer ,

I guess these would work perfectly when used in local scripts, for each individual player, but that would not be secure. I should not add badges based on that.

I’ll think about how to use this in a server script and make it work for all players who could be doing the “thing” that is counted.
Sounds difficult…

1 Like

You could use a similar idea but create a table to manage each player for a server-based implementation.

OK, thanks!
I’ll try to figure out how to do that and then post the solution when I succeed.

Edit: Managed to solve the problem. It works perfectly but is likely not the most elegant solution with my programming skills so I won’t share it now to prevent freaking you out.
Of course, I can help if anybody needs to do something similar and there is no better idea. Just ask!

I used it to solve this problem: