I have been working on a team balance script that balances money. (e.g two players have 15 cash and the third player has 40 cash, hence the two players will be on one team while the third player would be on another team.)

I had an idea where it would change every time a player was leaving or joining. So I came up with something sorta like this: (it is in a ModuleScript under ServerScriptService)

It has no errors, just doesn't accomplish what I need to fully do. Sometimes there's a team unbalance where a team would have 100 cash and the other team would have 5 cash.

Heres how it would work: a tolerancy would be created by adding up everyone's cash then dividing it by two (cause of two teams) So whatever cash is added beyond tolerancy it would put that player on the other team.

If you have any questions you can ask anytime

function module:ATeamBalance()
	
	--Variables
	local players = game.Players:GetPlayers()
	local total = 0
	local tolerancy 
	local grade = 1
	local starterPlayer = players[1]
	local starterCash = starterPlayer:WaitForChild("leaderstats").Money.Value
	--One player scenario
	if #players == 1 then
		return ("cannot balance team if no people")
	end
	
	--Finding total cash players have
	for i,v in pairs(players) do 
		total = total + v:WaitForChild("leaderstats").Money.Value
	end
	
	--Finding the cash teams must go up to. 
	tolerancy = math.floor(total / 2)
	
	--If starter cash is bigger than tolerancy
	while starterCash > tolerancy do
		grade = grade + 1
		starterPlayer = players[grade]
		starterCash = starterPlayer:WaitForChild("leaderstats").Money.Value
		wait()
	end
	if #players >= 2 then
		for i,v in pairs(players) do
			if starterPlayer ~= v and starterCash <= tolerancy then --assinging survivors if they have less cash then tolerancy.
				if v:WaitForChild("leaderstats").Money.Value <= tolerancy then -- If the current one has cash less than tolerancy
					starterCash = starterCash + v:WaitForChild("leaderstats").Money.Value
					v.Team = game.Teams.Team1
					starterPlayer.Team = game.Teams.Team1
				elseif v:WaitForChild("leaderstats").Money.Value >= tolerancy then
				
					--starterCash = v.leaderstats.Money.Value
					v.Team = game.Teams.Team2
				end
			elseif starterCash > tolerancy then
				starterCash = 0
				v.Team = game.Teams.Team2
			end
		end
	end
end

2 comments

0

How many players can there be total? Don't you want to balance for both money and team player count? One can have priority over the other, but when there are multiple solutions for balancing money, it would be weird to choose the one with the most uneven player count, wouldn't it?

0

There can be only 10 players total, I wanna only balance for money.