How do I make a 1st, 2nd and 3rd place system?

Hello, I am trying to make a racing game and I need to make a system that ranks people by how many laps they have.
An example of this would be:

-------------Laps-----------Ranking------------
 - Player2: 5                 🥇
 - Player1: 3                 🥈
 - Player3: 2                 🥉

Any help would be nice, Thank you!

1 Like

Probably a more efficient way of doing this, but this could work:

local First, Second, Third
local FirstLap, SecondLap, ThirdLap = -1, -1, -1

function updateRankings()
    FirstLap, SecondLap, ThirdLap = -1, -1, -1
	for _, plr in ipairs(game.Players:GetPlayers()) do
		if plr:FindFirstChild("leaderstats") then
			if leaderstats.Laps.Value > FirstLap then
				Third = Second
				ThirdLap = SecondLap

				Second = First
				SecondLap = FirstLap

				First = plr
				FirstLap = leaderstats.Laps.Value
			elseif leaderstats.Laps.Value > SecondLap then
				Third = Second
				ThirdLap = SecondLap                

				Second = plr
				SecondLap = leaderstats.Laps.Value
			elseif leaderstats.Laps.Value > ThirdLap then
				Third = plr
				ThirdLap = leaderstats.Laps.Value
			end
		end
	end
end

Run the function after each race and then the First, Second, and Third variables will hold the player with that ranking!

What you need my friend is a sorting algorithm, fun thing is that there is a metric crap ton of sorting algorithms. Just to keep it simple we will do an insertion sort.

You will need to sort them from highest to lowest and to do that we need will need to create a function

function insertionSort(tbl) -- A table of all the laps
    local placeHolder = nil
    for i=1,#tbl,1 do
        for ix=i,1,-1 do
            if tbl[ix] > tbl[ix-1] then
                --Swaping
                placeHolder = tbl[ix-1]
                tbl[ix-1] = tbl[ix]
                tbl[ix] = placeHolder
            else
                break
            end
        end
    end
end

I just created the algorithm without testing so you will have to do some test. You will also need to decide how you assign the names of each lap to the player. I recommend you maybe record the lap times, so that you can pull this off.

EDIT: You would need the above in case say that the fourth place contender is on the same lap as the 3rd place contender. Well then you would need to consider their lap times in order to see who is ahead. This is commonly done in racing games.

2 Likes

I decided to just show the player that won the current race. All of that was a little bit too confusing