Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Copyright 2010 Miguel Mendoza - miguel@micovery.com
- *
- * Insane Balancer 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. Insane Balancer 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. You should have received a copy of the
- * GNU General Public License along with Insane Balancer. If not, see http://www.gnu.org/licenses/.
- *
- */
- using System;
- using System.IO;
- using System.Text;
- using System.Reflection;
- using System.Collections.Generic;
- using System.Collections;
- using System.Net;
- using System.Threading;
- //using System.Drawing;
- //using System.Drawing.Drawing2D;
- using System.Data;
- using System.Text.RegularExpressions;
- using PRoCon.Core;
- using PRoCon.Core.Plugin;
- using PRoCon.Core.Plugin.Commands;
- using PRoCon.Core.Players;
- using PRoCon.Core.Players.Items;
- using PRoCon.Core.Battlemap;
- using PRoCon.Core.Maps;
- namespace PRoConEvents
- {
- public class InsaneBalancer : PRoConPluginAPI, IPRoConPluginInterface
- {
- int check_state_phase = 0;
- bool virtual_mode = false;
- int win_teamId, lose_teamId;
- public bool run_balancer = false;
- public bool level_started = false;
- private class PlayerSquad
- {
- public List<PlayerProfile> members;
- int squadId = 0;
- int teamId = 0;
- public PlayerSquad(int tid, int sid)
- {
- members = new List<PlayerProfile>();
- teamId = tid;
- squadId = sid;
- }
- public PlayerSquad(PlayerSquad squad)
- {
- squadId = squad.squadId;
- teamId = squad.squadId;
- members = squad.members;
- }
- private bool playerBelongs(PlayerProfile player)
- {
- return getTeamId() == player.getTeamId() && getSquadId() == player.getSquadId();
- }
- public bool hasPlayer(PlayerProfile player)
- {
- return members.Contains(player);
- }
- public int getFreeSlots()
- {
- if (getSquadId() == 0)
- return 32;
- return 4 - getCount();
- }
- public bool addPlayer(PlayerProfile player)
- {
- if (!playerBelongs(player) || hasPlayer(player))
- return false;
- members.Add(player);
- return true;
- }
- public virtual int getTeamId()
- {
- return teamId;
- }
- public virtual int getSquadId()
- {
- return squadId;
- }
- public bool dropPlayer(PlayerProfile player)
- {
- if (!members.Contains(player))
- return false;
- members.Remove(player);
- return true;
- }
- public virtual PlayerProfile getRandomPlayer()
- {
- if (getCount() == 0)
- return null;
- /* 0 - player 0 has been chosen by fair dice roll */
- return members[0];
- }
- public PlayerProfile removeRandomPlayer()
- {
- PlayerProfile player = getRandomPlayer();
- if (player == null)
- return null;
- dropPlayer(player);
- return player;
- }
- public int getCount()
- {
- return members.Count;
- }
- public List<PlayerProfile> getMembers()
- {
- return members;
- }
- public double getRoundSpm()
- {
- int count = getCount();
- if (count == 0)
- return 0;
- double spm = 0;
- foreach (PlayerProfile player in getMembers())
- {
- spm += player.getRoundSpm();
- }
- return (spm / count);
- }
- public double getRoundKpm()
- {
- int count = getCount();
- if (count == 0)
- return 0;
- double kpm = 0;
- foreach (PlayerProfile player in getMembers())
- {
- kpm += player.getRoundKpm();
- }
- return (kpm / count);
- }
- public double getRoundKills()
- {
- int count = getCount();
- if (count == 0)
- return 0;
- double kills = 0;
- foreach (PlayerProfile player in getMembers())
- {
- kills += player.getRoundKills();
- }
- return (kills / count);
- }
- public double getRoundDeaths()
- {
- int count = getCount();
- if (count == 0)
- return 0;
- double deaths = 0;
- foreach (PlayerProfile player in getMembers())
- {
- deaths += player.getRoundDeaths();
- }
- return (deaths / count);
- }
- public double getRoundScore()
- {
- int count = getCount();
- if (count == 0)
- return 0;
- double score = 0;
- foreach (PlayerProfile player in getMembers())
- {
- score += player.getRoundScore();
- }
- return (score / count);
- }
- public double getRoundKdr()
- {
- return (getRoundKills() + 1) / (getRoundDeaths() + 1);
- }
- public override String ToString()
- {
- return "Team(" + getTeamId() + ").Squad(" + SQN(getSquadId()) + "): " + getMembersListStr();
- }
- public string getMembersListStr()
- {
- List<string> names = new List<string>();
- foreach (PlayerProfile player in members)
- names.Add(player.name);
- return String.Join(", ", names.ToArray());
- }
- public string getClanTag()
- {
- if (getCount() == 0)
- return "";
- return getRandomPlayer().getClanTag();
- }
- public string getMajorityClanTag()
- {
- if (getCount() == 0)
- return "";
- Dictionary<string, int> tagCount = new Dictionary<string, int>();
- string tag = "";
- /* count how many times each tag repeats */
- foreach (PlayerProfile player in getMembers())
- {
- tag = player.getClanTag();
- if (tag == null || tag.Length == 0)
- continue;
- if (!tagCount.ContainsKey(tag))
- tagCount[tag] = 0;
- tagCount[tag]++;
- }
- if (tagCount.Count == 0)
- return "";
- /* sort by ascending tag count */
- List<KeyValuePair<string, int>> list = new List<KeyValuePair<string, int>>(tagCount);
- list.Sort(delegate(KeyValuePair<string, int> left, KeyValuePair<string, int> right) { return left.Value.CompareTo(right.Value)*(-1); });
- return list[0].Key;
- }
- public void setSquadId(int sid)
- {
- squadId = sid;
- }
- public void setTeamId(int tid)
- {
- teamId = tid;
- }
- }
- private class PlayerMessage
- {
- public MessageType type;
- public string text;
- public int time;
- public PlayerMessage(string tx)
- {
- text = tx;
- type = MessageType.say;
- }
- }
- public enum PluginState { stop, wait, check, warn, balance };
- //variables to keep track of the start time for each state
- DateTime startStopTime;
- DateTime startWaitTime;
- DateTime startCheckTime;
- DateTime startWarnTime;
- DateTime startBalanceTime;
- DateTime startRoundTime;
- DateTime utc; //universal time;
- PluginState pluginState;
- CServerInfo serverInfo = null;
- bool plugin_enabled = false;
- public Dictionary<string, bool> booleanVariables;
- public Dictionary<string, int> integerVariables;
- public Dictionary<string, float> floatVariables;
- public Dictionary<string, string> stringListVariables;
- public Dictionary<string, string> stringVariables;
- public List<string> hiddenVariables;
- public delegate bool integerVariableValidator(string var, int value);
- public delegate bool booleanVariableValidator(string var, bool value);
- private delegate int player_sort_method(PlayerProfile left, PlayerProfile right);
- private delegate int squad_sort_method(PlayerSquad left, PlayerSquad right);
- public delegate bool stringVariableValidator(string var, string value);
- public Dictionary<string, integerVariableValidator> intergerVarValidators;
- public Dictionary<string, booleanVariableValidator> booleanVarValidators;
- public Dictionary<string, stringVariableValidator> stringVarValidators;
- private Dictionary<string, PlayerProfile> players;
- public enum PlayerState { dead, alive, left, kicked, limbo };
- public enum MessageType { say, invalid };
- private struct PlayerStats
- {
- public double rank;
- public double kills;
- public double deaths;
- public double score;
- public double skill;
- public void reset()
- {
- rank = 0;
- kills = 0;
- deaths = 0;
- score = 0;
- skill = 0;
- }
- public double kdr()
- {
- return (kills + 1) / (deaths + 1);
- }
- }
- private class PlayerProfile
- {
- private InsaneBalancer plugin;
- public string name;
- public PlayerStats stats;
- public PlayerStats round_stats;
- public PlayerState state;
- public CPlayerInfo info;
- public CPunkbusterInfo pbinfo;
- public Queue<PlayerMessage> qmsg; //queued messages
- int savedTeamId = -1;
- int savedSquadId = -1;
- int targetTeamId = -1;
- int targetSquadId = -1;
- public void leaveGame()
- {
- state = PlayerState.left;
- }
- public void spawned()
- {
- state = PlayerState.alive;
- }
- public bool isInGame()
- {
- return (info.TeamID != null && info.TeamID >= 0);
- }
- public PlayerProfile(PlayerProfile player)
- {
- /* shallow copy */
- updateInfo(player.info);
- pbinfo = player.pbinfo;
- name = player.name;
- plugin = player.plugin;
- stats = player.stats;
- state = player.state;
- qmsg = player.qmsg;
- }
- public PlayerProfile(InsaneBalancer plg, CPlayerInfo inf)
- {
- plg.DebugWrite("^1ENTER: PlayerProfile(InsaneBalancer, CPlayerInfo)", 7);
- pbinfo = new CPunkbusterInfo();
- name = info.SoldierName;
- plugin = plg;
- updateInfo(inf);
- resetStats();
- plg.DebugWrite("^1EXIT: PlayerProfile(InsaneBalancer, CPlayerInfo)", 7);
- }
- public PlayerProfile(InsaneBalancer plg, CPunkbusterInfo inf)
- {
- plg.DebugWrite("^1ENTER: PlayerProfile(InsaneBalancer, CPunkbusterInfo)", 7);
- info = new CPlayerInfo();
- pbinfo = inf;
- name = pbinfo.SoldierName;
- plugin = plg;
- resetStats();
- plg.DebugWrite("^1EXIT: PlayerProfile(InsaneBalancer, CPunkbusterInfo)", 7);
- }
- public PlayerProfile(InsaneBalancer plg, string nm)
- {
- plg.DebugWrite("^1ENTER: PlayerProfile(InsaneBalancer, string)", 7);
- name = nm;
- info = new CPlayerInfo();
- pbinfo = new CPunkbusterInfo();
- plugin = plg;
- resetStats();
- plg.DebugWrite("^1EXIT: PlayerProfile(InsaneBalancer, string)", 7);
- }
- public void updateInfo(CPlayerInfo inf)
- {
- plugin.DebugWrite("^1ENTER: updateInfo", 7);
- /* don't update the information while round is begining */
- if (plugin.run_balancer)
- return;
- info = inf;
- round_stats.kills = info.Kills;
- round_stats.deaths = info.Deaths;
- round_stats.score = info.Score;
- plugin.DebugWrite("^1EXIT: updateInfo", 7);
- }
- public void resetStats()
- {
- plugin.DebugWrite("^1ENTER: resetStats for ^b"+name, 7);
- //queued messages
- qmsg = new Queue<PlayerMessage>();
- //other
- state = PlayerState.limbo;
- round_stats.reset();
- savedSquadId = -1;
- savedTeamId = -1;
- targetSquadId = -1;
- targetTeamId = -1;
- plugin.DebugWrite("^1EXIT: resetStats for ^b" + name, 7);
- }
- /* Player Messages */
- public void dequeueMessages()
- {
- while (this.qmsg.Count > 0)
- {
- PlayerMessage msg = this.qmsg.Dequeue();
- if (msg.type.Equals(MessageType.say))
- {
- this.plugin.SendPlayerMessage(name, msg.text);
- }
- }
- }
- public void enqueueMessage(PlayerMessage msg)
- {
- this.qmsg.Enqueue(msg);
- }
- /* Round Level Statistics */
- public double getRoundKpm()
- {
- double minutes = plugin.getRoundMinutes();
- double kills = getRoundKills();
- return kills / minutes;
- }
- public double getRoundSpm()
- {
- double minutes = plugin.getRoundMinutes();
- double score = getRoundScore();
- return score / minutes;
- }
- public double getRoundKills()
- {
- return round_stats.kills;
- }
- public double getRoundScore()
- {
- return round_stats.score;
- }
- public double getRoundDeaths()
- {
- return round_stats.deaths;
- }
- public double getRoundKdr()
- {
- return (getRoundKills() + 1) / (getRoundDeaths() + 1);
- }
- public override string ToString()
- {
- return this.name;
- }
- /* Player State and Information */
- public bool isAlive()
- {
- return state.Equals(PlayerState.alive);
- }
- public bool isDead()
- {
- return state.Equals(PlayerState.dead);
- }
- public bool wasKicked()
- {
- return state.Equals(PlayerState.kicked);
- }
- public string getClanTag()
- {
- if (info == null || info.ClanTag == null || info.ClanTag.Length == 0)
- return "";
- return info.ClanTag.ToLower();
- }
- public bool isInClan()
- {
- return getClanTag().Length > 0;
- }
- public virtual void setSquadId(int sid)
- {
- info.SquadID = sid;
- }
- public virtual void setTeamId(int tid)
- {
- info.TeamID = tid;
- }
- public virtual int getSquadId()
- {
- return info.SquadID;
- }
- public virtual int getTeamId()
- {
- return info.TeamID;
- }
- public void saveTeamSquad()
- {
- if (savedTeamId == -1)
- savedTeamId = getTeamId();
- if (savedSquadId == -1)
- savedSquadId = getSquadId();
- }
- public void saveTargetTeamSquad()
- {
- if (targetTeamId == -1)
- targetTeamId = getTeamId();
- if (targetSquadId == -1)
- targetSquadId = getSquadId();
- }
- public int getSavedSquadId()
- {
- return savedSquadId;
- }
- public int getSavedTeamId()
- {
- return savedTeamId;
- }
- public int getTargetSquadId()
- {
- return targetSquadId;
- }
- public int getTargetTeamId()
- {
- return targetTeamId;
- }
- public void resetTeamSquad()
- {
- if (savedTeamId > 0)
- setTeamId(savedTeamId);
- if (savedSquadId > 0)
- setSquadId(savedSquadId);
- }
- public string getRoundStatistics()
- {
- return String.Format("score({0}), kills({1}), deaths({2}) kdr({3}), spm({4}), kpm({5})", getRoundScore(), getRoundKills(), getRoundDeaths(), Math.Round(getRoundKdr(),2) , Math.Round(getRoundSpm(),2), Math.Round(getRoundKpm(),2));
- }
- }
- public InsaneBalancer()
- {
- utc = DateTime.Now;
- startRoundTime = utc;
- this.players = new Dictionary<string, PlayerProfile>();
- this.booleanVariables = new Dictionary<string, bool>();
- this.booleanVariables.Add("auto_start", true);
- this.booleanVariables.Add("keep_squads", true);
- this.booleanVariables.Add("keep_clans", false);
- this.booleanVariables.Add("warn_say", false);
- this.booleanVariables.Add("balance_round", true);
- this.booleanVariables.Add("balance_live", true);
- this.booleanVariables.Add("quiet_mode", false);
- this.booleanVariables.Add("advanced_mode", false);
- this.integerVariables = new Dictionary<string, int>();
- this.integerVariables.Add("balance_threshold", 1);
- this.integerVariables.Add("debug_level", 3);
- this.integerVariables.Add("live_interval_time", 15);
- this.integerVariables.Add("round_interval", 1);
- this.integerVariables.Add("warn_msg_interval_time", 15);
- this.integerVariables.Add("warn_msg_total_time", 15);
- this.integerVariables.Add("warn_msg_countdown_time", 3);
- this.integerVariables.Add("warn_msg_display_time", 5);
- this.intergerVarValidators = new Dictionary<string, integerVariableValidator>();
- this.intergerVarValidators.Add("warn_msg_interval_time", integerValidator);
- this.intergerVarValidators.Add("warn_msg_total_time", integerValidator);
- this.intergerVarValidators.Add("warn_msg_display_time", integerValidator);
- this.intergerVarValidators.Add("warn_msg_countdown_time", integerValidator);
- this.intergerVarValidators.Add("balance_threshold", integerValidator);
- this.intergerVarValidators.Add("round_interval", integerValidator);
- this.intergerVarValidators.Add("live_interval_time", integerValidator);
- this.intergerVarValidators.Add("debug_level", integerValidator);
- this.booleanVarValidators = new Dictionary<string, booleanVariableValidator>();
- this.booleanVarValidators.Add("keep_squads", booleanValidator);
- this.booleanVarValidators.Add("keep_clans", booleanValidator);
- this.stringVarValidators = new Dictionary<string, stringVariableValidator>();
- this.stringVarValidators.Add("round_sort", stringValidator);
- this.stringVarValidators.Add("live_sort", stringValidator);
- this.floatVariables = new Dictionary<string, float>();
- this.stringListVariables = new Dictionary<string, string>();
- this.stringListVariables.Add("admin_list", @"micovery, admin2, admin3");
- this.stringVariables = new Dictionary<string, string>();
- this.stringVariables.Add("round_sort", "spm_desc_round");
- this.stringVariables.Add("live_sort", "spm_desc_round");
- this.hiddenVariables = new List<string>();
- this.hiddenVariables.Add("warn_msg_total_time");
- this.hiddenVariables.Add("warn_msg_countdown_time");
- this.hiddenVariables.Add("warn_msg_interval_time");
- this.hiddenVariables.Add("warn_msg_display_time");
- this.hiddenVariables.Add("quiet_mode");
- this.hiddenVariables.Add("debug_level");
- this.hiddenVariables.Add("auto_start");
- }
- public void loadSettings()
- {
- }
- private player_sort_method getPlayerSort(string phase)
- {
- string sort_method = getStringVarValue(phase);
- if (sort_method.CompareTo("kdr_asc_round") == 0)
- return player_kdr_asc_round_cmp;
- else if (sort_method.CompareTo("kdr_desc_round") == 0)
- return player_kdr_desc_round_cmp;
- else if (sort_method.CompareTo("score_asc_round") == 0)
- return player_score_asc_round_cmp;
- else if (sort_method.CompareTo("score_desc_round") == 0)
- return player_score_desc_round_cmp;
- else if (sort_method.CompareTo("spm_asc_round") == 0)
- return player_spm_asc_round_cmp;
- else if (sort_method.CompareTo("spm_desc_round") == 0)
- return player_spm_desc_round_cmp;
- else if (sort_method.CompareTo("kpm_asc_round") == 0)
- return player_kpm_asc_round_cmp;
- else if (sort_method.CompareTo("kpm_desc_round") == 0)
- return player_kpm_desc_round_cmp;
- ConsoleWrite("cannot find player sort method for ^b" + sort_method + "^0 during ^b" + phase + "^n, using default sort");
- return player_spm_asc_round_cmp;
- }
- private squad_sort_method getSquadSort(string phase)
- {
- string sort_method = getStringVarValue(phase);
- if (sort_method.CompareTo("kdr_asc_round") == 0)
- return squad_kdr_asc_round_cmp;
- else if (sort_method.CompareTo("kdr_desc_round") == 0)
- return squad_kdr_desc_round_cmp;
- else if (sort_method.CompareTo("score_asc_round") == 0)
- return squad_score_asc_round_cmp;
- else if (sort_method.CompareTo("score_desc_round") == 0)
- return squad_score_desc_round_cmp;
- else if (sort_method.CompareTo("spm_asc_round") == 0)
- return squad_spm_asc_round_cmp;
- else if (sort_method.CompareTo("spm_desc_round") == 0)
- return squad_spm_desc_round_cmp;
- else if (sort_method.CompareTo("kpm_asc_round") == 0)
- return squad_kpm_asc_round_cmp;
- else if (sort_method.CompareTo("kpm_desc_round") == 0)
- return squad_kpm_desc_round_cmp;
- ConsoleWrite("cannot find squad sort method for ^b" + sort_method + "^0 during ^b" + phase + "^n, using default sort");
- return squad_kpm_desc_round_cmp;
- }
- /* squad comparison methods */
- private int squad_count_asc_cmp(PlayerSquad left, PlayerSquad right)
- {
- int lval = left.getCount();
- int rval = right.getCount();
- return lval.CompareTo(rval);
- }
- private int squad_count_desc_cmp(PlayerSquad left, PlayerSquad right)
- {
- return squad_count_asc_cmp(left, right) * (-1);
- }
- private int squad_kdr_asc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- double lval = left.getRoundKdr();
- double rval = right.getRoundKdr();
- return lval.CompareTo(rval);
- }
- private int squad_kdr_desc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- return squad_kdr_asc_round_cmp(left, right) * (-1);
- }
- private int squad_spm_asc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- double lval = left.getRoundSpm();
- double rval = right.getRoundSpm();
- return lval.CompareTo(rval);
- }
- private int squad_spm_desc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- return squad_spm_asc_round_cmp(left, right) * (-1);
- }
- private int squad_score_asc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- double lval = left.getRoundScore();
- double rval = right.getRoundScore();
- return lval.CompareTo(rval);
- }
- private int squad_score_desc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- return squad_score_asc_round_cmp(left, right) * (-1);
- }
- private int squad_kpm_asc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- double lval = left.getRoundKpm();
- double rval = right.getRoundKpm();
- return lval.CompareTo(rval);
- }
- private int squad_kpm_desc_round_cmp(PlayerSquad left, PlayerSquad right)
- {
- return squad_kpm_asc_round_cmp(left, right) * (-1);
- }
- /* player comparison methods */
- private int player_kdr_asc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- double lval = left.getRoundKdr();
- double rval = right.getRoundKdr();
- return lval.CompareTo(rval);
- }
- private int player_kdr_desc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- return player_kdr_asc_round_cmp(left, right) * (-1);
- }
- private int player_spm_asc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- double lval = left.getRoundSpm();
- double rval = right.getRoundSpm();
- return lval.CompareTo(rval);
- }
- private int player_spm_desc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- return player_spm_asc_round_cmp(left, right) * (-1);
- }
- private int player_score_asc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- double lval = left.getRoundScore();
- double rval = right.getRoundScore();
- return lval.CompareTo(rval);
- }
- private int player_score_desc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- return player_score_asc_round_cmp(left, right) * (-1);
- }
- private int player_kpm_asc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- double lval = left.getRoundKpm();
- double rval = right.getRoundKpm();
- return lval.CompareTo(rval);
- }
- private int player_kpm_desc_round_cmp(PlayerProfile left, PlayerProfile right)
- {
- return player_kpm_asc_round_cmp(left, right) * (-1);
- }
- public void unloadSettings()
- {
- this.players.Clear();
- }
- public string GetPluginName()
- {
- return "Insane Balancer";
- }
- public string GetPluginVersion()
- {
- return "0.0.0.2";
- }
- public string GetPluginAuthor()
- {
- return "micovery";
- }
- public string GetPluginWebsite()
- {
- return "www.insanegamersasylum.com";
- }
- public string GetPluginDescription()
- {
- return @"
- <h2>Description</h2>
- <p> This is the draft impelementation for a flexible team balancer, which can balance teams by skill, rank, score, kdr and other rules.
- All of it, while doing best effort to maintain squads together, and clans on the same team.
- </p>
- <h2>Sort Methods</h2>
- <p> A sort method is a rule used for sorting a list of players or squads. The following balancing methods are supported:
- </p>
- <ul>
- <li><b>kpm_asc_round</b> , <b>kpm_desc_round</b> <br />
- Sorting based on the soldier round kills per minute
- </li>
- <li><b>spm_asc_round</b> , <b>spm_desc_round</b> <br />
- Sorting based on the soldier round score per minute
- </li>
- <li><b>kdr_asc_round</b> , <b>kdr_desc_round</b> <br />
- Sorting based on the soldier round kill to death ratio
- </li>
- <li><b>score_asc_round</b> , <b>score_desc_round</b> <br />
- Sorting based on the soldier round score
- </li>
- </ul>
- All the data for sorting rules ending in <b>_round</b> is obtained from the previous or current round statistics.
- <h2>Live Balancing Logic</h2>
- <blockquote>
- Insane Balancer tries to be as un-intrusive as posible while balancing a game that is in progress.
- If the teams become un-balanced while the game is in progess it will create two pools of players and sort them.
- (players chosen from the bigger team) One pool for players who are not in any squad, and another pool for squads.
- First it will chose the player at the top of the no-squad pool and move it to the other team until teams are balanced.
- If the no-squad pool becomes empty (and teams are still unbalanced) then squad at the top of the squad pool is moved
- to the other team if the number of players needed is greater than or equal to the size of the squad. If the number of players
- needed is less than the size of the top squad, a random random player is chosen from the squad and moved to the opposite team
- until teams are balanced. (players that were on the same squad are kept together)
- </blockquote>
- <h2>Round Re-balancing Logic</h2>
- <blockquote>
- If end of round balancing is enabled, Insane Balancer will completely re-sort teams, even if they are already balanced.
- The logic for the re-sort is as follows. Create two pools of players and sort them (choosing players from all teams).
- One pool for players who are not in squads, and another for players who are in squads. Then, move all all players and squads
- to the neutral team, in order to end up with two empty non-neutral teams. Then, pick the squad at the top of the squad pool,
- and move it to the losing team. Then pick the next squad on top of the squad pool, and move it to the team with the least players, and so on.
- Once the squad pool is empty, pick the player on top of the no-squad pool, and move it to the team with least players, and so on.
- If teams are still unbalanced after the no-squad pool is empty, then the live balancing logic is applied.
- </blockquote>
- <h2>Balanced Team Determination </h2>
- <blockquote>
- Teams are determined to be balanced if the difference in number of players between teams is less than or equal to the <b>balance_threshold</b>.
- The <b>balance_threshold</b> has to be a number greater than 0. If the total number of players in the server is less than or equal to the
- <b>balance_threshold</b>, then the user set threshold is ignored, and a value of 1 is used instead. Technically, no team should ever be bigger
- than the other by more than the value of <b>balance_threshold</b>.
- </blockquote>
- <h2>Keeping Squads Together </h2>
- <blockquote>
- Insane Balancer is coded to keep squads together by default. However, you can set <b>keep_squads</b> to false and both round-balancing and
- live-balancing logics are changed a bit. What happens, is that all squads in the squad pool are broken, and players put into the no-squad pool,
- before balancing starts.<br />
- <br />
- Note that for live-balancing, players are not actually moved out of the squad. (it would kill all players if you do that).
- They are just treated as if they were not in a squad. Also, If <b>keep_squads</b> is enabled, clan-squads will not be broken.
- </blockquote>
- <h2> Keeping Clans On Same Team </h2>
- <blockquote>
- During end-of round re-balancing, if <b>keep_clans</b> is enabled, players with the same clan tag are be removed from their current squad,
- and put into exclusive squads. These special clan squads are given priority over non-clan squads, so that clan-squads end up in the same team.
- Note that when <b>keep_clans</b> is enabled, teams may end up unbalanced in number, so the live-balancing logic may still need to be applied.<br />
- <br />
- During live-balancing, if <b>keep_clans</b> is enabled, players with clan tags are given priority, as long as there is at least two members of
- the same clan in the server. When picking players to move to the other team, if a player has a clan tag, the player will be automatically skipped,
- if the majority of the clan is in the same team (otherwise the player is moved to the other team to join his clan buddies).
- If at the end of live-balancing phase, teams are still unbalanced, then <b>keep_clans</b> is disabled temporarily, and the live-balancer logic is applied again.
- </blockquote>
- <h2>Whitelist</h2>
- <blockquote>
- Whitelist is a list of players which have even higher priority than clan members. During live balancing, if a player is in the whitelist, he is skipped.
- If at the end of the live balancing, the teams are still unbalanced, then the whitelist is ignored, and the live balancing logic is re-applied.
- </blockquote>
- <h2>Settings</h2>
- <ol>
- <li><blockquote><b>balance_threshold</b><br />
- <i>(integer > 0)</i> - maximum difference in team sizes before teams are considered unbalanced <br />
- Technically, no team will ever be bigger by more than the <b>balance_threshold</b>
- </blockquote>
- </li>
- <li><blockquote><b>live_interval_time</b><br />
- <i>(integer > 0)</i> - interval number of seconds at which team balance is checked during game <br />
- </blockquote>
- </li>
- <li><blockquote><b>round_interval</b><br />
- <i>(integer > 0)</i> - interval number number of rounds at which the round balancer is applied <br />
- For example, if map Atacama has 6 rounds, and the value of <b>round_interval</b> is 2, then the round
- balancer is run at the end of rounds 2, 4, and 6.
- </blockquote>
- </li>
- <li><blockquote><strong>keep_squads</strong><br />
- <i>true</i> - squads are preseved when balancing <br />
- <i>false</i> - squads are intentionally broken up before balancing starts
- </blockquote>
- This setting only applies tot he round-end balancer.
- </li>
- <li><blockquote><strong>keep_clans</strong><br />
- <i>true</i> - players with same clan tags are kept on the same team <br />
- <i>false</i> - clan tags are ignored during balancing
- </blockquote>
- </li>
- <li><blockquote><strong>warn_say</strong><br />
- <i>true</i> - send auto-balancer warning in chat <br />
- <i>false</i> - do not say the auto-balancer warning in chat
- </blockquote>
- </li>
- <li><blockquote><strong>balance_round</strong><br />
- <i>true</i> - enables the end of round balancer<br />
- <i>false</i> - disabled the end of round balancer
- </blockquote>
- </li>
- <li><blockquote><strong>balance_live</strong><br />
- <i>true</i> - enables the live balancer<br />
- <i>false</i> - disables the live balancer
- </blockquote>
- </li>
- <li><blockquote><strong>admin_list</strong><br />
- <i>(string)</i> - list of players who are allow to execute admin commands
- </blockquote>
- </li>
- <li><blockquote><strong>round_sort</strong><br />
- <i>(string)</i> - method used for sorting players and squads during end of round balancing
- </blockquote>
- </li>
- <li><blockquote><strong>live_sort</strong><br />
- <i>(string)</i> - method used for sorting players and squads during live balancing
- </blockquote>
- </li>
- <li><blockquote><strong>advanced_mode</strong><br />
- <i>true</i> - enables the advanced settings mode which displays extra undocumented plugin settings<br />
- <i>false</i> - disables the advanced settings mode
- </blockquote>
- </li>
- </ol>
- <h2> Advanced Settings</h2>
- There are settings that are shown by enabling <b>advanced_mode</b>
- <ol>
- <li><blockquote><b>warn_msg_interval_time</b><br />
- <i>(integer > 0)</i> - this is the interval time in seconds at which the balance warning will be sent <br />
- The value must be less than or equal to the <b>warn_msg_total_time</b>
- </blockquote>
- </li>
- <li><blockquote><b>warn_msg_total_time</b><br />
- <i>(integer > 0)</i> - this is the total amount of time in seconds, that a warning message will be sent <br />
- Basically this is a grace period for players to fix themselves the teams before the live balancer kicks in.
- </blockquote>
- </li>
- <li><blockquote><b>warn_msg_display_time</b><br />
- <i>(integer >= 0)</i> - this is the amount of time in seconds for how long the balancing warning is displayed <br />
- The value must be less than or equal to the <b>warn_msg_total_time</b>
- </blockquote>
- </li>
- <li><blockquote><b>warn_msg_countdown_time</b><br />
- <i>(integer >= 0)</i> - this is the amount of time in seconds for the countdown at the end of the warning period.
- The value must be less than or equal to the <b>warn_msg_total_time</b>
- </blockquote>
- </li>
- <li><blockquote><strong>auto_start</strong><br />
- <i>true</i> - enables auto start for live balancing checks<br />
- <i>false</i> - disables the live balancer auto start, you will need to issue the <i>!start check</i> command
- </blockquote>
- </li>
- <li><blockquote><b>warn_msg_countdown_time</b><br />
- <i>(integer >= 0 && <= 6)</i> - this variable is for debug mode. When the value is zero, no debug information is printed <br />
- on the plugin console. For medium debugging information you can set it to 3. The bigger the value, the more debugging details are printed. <br />
- </blockquote>
- </li>
- </ol>
- <h2>Public In-Game Commands</h2>
- <p>
- In-game commands are messages typed into the game chat box, which have special meaning to the plugin.
- Commands must start with one of the following characters: !,@, or /. This plugin interprets the following commands:
- </p>
- <ul>
- <li><blockquote><strong>!move</strong><br />
- This command can be used by regular players to move themselves to the opposite team as long as teams are balanced.
- </blockquote>
- </li>
- </ul>
- <h2> Admin In-Game Commands</h2>
- <p>
- These are the commands that only soldiers in the ""admin_list"" are allowed to execute. Reply messages generated by admin commands
- are sent only to the admin who executed the command.
- </p>
- <ul>
- <li><blockquote><strong>!start check</strong><br />
- This command puts the live balancer in started state, so that it periodically (every <b>live_interval_time</b> seconds) checks the teams for balance. <br />
- When this command is run <b>balance_live</b>is implicitly set to true.
- </blockquote>
- </li>
- <li><blockquote><strong>!stop check</strong><br />
- This command puts the live balancer in stopped state.
- When this command is run <b>balance_live</b> is implicitly set to false.
- </blockquote>
- </li>
- <li><blockquote><strong>!show round stats [player-name]</strong><br />
- This command is used for showing the player statistics for the current round.
- The name of the player is optional. If you do not provide a player name, it will print statistics for all players.
- </blockquote>
- </li>
- <li><blockquote><strong>!balance live</strong><br />
- This command forces the live balancing logic to be applied whithout any warning period or countdown.
- </blockquote>
- </li>
- <li><blockquote><strong>!balance round</strong><br />
- This command forces the round balancing logic to be applied whithout any warning period or countdown.
- </blockquote>
- </li>
- <li><blockquote>
- <strong>1. !set {variable} {to|=} {value}</strong><br />
- <strong>2. !set {variable} {value}</strong><br />
- <strong>3. !set {variable}</strong><br />
- This command is used for setting the value of this plugin's variables.<br />
- For the 2nd invocation syntax you cannot use ""="" or ""to"" as the variable value. <br />
- For the 3rd invocation syntax the value is assumed to be ""true"".
- </blockquote>
- </li>
- <li><blockquote>
- <strong>!get {variable} </strong><br />
- This command prints the value of the specified variable.
- </blockquote>
- </li>
- </ul>
- ";
- }
- public void OnPluginLoaded(string strHostName, string strPort, string strPRoConVersion)
- {
- ConsoleWrite("plugin loaded");
- this.RegisterEvents("OnPlayerJoin",
- "OnPlayerLeft",
- "OnGlobalChat",
- "OnTeamChat",
- "OnSquadChat",
- "OnLevelStarted",
- "OnPunkbusterplayerStatsCmd",
- "OnServerInfo",
- "OnPlayerTeamChange",
- "OnPlayerSquadChange",
- "OnplayersStatsCmd",
- "OnRoundOver");
- }
- public void OnPluginEnable()
- {
- ConsoleWrite("^b^2Enabled!^0");
- plugin_enabled = true;
- unloadSettings();
- loadSettings();
- addPluginCallTask("InsaneBalancer", "ticks", 0, 1, -1);
- initializeBalancer();
- }
- public void addPluginCallTask(string task, string method, int delay, int interval, int repeat)
- {
- this.ExecuteCommand("procon.protected.tasks.add", task, delay.ToString(), interval.ToString(), repeat.ToString(), "procon.protected.plugins.call", "InsaneBalancer", method);
- }
- public void removeTask(string task)
- {
- this.ExecuteCommand("procon.protected.tasks.remove", task);
- }
- public int getElapsedTime(DateTime now, PluginState state)
- {
- DateTime startTime = getStartTime(state);
- int elapsed = (int)now.Subtract(startTime).TotalSeconds;
- return elapsed;
- }
- public DateTime getStartTime(PluginState state)
- {
- if (state.Equals(PluginState.wait))
- return startWaitTime;
- else if (state.Equals(PluginState.warn))
- return startWarnTime;
- else if (state.Equals(PluginState.check))
- return startCheckTime;
- else if (state.Equals(PluginState.balance))
- return startBalanceTime;
- else if (state.Equals(PluginState.stop))
- return startStopTime;
- else
- ConsoleWrite("^1cannot find start time for ^b" + state.ToString() + "^n^0");
- return utc;
- }
- public void setStartTime(PluginState state, DateTime now)
- {
- if (state.Equals(PluginState.wait))
- startWaitTime = now;
- else if (state.Equals(PluginState.warn))
- startWarnTime = now;
- else if (state.Equals(PluginState.check))
- startCheckTime = now;
- else if (state.Equals(PluginState.balance))
- startBalanceTime = now;
- else if (state.Equals(PluginState.stop))
- startStopTime = now;
- else
- ConsoleWrite("^1cannot set start time for ^b" + state.ToString() + "^n^0");
- }
- public int getMaxTime(PluginState state)
- {
- if (state.Equals(PluginState.wait))
- return getIntegerVarValue("live_interval_time");
- else if (state.Equals(PluginState.warn))
- return getIntegerVarValue("warn_msg_total_time");
- /*else
- DebugWrite("^1Getting max time for ^b" + state.ToString() + "^n state is not valid", 6);
- */
- return getElapsedTime(utc, PluginState.check);
- }
- public int getRemainingTime(DateTime now, PluginState state)
- {
- int max_time = getMaxTime(state);
- int elapsed = getElapsedTime(now, state);
- int remain = max_time - elapsed;
- return remain;
- }
- public void ExecCommand(params string[] args)
- {
- List<string> list = new List<string>();
- list.Add("procon.protected.send");
- list.AddRange(args);
- this.ExecuteCommand(list.ToArray());
- }
- public void getPlayerList()
- {
- ExecCommand("admin.listPlayers", "all");
- ExecCommand("punkBuster.pb_sv_command", "pb_sv_plist");
- }
- public void getServerInfo()
- {
- ExecCommand("serverInfo");
- }
- public void ticks()
- {
- utc = utc.AddSeconds(1);
- timer(utc);
- }
- public bool isPluginState(PluginState state)
- {
- return pluginState.Equals(state);
- }
- public bool isPluginWaiting()
- {
- return isPluginState(PluginState.wait);
- }
- public bool isPluginBalancing()
- {
- return isPluginState(PluginState.balance);
- }
- public bool isPluginWarning()
- {
- return isPluginState(PluginState.warn);
- }
- public bool isPluginStopped()
- {
- return isPluginState(PluginState.stop);
- }
- public bool isPluginChecking()
- {
- return isPluginState(PluginState.check);
- }
- public void startCheckState(DateTime now)
- {
- DebugWrite("^1ENTER: startCheckState", 10);
- if (check_state_phase == 0)
- {
- pluginState = PluginState.check;
- setStartTime(pluginState, now.AddSeconds(1));
- DebugWrite("^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
- DebugWrite("^b" + PluginState.check.ToString() + "^n state ^bphase-" + check_state_phase + "^n started " + getStartTime(pluginState).ToString() + "^0", 2);
- DebugWrite("Requesting player list", 2);
- check_state_phase = 1;
- getPlayerList();
- DebugWrite("^1EXIT: startCheckState", 10);
- return;
- }
- else if (check_state_phase == 1)
- {
- DebugWrite("^b" + PluginState.check.ToString() + "^n state ^bphase-" + check_state_phase + "^n started " + now.ToString() + "^0", 2);
- if (teamsUnbalanced())
- {
- DebugWrite("Teams are unbalanced, going to ^b" + PluginState.warn.ToString() + "^n state", 2);
- startWarnState(now);
- }
- else
- {
- DebugWrite("Teams are balanced, going to ^b" + PluginState.wait.ToString() + "^n state", 2);
- restartWaitState(now);
- }
- check_state_phase = 0;
- DebugWrite("^1EXIT: startCheckState", 10);
- return;
- }
- }
- public void timer(DateTime now)
- {
- if (!getBooleanVarValue("balance_live"))
- return;
- int remain_time = getRemainingTime(now, pluginState);
- int elapsed_time = getElapsedTime(now, pluginState);
- if (isPluginChecking() || isPluginStopped() || isPluginBalancing())
- DebugWrite(pluginState.ToString() + "(" + elapsed_time + ")", 4);
- else
- DebugWrite(pluginState.ToString() + "(" + remain_time + ")", 4);
- if (isPluginStopped())
- {
- if (getBooleanVarValue("auto_start"))
- {
- DebugWrite("^bauto_start^n is enabled, going to ^b" + PluginState.wait.ToString() + "^n state^0", 2);
- startWaitSate(now);
- }
- }
- else if (isPluginWaiting())
- {
- if (remain_time <= 0)
- startCheckState(now);
- }
- else if (isPluginWarning())
- {
- int countdown_time = getIntegerVarValue("warn_msg_countdown_time");
- int display_time = getIntegerVarValue("warn_msg_display_time");
- int interval_time = getIntegerVarValue("warn_msg_interval_time");
- if (teamsBalanced())
- {
- DebugWrite("Teams are balanced, halting ^b" + PluginState.warn.ToString() + "^n state, and restarting ^b" + PluginState.wait.ToString() + "^n state^0", 4);
- restartWaitState(now);
- return;
- }
- else if (remain_time <= 0)
- {
- balanceLive(now);
- restartWaitState(now);
- return;
- }
- else if (remain_time >= 1 && remain_time <= countdown_time)
- {
- warnCountdown();
- return;
- }
- else if (isTimeLeft(remain_time, display_time, interval_time, countdown_time))
- {
- warnAnnounce(display_time);
- return;
- }
- }
- }
- private bool teamsUnbalanced()
- {
- return !teamsBalanced();
- }
- private bool teamsBalanced()
- {
- DebugWrite("^1ENTER: teamsBalanced", 10);
- //return false;
- /* initialize hash with player count for 16 teams*/
- Dictionary<int, int> player_count = getPlayerCount();
- int total = player_count[1] + player_count[2];
- int difference = Math.Abs(player_count[1] - player_count[2]);
- int balance_threshold = getIntegerVarValue("balance_threshold");
- /* assumer the minimum threshold if user total players is less than user set threshold */
- int threshold = (total <= balance_threshold) ? 1 : balance_threshold;
- DebugWrite("^1EXIT: teamsBalanced", 10);
- if (difference <= balance_threshold)
- return true;
- return false;
- }
- private int sumSquadPlayers(List<PlayerSquad> squads)
- {
- int sum = 0;
- foreach (PlayerSquad squad in squads)
- sum += squad.getCount();
- return sum;
- }
- private void listPlayers()
- {
- List<PlayerProfile> players_list = getPlayersProfile("");
- int count = 1;
- DebugWrite("== Listing Players == ", 3);
- foreach (PlayerProfile player in players_list)
- {
- DebugWrite(" "+count+". ^b"+player.name+"^n STeam("+player.getSavedTeamId()+").SSquad("+SQN(player.getSavedSquadId())+") ... Team("+player.getTeamId()+").Squad("+SQN(player.getSquadId())+")", 3);
- count++;
- }
- }
- private void balanceRound(int winTeamId)
- {
- if (!getBooleanVarValue("balance_round"))
- {
- ConsoleWrite("Round balancer disbaled, not running");
- return;
- }
- virtual_mode = true;
- DateTime now = utc;
- pluginState = PluginState.balance;
- setStartTime(pluginState, now.AddSeconds(1));
- DebugWrite("^b" + pluginState + "_clans^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
- int neutralTeamId = 0;
- int loseTeamId = getOpposingTeamId(winTeamId);
- DebugWrite("Building no-squad pool from ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- List<PlayerProfile> win_nosquad_pool = getNoSquadPlayers(winTeamId);
- List<PlayerProfile> lose_nosquad_pool = getNoSquadPlayers(loseTeamId);
- List<PlayerProfile> nosquad_pool = new List<PlayerProfile>();
- nosquad_pool.AddRange(win_nosquad_pool);
- nosquad_pool.AddRange(lose_nosquad_pool);
- DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 2);
- DebugWrite("Building squad pool from ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- List<PlayerSquad> win_squad_pool = getNonEmptySquads(winTeamId);
- List<PlayerSquad> lose_squad_pool = getNonEmptySquads(loseTeamId);
- List<PlayerSquad> squad_pool = new List<PlayerSquad>();
- squad_pool.AddRange(win_squad_pool);
- squad_pool.AddRange(lose_squad_pool);
- DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 3);
- if (!getBooleanVarValue("keep_squads"))
- {
- foreach (PlayerSquad squad in squad_pool)
- {
- DebugWrite("Breaking up ^bTeam(" + squad.getTeamId() + ").Squad(" + SQN(squad.getSquadId()) + ")^n^0", 3);
- while (squad.getCount() > 0)
- {
- PlayerProfile player = squad.getRandomPlayer();
- squad.dropPlayer(player);
- movePlayer(player, player.getTeamId(), 0, true);
- nosquad_pool.Add(player);
- }
- }
- }
- DebugWrite("Moving no-squad pool to neutral ^bTeam(" + neutralTeamId + ")^n^0", 3);
- foreach (PlayerProfile player in nosquad_pool)
- movePlayer(player, neutralTeamId, 0, true);
- DebugWrite("Moving squal pool to neutral ^bTeam(" + neutralTeamId + ")^n^0", 3);
- foreach (PlayerSquad squad in squad_pool)
- moveSquad(squad, neutralTeamId);
- /* re-build the pools */
- DebugWrite("Rebuilding no-squad pool from ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- nosquad_pool = getNoSquadPlayers(neutralTeamId);
- DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 3);
- DebugWrite("Rebuilding squad pool from ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- squad_pool = getNonEmptySquads(neutralTeamId);
- DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 2);
- if (getBooleanVarValue("keep_clans"))
- {
- DebugWrite("Keeping clans in same team", 3);
- /* collect statistics about clans */
- DebugWrite("Collecting clan statistics", 3);
- Dictionary<string, int> clan_stats = new Dictionary<string, int>();
- getClanStats(nosquad_pool, clan_stats);
- foreach (PlayerSquad squad in squad_pool)
- getClanStats(squad.getMembers(), clan_stats);
- List<string> clanlist = new List<string>(clan_stats.Keys);
- DebugWrite("^b" + clanlist.Count + "^n clans in server: [^b" + String.Join("^n], [^b", clanlist.ToArray()) + "^n]", 3);
- int count = 1;
- foreach (KeyValuePair<string, int> pair in clan_stats)
- {
- DebugWrite(" "+count+". clan [^b" + pair.Key + "^n] has ^b" + pair.Value + "^n member/s", 3);
- count++;
- }
- /* for clans with more than two players in game, create a new squad for them, and remove them from their current squads */
- Dictionary<string, List<PlayerSquad>> clan_squads = new Dictionary<string, List<PlayerSquad>>();
- DebugWrite("Creating clan squads from ^bno-squad^n pool", 3);
- getClanSquads(nosquad_pool, clan_squads, clan_stats);
- DebugWrite("Creating clan squads from ^bsquad-spool^n pool", 3);
- foreach (PlayerSquad squad in squad_pool)
- getClanSquads(squad.getMembers(), clan_squads, clan_stats);
- /* remove the empty squads */
- DebugWrite("Removing empty squads", 3);
- squad_pool.RemoveAll(delegate(PlayerSquad squad) { return squad.getCount() == 0; });
- /* add clan squads to the squad pool */
- DebugWrite("Adding clan squads to the squad pool", 3);
- foreach (KeyValuePair<string, List<PlayerSquad>> pair in clan_squads)
- foreach (PlayerSquad squad in pair.Value)
- squad_pool.Add(squad);
- }
- /* sort the no-squad pool */
- DebugWrite("Sorting the no-squad pool by ^b" + getStringVarValue("round_sort") + "^n^0", 3);
- nosquad_pool.Sort(new Comparison<PlayerProfile>(getPlayerSort("round_sort")));
- for (int i = 0; i < nosquad_pool.Count; i++)
- {
- DebugWrite(" " + i + ". " + nosquad_pool[i].name + "(" + getSortFieldValueStr(nosquad_pool[i], "round_sort") + ")", 3);
- }
- /* sort the squad pool */
- DebugWrite("Sorting the squad pool by ^b" + getStringVarValue("round_sort") + "^n^0", 3);
- squad_pool.Sort(new Comparison<PlayerSquad>(getSquadSort("round_sort")));
- for (int i = 0; i < squad_pool.Count; i++)
- {
- DebugWrite(" " + i + ". " + squad_pool[i].ToString() + "(" + getSortFieldValueStr(squad_pool[i], "round_sort") + ")", 3);
- }
- int[] teamCount = new int[3];
- teamCount[neutralTeamId] = sumSquadPlayers(squad_pool) + nosquad_pool.Count;
- teamCount[winTeamId] = 0;
- teamCount[loseTeamId] = 0;
- Dictionary<string, int> clanTeam = new Dictionary<string, int>();
- /* assume the smaller team */
- int smallTeamId = loseTeamId;
- DebugWrite("Moving ^b" + squad_pool.Count + "^n squads from neutral ^bTeam(" + neutralTeamId + ")^n into ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- while (squad_pool.Count > 0)
- {
- /* get the top squad */
- PlayerSquad squad = squad_pool[0];
- squad_pool.RemoveAt(0);
- if (getBooleanVarValue("keep_clans") && squad.getSquadId() > 8)
- {
- string tag = squad.getClanTag();
- if (clanTeam.ContainsKey(tag))
- smallTeamId = clanTeam[tag];
- else
- clanTeam.Add(tag, smallTeamId);
- }
- int squad_sz = squad.getCount();
- /* move top squad to the smaller team */
- DebugWrite("Moving entire " + squad.ToString() + " to ^bTeam(" + smallTeamId + ")^n^0", 3);
- moveSquad(squad, smallTeamId);
- /* update the team counts */
- teamCount[smallTeamId] += squad_sz;
- teamCount[neutralTeamId] -= squad_sz;
- /* determine the smaller team */
- smallTeamId = getSmallTeamId(winTeamId, teamCount[winTeamId], loseTeamId, teamCount[loseTeamId]);
- }
- DebugWrite("^bTeam(" + winTeamId + ")^n has now ^b" + teamCount[winTeamId] + "^n player/s", 3);
- DebugWrite("^bTeam(" + loseTeamId + ")^n has now ^b" + teamCount[loseTeamId] + "^n player/s", 3);
- DebugWrite("Moving ^b" + nosquad_pool.Count + "^n player/s from neutral ^bTeam(" + neutralTeamId + ")^n into ^bTeam(" + winTeamId + ")^n and ^bTeam(" + loseTeamId + ")^n^0", 3);
- while (nosquad_pool.Count > 0)
- {
- /* get the top player */
- PlayerProfile player = nosquad_pool[0];
- nosquad_pool.RemoveAt(0);
- /* move the top player to the smaller team */
- DebugWrite("Moving ^b" + player.ToString() + "^n to ^bTeam(^n" + smallTeamId + ")^n^0", 3);
- movePlayer(player, smallTeamId, 0, true);
- /* update the team counts */
- teamCount[neutralTeamId] -= 1;
- teamCount[smallTeamId] += 1;
- /* determine the smaller team */
- smallTeamId = getSmallTeamId(winTeamId, teamCount[winTeamId], loseTeamId, teamCount[loseTeamId]);
- }
- DebugWrite("^bTeam(" + winTeamId + ")^n has now ^b" + teamCount[winTeamId] + "^n player/s", 3);
- DebugWrite("^bTeam(" + loseTeamId + ")^n has now ^b" + teamCount[loseTeamId] + "^n player/s", 3);
- if (teamsUnbalanced())
- {
- DebugWrite("Teams are still unbalanced, applying the live balancing logic", 3);
- balanceLive(utc);
- }
- else
- DebugWrite("Teams should now be balanced!", 3);
- virtual_mode = false;
- fixTeamSquads(winTeamId);
- }
- private void balanceLive(DateTime now)
- {
- balanceTeams(now);
- if (balanceTeams(now) > 0 && getBooleanVarValue("keep_clans"))
- {
- DebugWrite("Re-running live balancer, with ^bkeep_clans^n disabled", 3);
- setBooleanVarValue("keep_clans", false);
- balanceTeams(now);
- setBooleanVarValue("keep_clans", true);
- }
- }
- private void fixTeamSquads(int winTeamId)
- {
- List<PlayerProfile> players_list = getPlayersProfile("");
- /* remove the players that are not moving at all */
- players_list.RemoveAll(delegate(PlayerProfile p) { return p.getTargetTeamId() == p.getSavedTeamId() && p.getTargetSquadId() == p.getSavedSquadId(); });
- /* save everyone's target team and squad */
- players_list.ForEach(delegate(PlayerProfile p) { p.saveTargetTeamSquad(); });
- /* divide every one into teams */
- List<PlayerProfile>[] steams = new List<PlayerProfile>[3];
- int loseTeamId = getOpposingTeamId(winTeamId);
- int neutralTeamId = 0;
- steams[neutralTeamId] = new List<PlayerProfile>();
- steams[winTeamId] = new List<PlayerProfile>();
- steams[loseTeamId] = new List<PlayerProfile>();
- foreach (PlayerProfile p in players_list)
- steams[p.getSavedTeamId()].Add(p);
- /* put some players into the neutral team */
- int difference = Math.Abs(steams[winTeamId].Count - steams[loseTeamId].Count);
- difference = (difference == 0) ? 1 : difference;
- List<PlayerProfile> winNeutral = removePlayers(steams[winTeamId], difference);
- List<PlayerProfile> loseNeutral = removePlayers(steams[loseTeamId], difference);
- List<PlayerProfile> neutral = new List<PlayerProfile>();
- neutral.AddRange(winNeutral);
- neutral.AddRange(loseNeutral);
- DebugWrite("Moving ^b" + neutral.Count + "^n offset player/s to neutral team", 3);
- neutral.ForEach(delegate(PlayerProfile p) { movePlayer(p, 0, 0, true); });
- DebugWrite("Moving ^b" + (steams[winTeamId].Count + steams[loseTeamId].Count) + "^n player/s to no-squad", 3);
- for(int i = 1; i <= 2; i++)
- steams[i].ForEach(delegate(PlayerProfile p) { if (p.getSavedSquadId() != 0) movePlayer(p, p.getSavedTeamId(), 0, true); });
- /* round robin start swapping players */
- DebugWrite("Swapping ^b" + (steams[winTeamId].Count + steams[loseTeamId].Count) + "^n player/s to target teams", 3);
- while (steams[winTeamId].Count > 0 && steams[loseTeamId].Count > 0)
- {
- int bigTeamId = getBigTeamId(winTeamId, steams[winTeamId].Count , loseTeamId, steams[loseTeamId].Count);
- PlayerProfile p = steams[bigTeamId][0];
- steams[bigTeamId].Remove(p);
- movePlayer(p, p.getTargetTeamId(), p.getTargetSquadId(), true);
- }
- /* put back the players who are in the offset */
- DebugWrite("Moving ^b" + neutral.Count + "^n neutral player/s to target teams", 3);
- neutral.ForEach(delegate(PlayerProfile p) { movePlayer(p, p.getTargetTeamId(), p.getTargetSquadId(), true); });
- }
- private void getClanSquads(List<PlayerProfile> members, Dictionary<string, List<PlayerSquad>> clan_squads, Dictionary<string, int> clan_stats)
- {
- int neutralTeamId = 0;
- int noSquadId = 0;
- int max_squad_size = 4;
- members.RemoveAll(delegate(PlayerProfile player)
- {
- /* if player is not in a clan, ignore it*/
- if (!player.isInClan())
- return false;
- string tag = player.getClanTag();
- /* if less than two players for the clan, ignore it */
- if (clan_stats[tag] < 2)
- return false;
- if (!clan_squads.ContainsKey(tag))
- clan_squads[tag] = new List<PlayerSquad>();
- List<PlayerSquad> squads = clan_squads[tag];
- /* if there is no squads, of they are all full, add a new at the end */
- if (squads.Count == 0 || squads[squads.Count - 1].getCount() == max_squad_size)
- squads.Add(new PlayerSquad(neutralTeamId, getNextFreeClanSquadId(clan_squads)));
- /* add player to the last squad in the clan */
- movePlayer(player, neutralTeamId, squads[squads.Count - 1].getSquadId(), true);
- squads[squads.Count - 1].addPlayer(player);
- return true;
- });
- }
- private int getNextFreeClanSquadId(Dictionary<string, List<PlayerSquad>> clan_squads)
- {
- int count = 0;
- foreach (KeyValuePair<string, List<PlayerSquad>> pair in clan_squads)
- foreach (PlayerSquad squad in pair.Value)
- count++;
- return 9 + count;
- }
- private void getClanStats(List<PlayerProfile> members, Dictionary<string, int> stats)
- {
- foreach (PlayerProfile player in members)
- {
- if (!player.isInClan())
- continue;
- string tag = player.getClanTag();
- if (!stats.ContainsKey(tag))
- stats[tag] = 0;
- stats[tag]++;
- }
- }
- private void getClanStatsByTeam(List<PlayerProfile> members, Dictionary<string, int>[] stats)
- {
- for(int i = 0; i < members.Count; i++)
- {
- PlayerProfile player = members[i];
- if (!player.isInClan())
- continue;
- string tag = player.getClanTag();
- int teamId = player.getTeamId();
- if (!stats[teamId].ContainsKey(tag))
- {
- stats[teamId].Add(tag, 0);
- stats[getOpposingTeamId(teamId)].Add(tag, 0);
- }
- stats[teamId][tag]++;
- }
- }
- private int getSmallTeamId(int team1Id, int team1Count, int team2Id, int team2Count)
- {
- return (team1Count < team2Count) ? team1Id : team2Id;
- }
- private int getBigTeamId(int team1Id, int team1Count, int team2Id, int team2Count)
- {
- return (team1Count > team2Count) ? team1Id : team2Id;
- }
- private int getOpposingTeamId(int teamId)
- {
- return (teamId == 0) ? teamId : (teamId == 1) ? 2 : 1;
- }
- private int balanceTeams(DateTime now)
- {
- pluginState = PluginState.balance;
- setStartTime(pluginState, now.AddSeconds(1));
- DebugWrite("^b" + pluginState + "_live^n state started " + getStartTime(pluginState).ToString() + "^n^0", 1);
- bool keep_clans = getBooleanVarValue("keep_clans");
- Dictionary<int, int> player_count = getPlayerCount();
- if (player_count[1] == player_count[2])
- return 0;
- int neutral_team = 0;
- int bigger_team = (player_count[1] > player_count[2]) ? 1 : 2;
- int smaller_team = (player_count[1] > player_count[2]) ? 2 : 1;
- int total = player_count[1] + player_count[2];
- int difference = Math.Abs(player_count[1] - player_count[2]);
- int needed = difference / 2;
- DebugWrite("Total of ^b" + total + "^n player/s in server^0", 3);
- for (int i = 1; i < 3; i++)
- {
- DebugWrite("^bTeam(" + i + ")^n has ^b" + player_count[i] + "^n player/s^0", 3);
- }
- DebugWrite("Teams differ by ^b" + difference + "^n player/s, ^b" + needed + "^n player/s are needed on ^bTeam(" + smaller_team + ")^n^0", 3);
- DebugWrite("Building no-squad pool from ^bTeam(" + bigger_team + ")^n^0", 3);
- List<PlayerProfile> nosquad_pool = getNoSquadPlayers(bigger_team);
- DebugWrite("No-squad pool has ^b" + nosquad_pool.Count + "^n player/s^0", 3);
- DebugWrite("Building squad pool from ^bTeam(" + bigger_team + ")^n^0", 3);
- List<PlayerSquad> squad_pool = getNonEmptySquads(bigger_team);
- DebugWrite("Squad pool has ^b" + squad_pool.Count + "^n squads^0", 3);
- Dictionary<string, int>[] clan_stats = new Dictionary<string, int>[3];
- clan_stats[smaller_team] = new Dictionary<string, int>();
- clan_stats[bigger_team] = new Dictionary<string, int>();
- clan_stats[neutral_team] = new Dictionary<string, int>();
- if (keep_clans)
- {
- DebugWrite("Keeping clans in same team", 3);
- List<PlayerProfile> players_list = getPlayersProfile("");
- /* collect statistics about clans */
- DebugWrite("Collecting clan statistics", 3);
- getClanStatsByTeam(players_list, clan_stats);
- List<string> clanlist = new List<string>();
- clanlist.AddRange(clan_stats[1].Keys);
- DebugWrite("^b" + clanlist.Count + "^n clans in server: [^b" + String.Join("^n], [^b", clanlist.ToArray()) + "^n]", 3);
- }
- /* sort the no-squad pool */
- DebugWrite("Sorting the no-squad pool by ^b" + getStringVarValue("live_sort") + "^n^0", 3);
- nosquad_pool.Sort(new Comparison<PlayerProfile>(getPlayerSort("live_sort")));
- for (int i = 0; i < nosquad_pool.Count; i++)
- {
- DebugWrite(" " + i + ". " + nosquad_pool[i].name + "(" + getSortFieldValueStr(nosquad_pool[i], "live_sort") + ")", 3);
- }
- DebugWrite("Moving ^b" + needed + "^n players from sorted no-squad pool to ^bTeam(" + smaller_team + ")^n^0", 3);
- while (needed > 0 && nosquad_pool.Count > 0)
- {
- PlayerProfile player = nosquad_pool[0];
- nosquad_pool.RemoveAt(0);
- string tag = player.getClanTag();
- /* if keeping clans together, and there are more than two players in the clan in the sever */
- if (keep_clans)
- {
- if (shouldSkipClanPlayer(player, smaller_team, bigger_team, clan_stats))
- continue;
- }
- DebugWrite("Moving ^b" + player.ToString() + "^n to ^bTeam(^n" + smaller_team + ")^n^0", 3);
- movePlayer(player, smaller_team, 0, true);
- needed--;
- }
- /* if teams are balanced, we are done */
- if (needed == 0)
- {
- DebugWrite("Teams should now be balanced!", 3);
- return needed;
- }
- /* teams are not balanced, proceed on squad balancing */
- DebugWrite("Teams are still unbalanced, " + needed + " more player/s needed", 3);
- /* sort the squad pool */
- DebugWrite("Sorting the squad pool by ^b" + getStringVarValue("live_sort") + "^n^0", 3);
- squad_pool.Sort(new Comparison<PlayerSquad>(getSquadSort("live_sort")));
- for (int i = 0; i < squad_pool.Count; i++)
- {
- DebugWrite(" " + i + ". " + squad_pool[i].ToString() + "(" + getSortFieldValueStr(squad_pool[i], "live_sort") + ")", 3);
- }
- DebugWrite("Moving squads from sorted squad pool to ^bTeam(" + smaller_team + ")^n^0", 3);
- while (needed > 0 && squad_pool.Count > 0)
- {
- PlayerSquad squad = squad_pool[0];
- squad_pool.RemoveAt(0);
- int squad_sz = squad.getCount();
- string squad_uid = squad.ToString();
- string smaller_team_uid = "^bTeam(" + smaller_team + ")^n";
- DebugWrite("^b" + needed + "^n players are needed on " + smaller_team_uid + "^0", 3);
- DebugWrite(squad_uid + " has ^b" + squad_sz + "^n player/s^0", 2);
- if (needed >= squad_sz)
- {
- if (keep_clans)
- {
- if (shouldSkipClanSquad(squad, smaller_team, bigger_team, clan_stats))
- continue;
- }
- /* we can move the entrie squad */
- DebugWrite("Moving entire " + squad_uid + " to " + smaller_team_uid + "^0", 3);
- moveSquad(squad, smaller_team);
- needed -= squad_sz;
- }
- else
- {
- /* we have to break up a squad */
- PlayerSquad temp_squad = new PlayerSquad(squad.getTeamId(), squad.getSquadId());
- DebugWrite("Breaking up " + squad_uid + " to get ^b" + needed + "^n player/s^0", 3);
- /* get as many players as needed */
- while (needed > 0 && squad.getCount() > 0)
- {
- PlayerProfile player = squad.getRandomPlayer();
- squad.dropPlayer(player);
- if (shouldSkipClanPlayer(player, smaller_team, bigger_team, clan_stats))
- continue;
- temp_squad.addPlayer(player);
- DebugWrite("Player " + player.name + " selected to move to " + smaller_team_uid + "^0", 3);
- needed--;
- }
- /* move the temporary squad */
- moveSquad(temp_squad, smaller_team);
- }
- }
- if (needed == 0)
- DebugWrite("Teams should now be balanced!", 3);
- else
- DebugWrite("Teams are still ubalanced!", 3);
- return needed;
- }
- private bool shouldSkipClanSquad(PlayerSquad squad, int smaller_team, int bigger_team, Dictionary<string, int>[] clan_stats)
- {
- int squad_sz = squad.getCount();
- string tag = squad.getMajorityClanTag();
- if (tag.Length > 0 && (clan_stats[bigger_team][tag] + clan_stats[smaller_team][tag]) > 1)
- {
- if (clan_stats[bigger_team][tag] >= clan_stats[smaller_team][tag])
- {
- DebugWrite("Skipping clan-squad " + squad.ToString() + " because majority of clan is in same team", 3);
- return true;
- }
- /* update clan stats */
- clan_stats[bigger_team][tag] -= squad_sz;
- clan_stats[smaller_team][tag] += squad_sz;
- }
- return false;
- }
- private bool shouldSkipClanPlayer(PlayerProfile player, int smaller_team, int bigger_team, Dictionary<string, int>[] clan_stats)
- {
- string tag = player.getClanTag();
- if (player.isInClan() && (clan_stats[bigger_team][tag] + clan_stats[smaller_team][tag]) > 1)
- {
- /* if the majority of the players in the clan are in this team, skip this player */
- if (clan_stats[bigger_team][tag] >= clan_stats[smaller_team][tag])
- {
- DebugWrite("Skipping clan-player ^b" + player.name + "^n because majority of clan is in his team", 3);
- return true;
- }
- /* update the clan stats */
- clan_stats[bigger_team][tag]--;
- clan_stats[smaller_team][tag]++;
- }
- return false;
- }
- private string getSortFieldValueStr(PlayerProfile player, string phase)
- {
- string sort_method = getStringVarValue(phase);
- if (sort_method.CompareTo("kdr_asc_round") == 0 || sort_method.CompareTo("kdr_desc_round") == 0)
- return "kdr_round: " + Math.Round(player.getRoundKdr(), 2);
- else if (sort_method.CompareTo("score_asc_round") == 0 || sort_method.CompareTo("score_desc_round") == 0)
- return "score_round: " + Math.Round(player.getRoundScore(), 2);
- else if (sort_method.CompareTo("spm_asc_round") == 0 || sort_method.CompareTo("spm_desc_round") == 0)
- return "spm_round: " + Math.Round(player.getRoundSpm(), 2);
- else if (sort_method.CompareTo("kpm_asc_round") == 0 || sort_method.CompareTo("kpm_desc_round") == 0)
- return "kpm_round: " + Math.Round(player.getRoundKpm(), 2);
- ConsoleWrite("^1cannot find player sort method for ^b" + sort_method + "^0");
- return "";
- }
- private string getSortFieldValueStr(PlayerSquad squad, string phase)
- {
- string sort_method = getStringVarValue(phase);
- if (sort_method.CompareTo("kdr_asc_round") == 0 || sort_method.CompareTo("kdr_desc_round") == 0)
- return "kdr_round: " + Math.Round(squad.getRoundKdr(), 2);
- else if (sort_method.CompareTo("score_asc_round") == 0 || sort_method.CompareTo("score_desc_round") == 0)
- return "score_round: " + Math.Round(squad.getRoundScore(), 2);
- else if (sort_method.CompareTo("spm_asc_round") == 0 || sort_method.CompareTo("spm_desc_round") == 0)
- return "spm_round: " + Math.Round(squad.getRoundSpm(), 2);
- else if (sort_method.CompareTo("kpm_asc_round") == 0 || sort_method.CompareTo("kpm_desc_round") == 0)
- return "kpm_round: " + Math.Round(squad.getRoundKpm(), 2);
- ConsoleWrite("^1cannot find squad sort method for ^b" + sort_method + "^0");
- return "";
- }
- private void movePlayer(PlayerProfile player, int teamId, int squadId)
- {
- movePlayer(player, teamId, squadId, false);
- }
- private void movePlayer(PlayerProfile player, int teamId, int squadId, bool force)
- {
- if (player == null)
- return;
- if (!force && player.getTeamId() == teamId && player.getSquadId() == squadId)
- {
- ConsoleWrite("^1not moving ^b" + player.name + "^n to same Team(" + teamId + ").Squad(" + SQN(squadId) + ")");
- return;
- }
- /* firt move player to the no-squad, to guarantee a spot */
- if (squadId != 0 && player.getSquadId() != 0)
- {
- if (!virtual_mode)
- ExecCommand("admin.movePlayer", player.name, teamId.ToString(), "0", "true");
- else
- {
- player.saveTeamSquad();
- }
- }
- DebugWrite("moving ^b" + player.name + "^n to Team(" + teamId + ").Squad(" + SQN(squadId) + ")", 4);
- /* in virtual mode, don't actually do the move */
- if (!virtual_mode)
- ExecCommand("admin.movePlayer", player.name, teamId.ToString(), squadId.ToString(), "true");
- /* instead save the original squad, and team id */
- else
- player.saveTeamSquad();
- player.setTeamId(teamId);
- player.setSquadId(squadId);
- }
- /* best effort to move an entire squad into another team withouth breaking up */
- private void moveSquad(PlayerSquad squad, int teamId)
- {
- if (squad == null)
- return;
- /* first move all players to the opposite team without squad (to guarantee a spot)*/
- int squadId = 0;
- List<PlayerProfile> squad_players = squad.getMembers();
- /* find a squad on teamId with enough space */
- List<PlayerSquad> squads = getAllSquads(teamId);
- /* sort the squads in increasing order of player count */
- squads.Sort(new Comparison<PlayerSquad>(squad_count_asc_cmp));
- for (int i = 0; i < squads.Count; i++)
- {
- PlayerSquad sorted_squad = squads[i];
- if (sorted_squad.getSquadId() > 8)
- continue;
- while (sorted_squad.getFreeSlots() > 0 && squad_players.Count > 0)
- {
- PlayerProfile squad_player = squad_players[0];
- squad_players.RemoveAt(0);
- movePlayer(squad_player, teamId, sorted_squad.getSquadId());
- }
- }
- foreach (PlayerProfile squad_player in squad_players)
- ConsoleWrite("^1could not find squad on ^bTeam(" + teamId + ")^n for ^b" + squad_player.name + "^n^0");
- }
- private List<PlayerProfile> removePlayers(List<PlayerProfile> player_list, int max_size)
- {
- if (players == null || players.Count == 0)
- {
- ConsoleWrite("^1cannot make a squad without any players");
- return null;
- }
- List<PlayerProfile> removed = new List<PlayerProfile>();
- while (player_list.Count > 0 && removed.Count <= max_size)
- {
- removed.Add(player_list[0]);
- player_list.RemoveAt(0);
- }
- return removed;
- }
- public Dictionary<int, int> getPlayerCount()
- {
- DebugWrite("^1ENTER: getPlayerCount", 11);
- /* initialize hash with player count for 16 teams*/
- Dictionary<int, int> player_count = new Dictionary<int, int>();
- for (int i = 0; i < 16; i++)
- player_count[i] = 0;
- List<PlayerProfile> player_list = getPlayersProfile("");
- foreach (PlayerProfile player in player_list)
- player_count[player.getTeamId()]++;
- DebugWrite("^1EXIT: getPlayerCount", 11);
- return player_count;
- }
- private List<PlayerProfile> getNoSquadPlayers(int teamId)
- {
- Dictionary<int, PlayerSquad> squads = getSquads(teamId);
- /* return the members of the no-squad */
- return squads[0].getMembers();
- }
- private List<PlayerSquad> getAllSquads(int teamId)
- {
- Dictionary<int, PlayerSquad> squads = getSquads(teamId);
- /* remove the no-squad */
- squads.Remove(0);
- List<PlayerSquad> list = new List<PlayerSquad>();
- foreach (KeyValuePair<int, PlayerSquad> pair in squads)
- list.Add(pair.Value);
- return list;
- }
- private List<PlayerSquad> getNonEmptySquads(int teamId)
- {
- Dictionary<int, PlayerSquad> squads = getSquads(teamId);
- /* remove the no-squad */
- squads.Remove(0);
- /* get only the non-empty squads */
- List<PlayerSquad> list = new List<PlayerSquad>();
- foreach (KeyValuePair<int, PlayerSquad> pair in squads)
- if (pair.Value.getCount() > 0)
- list.Add(pair.Value);
- return list;
- }
- private Dictionary<int, PlayerSquad> getSquads(int teamId)
- {
- List<PlayerProfile> player_list = getPlayersProfile("");
- Dictionary<int, PlayerSquad> squads = new Dictionary<int, PlayerSquad>();
- for (int i = 0; i <= 32; i++)
- squads[i] = new PlayerSquad(teamId, i);
- foreach (PlayerProfile player in player_list)
- {
- if (player.getTeamId() == teamId)
- squads[player.getSquadId()].addPlayer(player);
- }
- return squads;
- }
- private bool isTimeLeft(int remain_time, int msg_display_time, int msg_interval_time, int countdown_time)
- {
- return (remain_time % msg_interval_time) == 0 && (remain_time - msg_display_time) >= countdown_time;
- }
- public bool isServerEmpty()
- {
- return players.Count == 0;
- }
- public void forwardTicks(int count)
- {
- utc = utc.AddSeconds(count);
- }
- public void ConsoleWrite(string msg)
- {
- string prefix = "[^b" + GetPluginName() + "^n] ";
- this.ExecuteCommand("procon.protected.pluginconsole.write", prefix + msg);
- }
- public void DebugWrite(string msg, int level)
- {
- if (getIntegerVarValue("debug_level") >= level)
- ConsoleWrite(msg);
- }
- public void OnPluginDisable()
- {
- ConsoleWrite("^b^1Disabled =(^0");
- plugin_enabled = false;
- unloadSettings();
- removeTask("InsaneBalancer");
- players.Clear();
- }
- public List<CPluginVariable> GetDisplayPluginVariables()
- {
- List<CPluginVariable> lstReturn = new List<CPluginVariable>();
- lstReturn.Add(new CPluginVariable("Settings|Refresh", typeof(string), "| edit this field to refresh settings |"));
- List<string> vars = getPluginVars(true);
- foreach (string var in vars)
- {
- if (var.Equals("live_sort") || var.Equals("round_sort"))
- {
- lstReturn.Add(new CPluginVariable("Settings|" + var, "enum."+var+"("+String.Join("|",getAllowedSorts().ToArray())+")", getPluginVarValue(var)));
- continue;
- }
- lstReturn.Add(new CPluginVariable("Settings|" + var, typeof(string), getPluginVarValue(var)));
- }
- return lstReturn;
- }
- //Lists all of the plugin variables.
- public List<CPluginVariable> GetPluginVariables()
- {
- List<CPluginVariable> lstReturn = new List<CPluginVariable>();
- List<string> vars = getPluginVars();
- foreach (string var in vars)
- lstReturn.Add(new CPluginVariable(var, typeof(string), getPluginVarValue(var)));
- return lstReturn;
- }
- public void SetPluginVariable(string strVariable, string strValue)
- {
- //ConsoleWrite("setting " + strVariable + " to " + strValue);
- if (strVariable.ToLower().Contains("refresh"))
- return;
- setPluginVarValue(strVariable, strValue);
- }
- public void OnPlayerJoin(string strSoldierName)
- {
- //if (!this.players.ContainsKey(strSoldierName))
- // this.players.Add(strSoldierName, new PlayerProfile(this, strSoldierName));
- }
- public void OnPlayerLeft(string strSoldierName)
- {
- PlayerProfile player = getPlayerProfile(strSoldierName);
- if (player != null)
- {
- player.leaveGame();
- this.players.Remove(player.name);
- }
- }
- public void OnGlobalChat(string strSpeaker, string strMessage)
- {
- if (isInGameCommand(strMessage))
- inGameCommand(strSpeaker, strMessage);
- }
- public void OnTeamChat(string strSpeaker, string strMessage, int iTeamID)
- {
- if (isInGameCommand(strMessage))
- inGameCommand(strSpeaker, strMessage);
- }
- public void OnSquadChat(string strSpeaker, string strMessage, int iTeamID, int iSquadID)
- {
- if (isInGameCommand(strMessage))
- inGameCommand(strSpeaker, strMessage);
- }
- private bool isInGameCommand(string str)
- {
- if (Regex.Match(str, @"^\s*[@/!]").Success)
- return true;
- return false;
- }
- public void OnLevelStarted()
- {
- DebugWrite("Level starting!", 3);
- level_started = true;
- }
- public void OnPunkbusterplayerStatsCmd(CPunkbusterInfo cpbiPlayer)
- {
- if (cpbiPlayer != null)
- {
- if (this.players.ContainsKey(cpbiPlayer.SoldierName))
- this.players[cpbiPlayer.SoldierName].pbinfo = cpbiPlayer;
- else
- this.players.Add(cpbiPlayer.SoldierName, new PlayerProfile(this, cpbiPlayer));
- }
- }
- public void OnServerInfo(CServerInfo csiServerInfo)
- {
- this.serverInfo = csiServerInfo;
- }
- public void OnPlayerTeamChange(string strSoldierName, int iTeamID, int iSquadID)
- {
- PlayerProfile player = getPlayerProfile(strSoldierName);
- if (player == null)
- return;
- player.setSquadId(iSquadID);
- player.setTeamId(iTeamID);
- }
- public void OnPlayerSquadChange(string strSoldierName, int iTeamID, int iSquadID)
- {
- PlayerProfile player = getPlayerProfile(strSoldierName);
- if (player == null)
- return;
- player.setSquadId(iSquadID);
- player.setTeamId(iTeamID);
- }
- public void OnplayersStatsCmd(List<CPlayerInfo> lstPlayers, CPlayerSubset cpsSubset)
- {
- /* if (cpsSubset.Subset == CPlayerSubset.PlayerSubsetType.All)
- {
- foreach (CPlayerInfo cpiPlayer in lstPlayers)
- {
- if (this.players.ContainsKey(cpiPlayer.SoldierName))
- this.players[cpiPlayer.SoldierName].updateInfo(cpiPlayer);
- else
- this.players.Add(cpiPlayer.SoldierName, new PlayerProfile(this, cpiPlayer));
- }
- }
- */
- }
- public bool checkRoundBalance()
- {
- int round_interval = this.getIntegerVarValue("round_interval");
- int round_total = serverInfo.TotalRounds;
- int round_current = serverInfo.CurrentRound+1;
- string map = serverInfo.Map.ToLower();
- if (round_interval > round_total)
- {
- ConsoleWrite("^1^bround_interval(" + round_interval + ")^n is greater than total ^brounds(" + round_total + ")^n for ^bmap(" + map + ")^n^0");
- ConsoleWrite("setting ^bround_interval^n to ^b" + round_total + "^n internally for ^bmap(" + map + ")^n^0");
- round_interval = round_total;
- }
- ConsoleWrite("End of round detected");
- ConsoleWrite("Current round is ^b" + round_current + "^n/^b" + round_total + "^n,");
- ConsoleWrite("Round balance interval is ^b" + round_interval + "^n^0");
- if (round_current % round_interval == 0)
- return true;
- return false;
- }
- public static string SQN(int squadNo)
- {
- switch (squadNo)
- {
- case 0:
- return "Neutral";
- case 1:
- return "Alpha";
- case 2:
- return "Bravo";
- case 3:
- return "Charlie";
- case 4:
- return "Delta";
- case 5:
- return "Echo";
- case 6:
- return "Foxtrot";
- case 7:
- return "Golf";
- case 8:
- return "Hotel";
- default:
- if (squadNo > 8 && squadNo <= 32)
- return "Clan-" + squadNo;
- else
- return "Unknown";
- }
- }
- public double getRoundMinutes()
- {
- return utc.Subtract(startRoundTime).TotalMinutes;
- }
- public void OnRoundOver(int iWinningTeamID)
- {
- run_balancer = checkRoundBalance();
- win_teamId = iWinningTeamID;
- lose_teamId = getOpposingTeamId(win_teamId);
- level_started = true;
- }
- public override void OnPlayerSpawned(string soldierName, Inventory spawnedInventory)
- {
- /*
- if (level_started)
- {
- if (run_balancer)
- {
- run_balancer = false;
- int seconds = 10;
- SendGlobalMessage("Team scrambler will start in " + seconds + " seconds");
- Thread.Sleep(10*1000);
- SendGlobalMessage("Scramling teams now.");
- //showPlayerRoundStatsCmd("micovery", null);
- balanceRound(win_teamId);
- restartWaitState(utc);
- resetPlayerStats();
- //showPlayerRoundStatsCmd("micovery", null);
- }
- startRoundTime = utc;
- level_started = false;
- }
- */
- PlayerProfile player = getPlayerProfile(soldierName);
- if (player != null)
- player.spawned();
- }
- private void resetPlayerStats()
- {
- DebugWrite("^1ENTER: resetPlayerStats", 7);
- List<PlayerProfile> players_list = getPlayersProfile("");
- foreach (PlayerProfile player in players_list)
- {
- player.resetStats();
- }
- DebugWrite("^1EXIT: resetPlayerStats", 7);
- }
- private void SendPlayerMessage(string soldierName, string message)
- {
- if (getBooleanVarValue("quiet_mode") && !isAdmin(soldierName))
- return;
- ExecCommand("admin.say", message, "player", soldierName);
- }
- private void SendGlobalMessage(string message)
- {
- if (getBooleanVarValue("quiet_mode"))
- SendConsoleMessage(message);
- else
- ExecCommand("admin.say", message, "all");
- }
- private void SendConsoleMessage(string name, string msg)
- {
- List<string> admin_list = getStringListVarValue("admin_list");
- ConsoleWrite(msg);
- msg = Regex.Replace(msg, @"\^[0-9a-zA-Z]", "");
- if (name != null)
- SendPlayerMessage(name, msg);
- else
- SendConsoleMessage(msg);
- }
- private void SendConsoleMessage(string msg)
- {
- List<string> admin_list = getStringListVarValue("admin_list");
- ConsoleWrite(msg);
- msg = Regex.Replace(msg, @"\^[0-9a-zA-Z]", "");
- foreach (string name in admin_list)
- {
- PlayerProfile pp = this.getPlayerProfile(name);
- if (pp != null)
- {
- SendPlayerMessage(pp.name, msg);
- }
- }
- }
- private void inGameCommand(string sender, string cmd)
- {
- //Player commands
- Match adminMovePlayerMatch = Regex.Match(cmd, @"\s*[!@/]\s*move\s+([^ ]+)", RegexOptions.IgnoreCase);
- Match movePlayerMatch = Regex.Match(cmd, @"\s*[!@/]\s*move", RegexOptions.IgnoreCase);
- Match showPlayerRoundStatsMatch = Regex.Match(cmd, @"\s*[!@/]\s*show\s+round\s+stats\s+([^ ]+)", RegexOptions.IgnoreCase);
- Match showRoundStatsMatch = Regex.Match(cmd, @"\s*[!@/]\s*show\s+round\s+stats", RegexOptions.IgnoreCase);
- Match stopBalancerMatch = Regex.Match(cmd, @"\s*[!@/]\s*stop\s+check", RegexOptions.IgnoreCase);
- Match startBalancerMatch = Regex.Match(cmd, @"\s*[!@/]\s*start\s+check", RegexOptions.IgnoreCase);
- Match balanceLiveMatch = Regex.Match(cmd, @"\s*[!@/]\s*balance\s+live", RegexOptions.IgnoreCase);
- Match balanceRoundMatch = Regex.Match(cmd, @"\s*[!@/]\s*balance\s+round", RegexOptions.IgnoreCase);
- //Setting/Getting variables
- Match setVarValueMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s+(.+)", RegexOptions.IgnoreCase);
- Match setVarValueEqMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s*=\s*(.+)", RegexOptions.IgnoreCase);
- Match setVarValueToMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)\s+to\s+(.+)", RegexOptions.IgnoreCase);
- Match setVarTrueMatch = Regex.Match(cmd, @"\s*[!@/]\s*set\s+([^ ]+)", RegexOptions.IgnoreCase);
- Match getVarValueMatch = Regex.Match(cmd, @"\s*[!@/]\s*get\s+([^ ]+)", RegexOptions.IgnoreCase);
- Match enableMatch = Regex.Match(cmd, @"\s*[!@/]\s*enable\s+(.+)", RegexOptions.IgnoreCase);
- Match disableMatch = Regex.Match(cmd, @"\s*[!@/]\s*disable\s+(.+)", RegexOptions.IgnoreCase);
- //Information
- Match pluginSettingsMatch = Regex.Match(cmd, @"\s*[!@/]\s*settings", RegexOptions.IgnoreCase);
- bool senderIsAdmin = isAdmin(sender);
- DateTime now = utc;
- if (startBalancerMatch.Success && senderIsAdmin)
- startBalancerCmd(sender, now);
- else if (stopBalancerMatch.Success && senderIsAdmin)
- stopBalancerCmd(sender, now);
- else if (showPlayerRoundStatsMatch.Success && senderIsAdmin)
- showPlayerRoundStatsCmd(sender, showPlayerRoundStatsMatch.Groups[1].Value);
- else if (showRoundStatsMatch.Success && senderIsAdmin)
- showPlayerRoundStatsCmd(sender, null);
- else if (balanceLiveMatch.Success && senderIsAdmin)
- balanceLiveCmd(sender, now);
- else if (balanceRoundMatch.Success && senderIsAdmin)
- balanceRoundCmd(sender, now);
- else if (adminMovePlayerMatch.Success && senderIsAdmin)
- movePlayerCmd(sender, adminMovePlayerMatch.Groups[1].Value);
- else if (movePlayerMatch.Success)
- movePlayerCmd(sender);
- else if (setVarValueEqMatch.Success && senderIsAdmin)
- setVariableCmd(sender, setVarValueEqMatch.Groups[1].Value, setVarValueEqMatch.Groups[2].Value);
- else if (setVarValueToMatch.Success && senderIsAdmin)
- setVariableCmd(sender, setVarValueToMatch.Groups[1].Value, setVarValueToMatch.Groups[2].Value);
- else if (setVarValueMatch.Success && senderIsAdmin)
- setVariableCmd(sender, setVarValueMatch.Groups[1].Value, setVarValueMatch.Groups[2].Value);
- else if (setVarTrueMatch.Success && senderIsAdmin)
- setVariableCmd(sender, setVarTrueMatch.Groups[1].Value, "1");
- else if (getVarValueMatch.Success && senderIsAdmin)
- getVariableCmd(sender, getVarValueMatch.Groups[1].Value);
- else if (enableMatch.Success && senderIsAdmin)
- enableVarGroupCmd(sender, enableMatch.Groups[1].Value);
- else if (disableMatch.Success && senderIsAdmin)
- disableVarGroupCmd(sender, disableMatch.Groups[1].Value);
- else if (pluginSettingsMatch.Success && senderIsAdmin)
- pluginSettingsCmd(sender);
- }
- private string state2strWHILE(PluginState state)
- {
- if (state.Equals(PluginState.balance))
- {
- return "balancing";
- }
- else if (state.Equals(PluginState.check))
- {
- return "checking";
- }
- else if (state.Equals(PluginState.warn))
- {
- return "warning";
- }
- else if (state.Equals(PluginState.stop))
- {
- return "stopped";
- }
- else if (state.Equals(PluginState.wait))
- {
- return "waiting";
- }
- return "unknown state";
- }
- private void initializeBalancer()
- {
- getServerInfo();
- startStopState(utc);
- }
- private void movePlayerCmd(string sender)
- {
- if (teamsUnbalanced())
- {
- SendConsoleMessage(sender, "Teams are un-balanced, cannot move to other team");
- return;
- }
- movePlayerCmd(sender, null);
- }
- private void movePlayerCmd(string sender, string player)
- {
- /* player is moving himself */
- if (player == null)
- player = sender;
- SendConsoleMessage(sender, "moving player " + player);
- PlayerProfile profile = getPlayerProfile(player);
- if (profile == null)
- {
- SendConsoleMessage(sender, "cannot find profile for " + player);
- return;
- }
- if (profile.getTeamId() == 0)
- {
- SendConsoleMessage(sender, "cannot move " + player + " from neutral team");
- return;
- }
- int opposite = (profile.getTeamId() == 1) ? 2 : 1;
- movePlayer(profile, opposite, 0, false);
- }
- private void startWaitSate(DateTime now)
- {
- startWaitSate(null, now);
- }
- private void startWarnState(DateTime now)
- {
- startWarnState(null, now);
- }
- private void startWarnState(string sender, DateTime now)
- {
- if (!isPluginChecking())
- {
- SendConsoleMessage(sender, "plugin is in " + pluginState.ToString() + " state");
- return;
- }
- pluginState = PluginState.warn;
- setStartTime(pluginState, now.AddSeconds(1));
- DebugWrite("^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString(), 1);
- }
- private void startWaitSate(string sender, DateTime now)
- {
- if (!isPluginStopped())
- {
- SendConsoleMessage(sender, "cannot start while balancer is in " + pluginState.ToString() + " state");
- return;
- }
- if (sender != null)
- setPluginVarValue("auto_start", "true");
- pluginState = PluginState.wait;
- setStartTime(pluginState, now.AddSeconds(1));
- SendConsoleMessage(sender, "^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString());
- }
- private void startStopState(DateTime now)
- {
- startStopState(null, now);
- }
- private void startStopState(string sender, DateTime now)
- {
- virtual_mode = false;
- run_balancer = false;
- level_started = false;
- check_state_phase = 0;
- if (sender != null)
- setPluginVarValue("auto_start", "false");
- pluginState = PluginState.stop;
- setStartTime(pluginState, now.AddSeconds(1));
- SendConsoleMessage(sender, "^b" + pluginState + "^n state started " + getStartTime(pluginState).ToString());
- }
- public void balanceLiveCmd(string sender, DateTime now)
- {
- balanceLive(now);
- restartWaitState(now);
- }
- public void balanceRoundCmd(string sender, DateTime now)
- {
- balanceRound(1);
- restartWaitState(now);
- }
- public void showPlayerRoundStatsCmd(string sender, string player_name)
- {
- List<PlayerProfile> players_list;
- if (player_name == null)
- players_list = getPlayersProfile("");
- else
- players_list = getPlayersProfile(player_name);
- if (players_list.Count == 0)
- return;
- SendConsoleMessage(sender, " == Round Statistics ( "+Math.Round(getRoundMinutes(), 2)+" minutes) ==");
- foreach (PlayerProfile player in players_list)
- {
- SendConsoleMessage(sender, player.name + ": " + player.getRoundStatistics());
- }
- }
- private void startBalancerCmd(string sender, DateTime now)
- {
- setBooleanVarValue("balance_live", true);
- startWaitSate(now);
- }
- private void stopBalancerCmd(string sender, DateTime now)
- {
- setBooleanVarValue("balance_live", false);
- startStopState(now);
- }
- private void restartWaitState(DateTime now)
- {
- pluginState = PluginState.wait;
- setStartTime(pluginState, now.AddSeconds(1));
- DebugWrite("^b" + pluginState.ToString() + "^n state re-started " + getStartTime(pluginState).ToString() + "^0", 1);
- }
- private void genericSayAnnounce(List<string> messages)
- {
- if (messages.Count == 0)
- return;
- int remain_time = getRemainingTime(utc, pluginState);
- for (int i = 0; i < messages.Count; i++)
- {
- string msg = messages[i];
- msg = msg.Replace("%time%", remain_time.ToString());
- SendGlobalMessage(msg);
- }
- }
- private void warnAnnounce(int display_time)
- {
- if (!isPluginWarning())
- return;
- DebugWrite("sending ^b" + pluginState.ToString() + "^n announcement", 1);
- List<string> msg = new List<string>();
- msg.Add("Teams are unbalanced");
- msg.Add("Autobalancer starts in %time% secs");
- if (getBooleanVarValue("warn_say"))
- genericSayAnnounce(msg);
- }
- private void warnCountdown()
- {
- if (!isPluginWarning())
- return;
- DebugWrite("sending ^b" + pluginState.ToString() + "^n countdown", 1);
- int remain_time = getRemainingTime(utc, PluginState.warn);
- string msg = "Autobalancer starts in " + remain_time.ToString() + "!";
- if (getBooleanVarValue("warn_say"))
- SendGlobalMessage(msg);
- }
- private void enableVarGroupCmd(string sender, string group)
- {
- if (group.CompareTo("plugin") == 0)
- {
- ConsoleWrite("Disabling plugin");
- this.ExecuteCommand("procon.plugin.enable", "InsaneBalancer", "false");
- }
- enablePluginVarGroup(sender, group);
- }
- private void disableVarGroupCmd(string sender, string group)
- {
- if (group.CompareTo("plugin") == 0)
- {
- ConsoleWrite("Enabling plugin");
- this.ExecuteCommand("procon.plugin.enable", "InsaneBalancer", "true");
- }
- disablePluginVarGroup(sender, group);
- }
- private bool setPluginVarGroup(string sender, string group, string val)
- {
- if (group == null)
- {
- SendPlayerMessage(sender, "no variables to enable");
- return false;
- }
- group = group.Replace(";", ",");
- List<string> vars = new List<string>(Regex.Split(group, @"\s*,\s*", RegexOptions.IgnoreCase));
- foreach (string var in vars)
- {
- if (setPluginVarValue(sender, var, val))
- SendPlayerMessage(sender, var + " set to \"" + val + "\"");
- }
- return true;
- }
- private bool enablePluginVarGroup(string sender, string group)
- {
- //search for all variables matching
- List<string> vars = getVariableNames(group);
- if (vars.Count == 0)
- {
- SendPlayerMessage(sender, "no variables match \"" + group + "\"");
- return false;
- }
- return setPluginVarGroup(sender, String.Join(",", vars.ToArray()), "true");
- }
- private List<string> getVariableNames(string group)
- {
- List<string> names = new List<string>();
- List<string> list = new List<string>(Regex.Split(group, @"\s*,\s*"));
- List<string> vars = getPluginVars();
- foreach (string search in list)
- {
- foreach (string var in vars)
- {
- if (var.Contains(search))
- if (!names.Contains(var))
- names.Add(var);
- }
- }
- return names;
- }
- private bool disablePluginVarGroup(string sender, string group)
- {
- //search for all variables matching
- List<string> vars = getVariableNames(group);
- if (vars.Count == 0)
- {
- SendConsoleMessage(sender, "no variables match \"" + group + "\"");
- return false;
- }
- return setPluginVarGroup(sender, String.Join(",", vars.ToArray()), "false");
- }
- private void getVariableCmd(string sender, string var)
- {
- string val = getPluginVarValue(sender, var);
- SendPlayerMessage(sender, var + " = " + val);
- }
- private void setVariableCmd(string sender, string var, string val)
- {
- if (setPluginVarValue(sender, var, val))
- SendPlayerMessage(sender, var + " set to \"" + val + "\"");
- }
- private void pluginSettingsCmd(string sender)
- {
- SendConsoleMessage(" == Insane Balancer Settings == ");
- foreach (string var in getPluginVars())
- {
- SendConsoleMessage(sender, var + " = " + getPluginVarValue(sender, var));
- }
- }
- public bool stringValidator(string var, string value)
- {
- if (var.CompareTo("round_sort") == 0)
- {
- if (!strAssertSort(value))
- return false;
- }
- if (var.CompareTo("live_sort") == 0)
- {
- if (!strAssertSort(value))
- return false;
- }
- return true;
- }
- public List<String> getAllowedSorts()
- {
- List<string> sort_methods = new List<string>();
- sort_methods.Add("kdr_asc_round");
- sort_methods.Add("kdr_desc_round");
- sort_methods.Add("spm_asc_round");
- sort_methods.Add("spm_desc_round");
- sort_methods.Add("kpm_asc_round");
- sort_methods.Add("kpm_desc_round");
- sort_methods.Add("score_asc_round");
- sort_methods.Add("score_desc_round");
- return sort_methods;
- }
- public bool strAssertSort(string value)
- {
- if (value == null)
- return false;
- List<String> sort_methods = getAllowedSorts();
- if (!sort_methods.Contains(value))
- {
- SendConsoleMessage("^1^b" + value + "^n is not a valid sort method ^0");
- SendConsoleMessage("valid sort methods are: ^b" + String.Join("^0,^b ", sort_methods.ToArray()) + "^0");
- return false;
- }
- return true;
- }
- public bool booleanValidator(string var, bool value)
- {
- return true;
- }
- bool boolAssertNE(string var, bool value, string cmp)
- {
- bool cmp_value = getBooleanVarValue(cmp);
- if (!(value != cmp_value))
- {
- ConsoleWrite("^1 cannot set ^b" + var + "^n to ^b" + value.ToString() + "^n while ^b" + cmp + "^n is set to ^b" + cmp_value.ToString() + "^n^0");
- return false;
- }
- return true;
- }
- public bool integerValidator(string var, int value)
- {
- if (var.CompareTo("warn_msg_interval_time") == 0)
- {
- if (!intAssertGTE(var, value, 0) ||
- !intAssertLTE(var, value, "warn_msg_total_time"))
- return false;
- }
- if (var.CompareTo("warn_msg_countdown_time") == 0)
- {
- if (!intAssertGTE(var, value, 0) ||
- !intAssertLTE(var, value, "warn_msg_total_time"))
- return false;
- }
- if (var.CompareTo("warn_msg_total_time") == 0)
- {
- if (!intAssertGTE(var, value, 0) ||
- !intAssertGTE(var, value, "warn_msg_interval_time") ||
- !intAssertGTE(var, value, "warn_msg_countdown_time"))
- return false;
- }
- if (var.CompareTo("warn_msg_display_time") == 0)
- {
- if (!intAssertGTE(var, value, 0) ||
- !intAssertLTE(var, value, "warn_msg_total_time"))
- return false;
- }
- if (var.CompareTo("balance_threshold") == 0)
- {
- if (!intAssertGT(var, value, 0))
- return false;
- }
- if (var.CompareTo("round_interval") == 0)
- {
- if (!intAssertGT(var, value, 0))
- return false;
- if (serverInfo == null)
- return true;
- if (value > serverInfo.TotalRounds)
- {
- SendConsoleMessage("^1^b" + var + "(" + value + ")^n must be less than or equal than the total number of ^brounds(" + serverInfo.TotalRounds + ")^n per ^bmap(" + serverInfo.Map.ToLower() + ")^n^0");
- return false;
- }
- }
- if (var.CompareTo("live_interval_time") == 0)
- {
- if (!intAssertGT(var, value, 0))
- return false;
- }
- if (var.CompareTo("debug_level") == 0)
- {
- if (!intAssertGTE(var, value, 0))
- return false;
- }
- return true;
- }
- private bool intAssertLT(string var, int value, int max_value)
- {
- if (!(value < max_value))
- {
- SendConsoleMessage("^1^b" + var + "(" + value + ")^n must be less than ^b" + max_value + "^n^0");
- return false;
- }
- return true;
- }
- private bool intAssertLTE(string var, int value, int max_value)
- {
- if (!(value <= max_value))
- {
- SendConsoleMessage("^1^b" + var + "(" + value + ")^n must be less than or equal to ^b" + max_value + "^n^0");
- return false;
- }
- return true;
- }
- private bool intAssertGT(string var, int value, int min_value)
- {
- if (!(value > min_value))
- {
- SendConsoleMessage("^1^b" + var + "(" + value + ")^n must be greater than ^b" + min_value + "^n^0");
- return false;
- }
- return true;
- }
- private bool intAssertGTE(string var, int value, int min_value)
- {
- if (!(value >= min_value))
- {
- SendConsoleMessage("^1^b" + var + "(" + value + ")^n must be greater than or equal to ^b" + min_value + "^n^0");
- return false;
- }
- return true;
- }
- private bool intAssertGTE(string var1, int var1_value, string var2)
- {
- int var2_value = getIntegerVarValue(var2);
- if (!(var1_value >= var2_value))
- {
- SendConsoleMessage("^1^b" + var1 + "(" + var1_value + ")^n must be greater than or equal to the value of ^b" + var2 + "(" + var2_value + ")^n");
- return false;
- }
- return true;
- }
- private bool intAssertLTE(string var1, int var1_value, string var2)
- {
- int var2_value = getIntegerVarValue(var2);
- if (!(var1_value <= var2_value))
- {
- SendConsoleMessage("^1^b" + var1 + "(" + var1_value + ")^n must be less than or equal to the value of ^b" + var2 + "(" + var2_value + ")^n");
- return false;
- }
- return true;
- }
- private bool setPluginVarValue(string var, string val)
- {
- return setPluginVarValue(null, var, val);
- }
- private bool setPluginVarValue(string sender, string var, string val)
- {
- if (var == null || val == null)
- return false;
- if (!getPluginVars().Contains(var))
- {
- SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
- return false;
- }
- /* Parse Boolean Values */
- bool booleanValue = false;
- bool isBooleanValue = true;
- if (Regex.Match(val, @"\s*(1|true|yes)\s*", RegexOptions.IgnoreCase).Success)
- booleanValue = true;
- else if (Regex.Match(val, @"\s*(0|false|no)\s*", RegexOptions.IgnoreCase).Success)
- booleanValue = false;
- else
- isBooleanValue = false;
- /* Parse Integer Values */
- int integerValue = 0;
- //bool isIntegerValue = int.TryParse(val, out integerValue) && integerValue >= 0;
- bool isIntegerValue = int.TryParse(val, out integerValue);
- /* Parse Float Values */
- float floatValue = 0F;
- bool isFloatValue = float.TryParse(val, out floatValue) && floatValue >= 0F;
- /* Parse String List */
- List<string> stringListValue = new List<string>(Regex.Split(val.Replace(";", ","), @"\s*,\s*"));
- bool isStringList = true;
- /* Parse String var */
- string stringValue = val;
- bool isStringValue = (val != null);
- if (isBooleanVar(var))
- {
- if (!isBooleanValue)
- {
- SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
- return false;
- }
- setBooleanVarValue(var, booleanValue);
- return true;
- }
- else if (isIntegerVar(var))
- {
- if (!isIntegerValue)
- {
- SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
- return false;
- }
- setIntegerVarValue(var, integerValue);
- return true;
- }
- else if (isFloatVar(var))
- {
- if (!isFloatValue)
- {
- SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
- return false;
- }
- setFloatVarValue(var, floatValue);
- return true;
- }
- else if (isStringListVar(var))
- {
- if (!isStringList)
- {
- SendConsoleMessage(sender, "\"" + val + "\" is invalid for " + var);
- return false;
- }
- setStringListVarValue(var, stringListValue);
- return true;
- }
- else if (isStringVar(var))
- {
- if (!isStringValue)
- {
- SendConsoleMessage(sender, "invalid value for " + var);
- return false;
- }
- setStringVarValue(var, stringValue);
- return true;
- }
- else
- {
- SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
- return false;
- }
- }
- private bool isIntegerVar(string var)
- {
- return this.integerVariables.ContainsKey(var);
- }
- private int getIntegerVarValue(string var)
- {
- if (!isIntegerVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return -1;
- }
- return this.integerVariables[var];
- }
- private bool setIntegerVarValue(string var, int val)
- {
- if (!isIntegerVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- if (hasIntegerValidator(var))
- {
- integerVariableValidator validator = intergerVarValidators[var];
- if (validator(var, val) == false)
- return false;
- }
- this.integerVariables[var] = val;
- return true;
- }
- private bool hasBooleanValidator(string var)
- {
- return booleanVarValidators.ContainsKey(var);
- }
- private bool hasIntegerValidator(string var)
- {
- return intergerVarValidators.ContainsKey(var);
- }
- private bool hasStringValidator(string var)
- {
- return stringVarValidators.ContainsKey(var);
- }
- private bool isStringVar(string var)
- {
- return this.stringVariables.ContainsKey(var);
- }
- private string getStringVarValue(string var)
- {
- if (!isStringVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return "";
- }
- return this.stringVariables[var];
- }
- private bool setStringVarValue(string var, string val)
- {
- if (!isStringVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- if (hasStringValidator(var))
- {
- stringVariableValidator validator = stringVarValidators[var];
- if (validator(var, val) == false)
- return false;
- }
- string oldval = this.stringVariables[var];
- this.stringVariables[var] = val;
- return true;
- }
- private bool isStringListVar(string var)
- {
- return this.stringListVariables.ContainsKey(var);
- }
- private List<string> getStringListVarValue(string var)
- {
- if (!isStringListVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return new List<string>();
- }
- string[] out_list = Regex.Split(this.stringListVariables[var].Replace(";", ","), @"\s*,\s*");
- return new List<string>(out_list);
- }
- private bool setStringListVarValue(string var, List<string> val)
- {
- if (!isStringListVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- List<string> cleanList = new List<string>();
- foreach (string item in val)
- if (Regex.Match(item, @"^\s*$").Success)
- continue;
- else
- cleanList.Add(item);
- //this.stringListVariables[var] = val;
- this.stringListVariables[var] = String.Join(",", cleanList.ToArray());
- return true;
- }
- private bool isFloatVar(string var)
- {
- return this.floatVariables.ContainsKey(var);
- }
- private float getFloatVarValue(string var)
- {
- if (!isFloatVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return -1F;
- }
- return this.floatVariables[var];
- }
- private bool setFloatVarValue(string var, float val)
- {
- if (!isFloatVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- this.floatVariables[var] = val;
- return true;
- }
- private bool isBooleanVar(string var)
- {
- return this.booleanVariables.ContainsKey(var);
- }
- private bool getBooleanVarValue(string var)
- {
- if (!isBooleanVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- return this.booleanVariables[var];
- }
- private bool setBooleanVarValue(string var, bool val)
- {
- if (!isBooleanVar(var))
- {
- SendConsoleMessage("unknown variable \"" + var + "\"");
- return false;
- }
- if (hasBooleanValidator(var))
- {
- booleanVariableValidator validator = booleanVarValidators[var];
- if (validator(var, val) == false)
- return false;
- }
- this.booleanVariables[var] = val;
- return true;
- }
- private string getPluginVarValue(string var)
- {
- return getPluginVarValue(null, var);
- }
- private string getPluginVarValue(string sender, string var)
- {
- if (!getPluginVars().Contains(var))
- {
- SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
- return "";
- }
- if (isBooleanVar(var))
- {
- return getBooleanVarValue(var).ToString();
- }
- else if (isIntegerVar(var))
- {
- return getIntegerVarValue(var).ToString();
- }
- else if (isFloatVar(var))
- {
- return getFloatVarValue(var).ToString();
- }
- else if (isStringListVar(var))
- {
- string lst = list2string(getStringListVarValue(var), "");
- return lst;
- }
- else if (isStringVar(var))
- {
- return getStringVarValue(var);
- }
- else
- {
- SendConsoleMessage(sender, "Insane Balancer: unknown variable \"" + var + "\"");
- return "";
- }
- }
- private List<string> getPluginVars()
- {
- return getPluginVars(false);
- }
- private List<string> getPluginVars(bool hide)
- {
- List<string> vars = new List<string>();
- vars.AddRange(getIntegerPluginVars());
- vars.AddRange(getBooleanPluginVars());
- vars.AddRange(getStringListPluginVars());
- vars.AddRange(getFloatPluginVars());
- vars.AddRange(getStringPluginVars());
- if (hide && !getBooleanVarValue("advanced_mode"))
- {
- foreach (string hidden_var in hiddenVariables)
- vars.Remove(hidden_var);
- }
- return vars;
- }
- private List<string> getStringPluginVars()
- {
- return new List<string>(this.stringVariables.Keys);
- }
- private List<string> getStringListPluginVars()
- {
- return new List<string>(this.stringListVariables.Keys);
- }
- private List<string> getIntegerPluginVars()
- {
- return new List<string>(this.integerVariables.Keys);
- }
- private List<string> getFloatPluginVars()
- {
- return new List<string>(this.floatVariables.Keys);
- }
- private List<string> getBooleanPluginVars()
- {
- return new List<string>(this.booleanVariables.Keys);
- }
- public string playerstate2stringED(PlayerState state)
- {
- switch (state)
- {
- case PlayerState.alive:
- return "is alive";
- case PlayerState.dead:
- return "is dead";
- case PlayerState.kicked:
- return "was kicked";
- case PlayerState.left:
- return "left the game";
- case PlayerState.limbo:
- return "is in limbo";
- default:
- return "(%player_state%)";
- }
- }
- public string list2string(List<string> list, string glue)
- {
- if (list == null || list.Count == 0)
- return "";
- else if (list.Count == 1)
- return list[0];
- string last = list[list.Count - 1];
- list.RemoveAt(list.Count - 1);
- string str = "";
- foreach (string item in list)
- str += item + ", ";
- return str + glue + last;
- }
- public string list2string(List<string> list)
- {
- return list2string(list, "and ");
- }
- private bool isAdmin(string soldier)
- {
- List<string> admin_list = getStringListVarValue("admin_list");
- return admin_list.Contains(soldier);
- }
- private PlayerProfile getPlayerProfile(CPlayerInfo info)
- {
- return getPlayerProfile(info.SoldierName);
- }
- private List<PlayerProfile> getPlayersProfile(string name)
- {
- DebugWrite("^1ENTER: getPlayersProfile", 11);
- List<PlayerProfile> profiles = new List<PlayerProfile>();
- foreach (KeyValuePair<string, PlayerProfile> pair in this.players)
- {
- DebugWrite("^1 getPlayersProfile: processing "+pair.Key, 6);
- if (pair.Value.info == null || pair.Value.info.TeamID < 0)
- {
- DebugWrite("^1 getPlayersProfile: skipping " + pair.Key, 6);
- continue;
- }
- if (name.Equals(""))
- profiles.Add(pair.Value);
- else if (pair.Key.ToLower().Contains(name.ToLower()))
- profiles.Add(pair.Value);
- }
- DebugWrite("^1EXIT: getPlayersProfile, found ^b"+profiles.Count + "^n players", 11);
- return profiles;
- }
- private PlayerProfile getPlayerProfile(string name)
- {
- PlayerProfile pp;
- this.players.TryGetValue(name, out pp);
- return pp;
- }
- public override void OnPunkbusterPlayerInfo(CPunkbusterInfo cpbiPlayer)
- {
- if (cpbiPlayer != null)
- {
- if (this.players.ContainsKey(cpbiPlayer.SoldierName))
- this.players[cpbiPlayer.SoldierName].pbinfo = cpbiPlayer;
- else
- this.players.Add(cpbiPlayer.SoldierName, new PlayerProfile(this, cpbiPlayer));
- }
- }
- public override void OnListPlayers(List<CPlayerInfo> lstPlayers, CPlayerSubset cpsSubset)
- {
- DebugWrite("^1Players list received, ^b" + lstPlayers.Count + "^n players found", 6);
- foreach (CPlayerInfo cpiPlayer in lstPlayers)
- {
- DebugWrite("^1 found, ^b" + cpiPlayer.SoldierName + "^n", 6);
- if (this.players.ContainsKey(cpiPlayer.SoldierName))
- {
- // DebugWrite("^1 updating, ^b" + cpiPlayer.SoldierName + "^n", 6);
- this.players[cpiPlayer.SoldierName].updateInfo(cpiPlayer);
- }
- /* else
- {
- DebugWrite("^1 adding, ^b" + cpiPlayer.SoldierName + "^n", 6);
- this.players.Add(cpiPlayer.SoldierName, new PlayerProfile(this, cpiPlayer));
- } */
- //DebugWrite("^1 done with, ^b" + cpiPlayer.SoldierName + "^n", 6);
- }
- if (check_state_phase == 1)
- startCheckState(utc);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement