Skip to content
View in the app

A better way to browse. Learn more.

Learn more

automatic-team-balance/addons/amxmodx/scripting/olds_teambalance.sma

olds_teambalance.sma
293 lines · 8.1 KB · Pawn (AMX Mod X)
Raw
/*
 * Automatic Team Balance (olds.ro workshop card LIB-2193)
 *
 * When a round ends with one team bigger than the other by more than
 * olds_tb_diff players, players are moved from the bigger team to the
 * smaller one until the difference is small enough, at most
 * olds_tb_maxmoves players per round end. Moved players are not killed: they
 * start the next round on their new team, with their score kept.
 *
 * Who is moved first (from the bigger team):
 *   olds_tb_skill 0   players who are dead at the round end before living
 *                     ones; among them the lowest score (frags); on a tie,
 *                     the one who died first.
 *   olds_tb_skill 1   the player whose move brings the two teams' skill
 *                     totals (sum of frags minus deaths) closest together;
 *                     on a tie, the order above.
 *   The bomb carrier and the VIP are never moved.
 *
 * Teams of equal size, or within olds_tb_diff, are left alone and no message
 * is printed. Turn the game's own balancing off (mp_autoteambalance 0) so the
 * two do not both move players.
 *
 * Cvars (configs/plugins/olds_teambalance.cfg; AutoExecConfig writes that
 * file with these defaults if it is missing):
 *   olds_tb_diff     1   Largest allowed difference between the team sizes (1 - 31).
 *   olds_tb_skill    0   1 = choose by skill (frags minus deaths), 0 = by score and death order.
 *   olds_tb_maxmoves 2   Most players moved at one round end (0 = balancing off, up to 31).
 *   olds_tb_warn     1   1 = announce each move in chat, 0 = move silently.
 *
 * Every text players read comes from data/lang/olds_teambalance.txt (English).
 *
 * Requires AMX Mod X 1.10 or newer and ReAPI with ReGameDLL_CS. Written and
 * tested on AMX Mod X 1.10.0.5490, ReAPI 5.29.0.358, ReGameDLL_CS 5.30.0.814.
 *
 * Copyright (C) 2026 alexit (olds.ro workshop)
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details: <https://www.gnu.org/licenses/>.
 */

#include <amxmodx>
#include <amxmisc>
#include <reapi>

#pragma semicolon 1

new const PLUGIN_NAME[] = "Automatic Team Balance";
new const PLUGIN_VERSION[] = "1.0.0";
new const PLUGIN_AUTHOR[] = "alexit (olds.ro)";

new const DICTIONARY[] = "olds_teambalance.txt";

// Value of g_deathTime[] for a player who has not died since spawning.
const Float:NOT_DEAD = 0.0;

new g_maxDiff;       // olds_tb_diff
new g_skillMode;     // olds_tb_skill
new g_maxMoves;      // olds_tb_maxmoves
new g_warn;          // olds_tb_warn

// Game time of each player's last death this round, used to find who died first.
new Float:g_deathTime[MAX_PLAYERS + 1];

public plugin_init()
{
	register_plugin(PLUGIN_NAME, PLUGIN_VERSION, PLUGIN_AUTHOR);
	register_dictionary(DICTIONARY);

	bind_pcvar_num(create_cvar("olds_tb_diff", "1", FCVAR_NONE,
		"Largest allowed difference between the T and CT player counts (1 - 31)",
		true, 1.0, true, 31.0), g_maxDiff);

	bind_pcvar_num(create_cvar("olds_tb_skill", "0", FCVAR_NONE,
		"1 = move the player whose move evens the teams' frags minus deaths the most, 0 = by score and death order",
		true, 0.0, true, 1.0), g_skillMode);

	bind_pcvar_num(create_cvar("olds_tb_maxmoves", "2", FCVAR_NONE,
		"Most players moved at one round end (0 = balancing off)",
		true, 0.0, true, 31.0), g_maxMoves);

	bind_pcvar_num(create_cvar("olds_tb_warn", "1", FCVAR_NONE,
		"1 = announce each move in chat, 0 = move players silently",
		true, 0.0, true, 1.0), g_warn);

	AutoExecConfig(true, "olds_teambalance");

	RegisterHookChain(RG_RoundEnd, "OnRoundEnd_Post", true);
	RegisterHookChain(RG_CBasePlayer_Killed, "OnPlayerKilled_Post", true);
	RegisterHookChain(RG_CBasePlayer_Spawn, "OnPlayerSpawn_Post", true);
}

public plugin_cfg()
{
	if (get_cvar_num("mp_autoteambalance"))
		server_print("[%s] %L", PLUGIN_NAME, LANG_SERVER, "OLDS_TB_GAME_BALANCE_ON");
}

public client_disconnected(id)
{
	g_deathTime[id] = NOT_DEAD;
}

public OnPlayerKilled_Post(victim, attacker, gib)
{
	g_deathTime[victim] = get_gametime();
}

public OnPlayerSpawn_Post(id)
{
	if (is_user_alive(id))
		g_deathTime[id] = NOT_DEAD;
}

/**
 * The round has just ended. The game can refuse to end it (for example a
 * second end in the same round); then nothing is balanced.
 */
public OnRoundEnd_Post(WinStatus:status, ScenarioEventEndRound:event, Float:delay)
{
	if (!GetHookChainReturn(ATYPE_BOOL) || g_maxMoves <= 0)
		return;

	balance_teams();
}

balance_teams()
{
	new moves = 0;

	while (moves < g_maxMoves)
	{
		new terrorists, cts, terroristSkill, ctSkill;
		count_teams(terrorists, cts, terroristSkill, ctSkill);

		// Each move narrows the gap by two, so the loop always ends.
		if (abs(terrorists - cts) <= g_maxDiff)
			break;

		new TeamName:from, TeamName:to, skillGap;

		if (terrorists > cts)
		{
			from = TEAM_TERRORIST;
			to = TEAM_CT;
			skillGap = terroristSkill - ctSkill;
		}
		else
		{
			from = TEAM_CT;
			to = TEAM_TERRORIST;
			skillGap = ctSkill - terroristSkill;
		}

		new player = choose_player(from, skillGap);

		// Only the bomb carrier or the VIP is left to move.
		if (!player)
			break;

		rg_set_user_team(player, to, MODEL_AUTO, true, false);
		moves++;

		if (g_warn)
			announce_move(player, to);
	}
}

/**
 * Counts the players on each side (dead ones included, HLTV proxies left
 * out) and adds up each side's skill, frags minus deaths.
 */
count_teams(&terrorists, &cts, &terroristSkill, &ctSkill)
{
	new players[MAX_PLAYERS], count;
	get_players_ex(players, count, GetPlayers_ExcludeHLTV);

	terrorists = cts = terroristSkill = ctSkill = 0;

	for (new i = 0; i < count; i++)
	{
		new id = players[i];

		switch (get_member(id, m_iTeam))
		{
			case TEAM_TERRORIST:
			{
				terrorists++;
				terroristSkill += skill_of(id);
			}
			case TEAM_CT:
			{
				cts++;
				ctSkill += skill_of(id);
			}
		}
	}
}

skill_of(id)
{
	return get_user_frags(id) - get_member(id, m_iDeaths);
}

/**
 * The player of team "from" to move, or 0 when nobody there may be moved.
 * skillGap is how much stronger "from" is than the other team.
 */
choose_player(TeamName:from, skillGap)
{
	new players[MAX_PLAYERS], count;
	get_players_ex(players, count, GetPlayers_ExcludeHLTV);

	new best = 0;

	for (new i = 0; i < count; i++)
	{
		new id = players[i];

		if (get_member(id, m_iTeam) != from || !can_move(id))
			continue;

		if (!best || comes_before(id, best, skillGap))
			best = id;
	}

	return best;
}

bool:can_move(id)
{
	// Moving the carrier would take the bomb to the other team, and the VIP
	// is the whole objective of an as_ map.
	if (user_has_weapon(id, CSW_C4) || get_member(id, m_bHasC4))
		return false;

	if (get_member(id, m_bIsVIP))
		return false;

	return true;
}

/**
 * Tells whether player a should be moved before player b.
 */
bool:comes_before(a, b, skillGap)
{
	if (g_skillMode)
	{
		// After moving a player with skill s the gap becomes skillGap - 2s.
		new gapA = abs(skillGap - 2 * skill_of(a));
		new gapB = abs(skillGap - 2 * skill_of(b));

		if (gapA != gapB)
			return gapA < gapB;
	}

	new bool:aliveA = is_user_alive(a) != 0;
	new bool:aliveB = is_user_alive(b) != 0;

	// Moving a dead player takes nothing away from a round in progress.
	if (aliveA != aliveB)
		return !aliveA;

	new fragsA = get_user_frags(a);
	new fragsB = get_user_frags(b);

	if (fragsA != fragsB)
		return fragsA < fragsB;

	// Both dead: the one who died first. A death time of NOT_DEAD (unknown,
	// for example a player who joined dead) counts as the earliest.
	if (!aliveA && g_deathTime[a] != g_deathTime[b])
		return g_deathTime[a] < g_deathTime[b];

	return false;
}

announce_move(id, TeamName:to)
{
	new name[MAX_NAME_LENGTH];
	get_user_name(id, name, charsmax(name));

	client_print_color(0, print_team_default, "^4*^1 %L", LANG_PLAYER,
		to == TEAM_TERRORIST ? "OLDS_TB_MOVED_T" : "OLDS_TB_MOVED_CT", name);
}

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.