Koenrad

TeamBattlefield

Sep 25th, 2015
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 20.04 KB | None | 0 0
  1. using System.Collections.Generic;
  2. using System;
  3. using System.Text;
  4. using UnityEngine;
  5. using Oxide.Core;
  6. using Oxide.Core.Plugins;
  7. using System.Reflection;
  8.  
  9. namespace Oxide.Plugins
  10. {
  11.     [Info("TeamBattlefield", "BodyweightEnergy", "1.1.4", ResourceId = 1330)]
  12.     class TeamBattlefield : RustPlugin
  13.     {
  14.         #region Cached Variables
  15.  
  16.         private string TeamOneSpawnsFilename;
  17.         private string TeamTwoSpawnsFilename;
  18.         private Dictionary<string, string> displaynameToShortname;
  19.         private Dictionary<ulong, Team> playerTeam;
  20.         private Dictionary<ulong, DateTime> disconnectTime;
  21.         private float damageScale;
  22.         private string TeamOneShirt;
  23.         private string TeamTwoShirt;
  24.         private object TeamOneSpawnPoint;
  25.         private object TeamTwoSpawnPoint;
  26.         public static FieldInfo lastPositionValue;
  27.         private bool isAdminExempt
  28.         {
  29.             get { return (bool) Config["isAdminExempt"]; }
  30.         }
  31.  
  32.         #endregion
  33.  
  34.         // Default Constructor
  35.         public TeamBattlefield ()
  36.         {
  37.             displaynameToShortname = new Dictionary<string, string>();
  38.             playerTeam = new Dictionary<ulong, Team>();
  39.             TeamOneSpawnPoint = new object();
  40.             TeamTwoSpawnPoint = new object();
  41.             damageScale = new float();
  42.         }
  43.  
  44.         // Reference to Spawns Database
  45.         [PluginReference("Spawns")]
  46.         Plugin SpawnsDatabase;
  47.        
  48.         #region Hooks
  49.  
  50.         void Loaded()
  51.         {
  52.             object damageScaleFriendlyObj = Config["DamageScale"];
  53.             damageScale = float.Parse(damageScaleFriendlyObj.ToString());
  54.             Puts("Friendly-fire damage scaled to " + damageScale.ToString("0.000"));
  55.             TeamOneShirt = Config["TeamOneShirt"] as string;
  56.             TeamTwoShirt = Config["TeamTwoShirt"] as string;
  57.             TeamOneSpawnsFilename = Config["TeamOneSpawnfile"] as string;
  58.             TeamTwoSpawnsFilename = Config["TeamTwoSpawnfile"] as string;
  59.             lastPositionValue = typeof(BasePlayer).GetField("lastPositionValue", (BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic));
  60.         }
  61.  
  62.         // Default Configuration
  63.         protected override void LoadDefaultConfig()
  64.         {
  65.             PrintWarning("Creating a new configuration file.");
  66.             Config.Clear();
  67.             Config["isAdminExempt"] = true;
  68.             Config["TeamOneSpawnfile"] = "tbf_t1_spawns";
  69.             Config["TeamTwoSpawnfile"] = "tbf_t2_spawns";
  70.             Config["DamageScale"] = 0.0f;
  71.             Config["TeamOneShirt"] = "hoodie";
  72.             Config["TeamTwoShirt"] = "tshirt.long";
  73.             var common_items_belt = new Dictionary<string, object>();
  74.             var common_items_wear = new Dictionary<string, object>();
  75.             var common_items_main = new Dictionary<string, object>();
  76.             common_items_wear.Add("pants", 1);
  77.             common_items_wear.Add("riot.helmet", 1);
  78.             common_items_wear.Add("metal.plate.chest", 1);
  79.             common_items_wear.Add("shoes.boots", 1);
  80.             common_items_wear.Add("metal.plate.torso", 1);
  81.             common_items_belt.Add("rifle.ak", 1);
  82.             common_items_belt.Add("pistol.semiauto", 1);
  83.             common_items_belt.Add("machete", 1);
  84.             common_items_belt.Add("largemedkit", 3);
  85.             common_items_belt.Add("syringe.medical", 3);
  86.             common_items_belt.Add("rifle.bolt", 1);
  87.             common_items_main.Add("ammo.rifle.hv", 200);
  88.             common_items_main.Add("ammo.pistol.hv", 200);
  89.             common_items_main.Add("hatchet", 1);
  90.             common_items_main.Add("pickaxe", 1);
  91.             common_items_main.Add("grenade", 1);
  92.             Config["common_items_belt"] = common_items_belt;
  93.             Config["common_items_wear"] = common_items_wear;
  94.             Config["common_items_main"] = common_items_main;
  95.             SaveConfig();
  96.         }
  97.  
  98.         private void OnServerInitialized()
  99.         {
  100.             playerTeam = new Dictionary<ulong, Team>();
  101.             disconnectTime = new Dictionary<ulong, DateTime>();
  102.         }
  103.  
  104.         private void OnEntityTakeDamage(BaseCombatEntity entity, HitInfo hitInfo)
  105.         {
  106.             //if (entity == null || hitInfo == null) return;
  107.             if (entity is BasePlayer && hitInfo.Initiator is BasePlayer)
  108.             {
  109.                 //float damageScale = 1.0f;
  110.                 var sb = new StringBuilder();
  111.                 if (entity as BasePlayer == null || hitInfo == null) return;
  112.                 var attackerPlayer = (BasePlayer)hitInfo.Initiator;
  113.                 var victimPlayer = (BasePlayer)entity;
  114.                 var victimID = victimPlayer.userID;
  115.                 var attackerID = attackerPlayer.userID;
  116.                 if (playerTeam.ContainsKey(victimID) && playerTeam.ContainsKey(attackerID))
  117.                 {
  118.                     if (victimID != attackerID)
  119.                     {
  120.                         if (playerTeam[victimID] == playerTeam[attackerID])
  121.                         {
  122.                             hitInfo.damageTypes.ScaleAll(damageScale);
  123.                             sb.Append("You are shooting at a friendly!");
  124.                         }
  125.                     }
  126.                 }
  127.                 SendReply(hitInfo.Initiator as BasePlayer, sb.ToString());
  128.             }
  129.         }
  130.  
  131.         private void OnPlayerInit(BasePlayer player)
  132.         {
  133.             Team team = getTeamForBalance();
  134.             if (player.IsAdmin() && isAdminExempt) { team = Team.SPECTATOR; }    // By-pass team assignment if player is admin
  135.             AssignPlayerToTeam(player, team);
  136.             OnPlayerRespawned(player);
  137.         }
  138.  
  139.         private void OnPlayerDisconnected(BasePlayer player)
  140.         {
  141.             Puts("OnPlayerDisconnected(" + player.displayName + ") has been called.");
  142.             ulong ID = player.userID;
  143.             if (playerTeam.ContainsKey(ID)) playerTeam.Remove(ID);
  144.             // record time of disconnect
  145.             var currentTime = DateTime.UtcNow;
  146.             //Puts("OnPlayerDisconnected(): Current time = " + currentTime.ToString());
  147.             if(!disconnectTime.ContainsKey(player.userID))
  148.             {
  149.                 disconnectTime.Add(player.userID, currentTime);
  150.             }
  151.             else
  152.             {
  153.                 disconnectTime[player.userID] = currentTime;
  154.             }
  155.             Puts("OnPlayerDisconnected(): disconnectTime[" + player.displayName + "]=" + disconnectTime[player.userID].ToString());
  156.         }
  157.  
  158.         private void OnPlayerRespawned(BasePlayer player)
  159.         {
  160.             if (playerTeam.ContainsKey(player.userID))
  161.             {
  162.                 if (playerTeam[player.userID] == Team.SPECTATOR || (isAdminExempt && player.IsAdmin())) return;    //By-pass item giving if player is admin or spectator
  163.                 try
  164.                 {
  165.                     // Spawns Database functionality
  166.                     if (SpawnsDatabase != null)
  167.                     {
  168.                         var loadFile1Status = SpawnsDatabase.Call("loadSpawnfile", (string) Config["TeamOneSpawnfile"]);
  169.                         var loadFile2Status = SpawnsDatabase.Call("loadSpawnfile", (string) Config["TeamTwoSpawnfile"]);
  170.                         if (loadFile1Status is string || loadFile2Status is string )
  171.                         {
  172.                             PrintWarning("Correct spawn files not found.");
  173.                         }
  174.                         else
  175.                         {
  176.                             Vector3 spawnPoint = (Vector3)GetSpawnPoint(player);
  177.                             ForcePlayerPosition(player, spawnPoint);
  178.                             Puts("{0} spawned using Spawns Database, to position {1}", player.displayName, spawnPoint.ToString());
  179.                         }
  180.                     }
  181.                 } catch (InvalidCastException ex)
  182.                 {
  183.                     PrintWarning("InvalidCastException on Spawns Database. Please report to plugin developer.");
  184.                 }
  185.                 //Puts("Entered OnPlayerRespawned. Player team is " + playerTeam[player.userID].ToString());
  186.                 player.inventory.Strip();
  187.                 var common_item_wear = (Dictionary<string, object>) Config["common_items_wear"];
  188.                 foreach (var item in common_item_wear)
  189.                 {
  190.                     GiveItem(player, item.Key, (int) item.Value, player.inventory.containerWear);
  191.                 }
  192.                 var common_item_belt = (Dictionary<string, object>) Config["common_items_belt"];
  193.                 foreach (var item in common_item_belt)
  194.                 {
  195.                     GiveItem(player, item.Key, (int) item.Value, player.inventory.containerBelt);
  196.                 }
  197.                 var common_item_main = (Dictionary<string, object>) Config["common_items_main"];
  198.                 foreach (var item in common_item_main)
  199.                 {
  200.                     GiveItem(player, item.Key, (int) item.Value, player.inventory.containerMain);
  201.                 }
  202.                 if (playerTeam[player.userID] == Team.RED)
  203.                 {
  204.                     GiveItem(player, TeamOneShirt, 1, player.inventory.containerWear);
  205.                 }
  206.                 else if (playerTeam[player.userID] == Team.BLUE)
  207.                 {
  208.                     //GiveItem(player, TeamTwoShirt, 1, player.inventory.containerWear);
  209.                     //----------------------Give a blue shirt---------------------//
  210.                     Item item = ItemManager.CreateByName("hoodie", 1);
  211.                     item.skin = 14178;      //Blue skin
  212.                     player.inventory.GiveItem(item, player.inventory.containerWear);
  213.                    
  214.                 }
  215.                
  216.                 //----------------------Lock the players clothing---------------------//
  217.                 player.inventory.containerWear.SetFlag(ItemContainer.Flag.IsLocked, true);
  218.                
  219.             }
  220.             else
  221.             {
  222.                 OnPlayerInit(player);
  223.             }
  224.         }
  225.  
  226.         #endregion
  227.  
  228.         #region Kits
  229.  
  230.         private void InitializeTable()
  231.         {
  232.             displaynameToShortname.Clear();
  233.             List<ItemDefinition> ItemsDefinition = ItemManager.GetItemDefinitions() as List<ItemDefinition>;
  234.             foreach (ItemDefinition itemdef in ItemsDefinition)
  235.             {
  236.                 displaynameToShortname.Add(itemdef.displayName.english.ToString().ToLower(), itemdef.shortname.ToString());
  237.             }
  238.         }
  239.  
  240.         public object GiveItem(BasePlayer player, string itemname, int amount, ItemContainer pref)
  241.         {
  242.             itemname = itemname.ToLower();
  243.  
  244.             bool isBP = false;
  245.             if (itemname.EndsWith(" bp"))
  246.             {
  247.                 isBP = true;
  248.                 itemname = itemname.Substring(0, itemname.Length - 3);
  249.             }
  250.             if (displaynameToShortname.ContainsKey(itemname))
  251.                 itemname = displaynameToShortname[itemname];
  252.             var definition = ItemManager.FindItemDefinition(itemname);
  253.             if (definition == null)
  254.                 return string.Format("{0} {1}", "Item not found: ", itemname);
  255.             int giveamount = 0;
  256.             int stack = (int)definition.stackable;
  257.             if (isBP)
  258.                 stack = 1;
  259.             if (stack < 1) stack = 1;
  260.             for (var i = amount; i > 0; i = i - stack)
  261.             {
  262.                 if (i >= stack)
  263.                     giveamount = stack;
  264.                 else
  265.                     giveamount = i;
  266.                 if (giveamount < 1) return true;
  267.                 player.inventory.GiveItem(ItemManager.CreateByItemID((int)definition.itemid, giveamount, isBP), pref);
  268.             }
  269.             return true;
  270.         }
  271.  
  272.         #endregion
  273.          
  274.         #region Console Commands
  275.  
  276.         [ConsoleCommand("tbf.list")]
  277.         private void cmdList(ConsoleSystem.Arg arg)
  278.         {
  279.            
  280.             var sb = new StringBuilder();
  281.             sb.Append("Team/Player List:\n");
  282.             foreach (var player in playerTeam)
  283.             {
  284.                 var playerID = player.Key;
  285.                 var Bplayer = BasePlayer.FindByID(playerID);
  286.                 //sb.Append(player.Key);
  287.                 //sb.Append(": ");
  288.                 sb.Append(player.Value.ToString());
  289.                 sb.Append("\t\t");
  290.                 if (!disconnectTime.ContainsKey(playerID)) { sb.Append("N/A"); } else { sb.Append(disconnectTime[playerID].ToString()); }
  291.                 sb.Append("\t\t");
  292.                 sb.Append(Bplayer.displayName);
  293.                 sb.Append("\n");
  294.             }
  295.             PrintToConsole(arg.Player(), sb.ToString());
  296.         }
  297.  
  298.         [ConsoleCommand("tbf.assign")]
  299.         private void cmdAssign(ConsoleSystem.Arg arg)
  300.         {
  301.             var success = true;
  302.             var sb = new StringBuilder();
  303.             var args = arg.Args;
  304.             if(args.Length != 2)
  305.             {
  306.                 sb.Append("Format: tbf.assign <PARTIAL_PLAYERNAME> <[\"red\",\"blue\",\"spectator\"]>");
  307.             }
  308.             else if(arg.connection.authLevel < 1)
  309.             {
  310.                 sb.Append("You don't have permission to assign players.");
  311.             }
  312.             else
  313.             {
  314.                 var partialPlayerName = args[0];
  315.                 var player = FindPlayerByPartialName(partialPlayerName);
  316.                 var newTeamString = args[1].ToLower();
  317.                 var newTeam = Team.SPECTATOR;
  318.                 switch(newTeamString)
  319.                 {
  320.                     case "red":
  321.                         newTeam = Team.RED;
  322.                         break;
  323.  
  324.                     case "blue":
  325.                         newTeam = Team.BLUE;
  326.                         break;
  327.                     case "spectator":
  328.                         newTeam = Team.SPECTATOR;
  329.                         break;
  330.  
  331.                     default:
  332.                         sb.Append("Invalid team assignment.");
  333.                         success = false;
  334.                         break;
  335.                 }
  336.                 if (success)
  337.                 {
  338.                     AssignPlayerToTeam(player, newTeam);
  339.                     sb.Append(player.displayName + " has been successfully assigned to team " + newTeamString);
  340.                 }
  341.             }
  342.             PrintToConsole(arg.Player(), sb.ToString());
  343.         }
  344.  
  345.         [ConsoleCommand("tbf.version")]
  346.         private void cmdVersion(ConsoleSystem.Arg arg)
  347.         {
  348.             PrintToConsole(arg.Player(), Version.ToString());
  349.         }
  350.  
  351.         [ConsoleCommand("tbf.purge")]
  352.         private void cmdPurge(ConsoleSystem.Arg arg)
  353.         {
  354.             int count = KickSleepers();
  355.             PrintToConsole(arg.Player(), "Unassigned a total of " + count.ToString() + " players.");
  356.         }
  357.  
  358.         [ConsoleCommand("tbf.help")]
  359.         private void cmdHelp(ConsoleSystem.Arg arg)
  360.         {
  361.             var sb = new StringBuilder();
  362.             sb.Append("TeamBattlefield Console Commands:\n\n");
  363.             sb.Append("tbf.list\t\t\tLists Teams and Disconnect Times of players.\n");
  364.             sb.Append("tbf.assign <PartialPlayerName> [red/blue/spectator]\t\t\tAssigns player to team.\n");
  365.             sb.Append("tbf.purge\t\t\tRemoves players from all teams if they're been disconnected for more than 5 minutes.\n");
  366.             sb.Append("tbf.version\t\t\tPrints current version number of plugin.\n");
  367.  
  368.             PrintToConsole(arg.Player(), sb.ToString());
  369.         }
  370.  
  371.         #endregion
  372.  
  373.         #region Team Management
  374.  
  375.         enum Team
  376.         {
  377.             RED,
  378.             BLUE,
  379.             SPECTATOR
  380.         }
  381.  
  382.         private int TeamCount(Team team)
  383.         {
  384.             int count = 0;
  385.             foreach (var player in playerTeam)
  386.             {
  387.                 if (player.Value == team)
  388.                     count++;
  389.             }
  390.             return count;
  391.         }
  392.  
  393.         // Returns the proper team to maintain team balance
  394.         private Team getTeamForBalance()
  395.         {
  396.             Team returnedTeam = Team.SPECTATOR;
  397.             int teamOneCount = TeamCount(Team.RED);
  398.             int teamTwoCount = TeamCount(Team.BLUE);
  399.  
  400.             if (teamOneCount > teamTwoCount)
  401.             {
  402.                 returnedTeam = Team.BLUE;
  403.             }
  404.             else
  405.             {
  406.                 returnedTeam = Team.RED;
  407.             }
  408.             return returnedTeam;
  409.         }
  410.  
  411.         private object GetSpawnPoint(BasePlayer player)
  412.         {
  413.             var filename = "";
  414.             var team = playerTeam[player.userID];
  415.             if (team == Team.RED) filename = Config["TeamOneSpawnfile"].ToString();
  416.             else if (team == Team.BLUE) filename = Config["TeamTwoSpawnfile"].ToString();
  417.             var spawnPoint = SpawnsDatabase.Call("GetRandomSpawn", new object[] {filename});
  418.             return spawnPoint;
  419.         }
  420.  
  421.         private BasePlayer FindPlayerByPartialName(string name)
  422.         {
  423.             if (string.IsNullOrEmpty(name))
  424.                 return null;
  425.             BasePlayer player = null;
  426.             name = name.ToLower();
  427.             var allPlayers = BasePlayer.activePlayerList.ToArray();
  428.             // Try to find an exact match first
  429.             foreach (var p in allPlayers)
  430.             {
  431.                 if (p.displayName == name)
  432.                 {
  433.                     if (player != null)
  434.                         return null; // Not unique
  435.                     player = p;
  436.                 }
  437.             }
  438.             if (player != null)
  439.                 return player;
  440.             // Otherwise try to find a partial match
  441.             foreach (var p in allPlayers)
  442.             {
  443.                 if (p.displayName.ToLower().IndexOf(name) >= 0)
  444.                 {
  445.                     if (player != null)
  446.                         return null; // Not unique
  447.                     player = p;
  448.                 }
  449.             }
  450.             return player;
  451.         }
  452.  
  453.         private void AssignPlayerToTeam(BasePlayer player , Team newTeam)
  454.         {
  455.             playerTeam[player.userID] = newTeam;
  456.             string teamName = playerTeam[player.userID].ToString();
  457.             if(playerTeam[player.userID] != Team.SPECTATOR) SendReply(player, "You have been assigned to Team " + teamName + ".");
  458.         }
  459.  
  460.         private int KickSleepers()
  461.         {
  462.             int count = 0;
  463.             foreach(var playerKey in disconnectTime)
  464.             {
  465.                 var playerID = playerKey.Key;
  466.                 var timeDelta = DateTime.UtcNow.Subtract(playerKey.Value);
  467.                 if (timeDelta.TotalMinutes > 5)
  468.                 {
  469.                     var player = BasePlayer.FindByID(playerID);
  470.                     if (player == null)
  471.                     {
  472.                         disconnectTime.Remove(playerID);
  473.                         count++;
  474.                     }
  475.                     else if (!BasePlayer.FindByID(playerID).IsAlive() && playerTeam.ContainsKey(playerID))
  476.                     {
  477.                         playerTeam.Remove(playerID);
  478.                         disconnectTime.Remove(playerID);
  479.                         count++;
  480.                     }
  481.                 }
  482.             }
  483.             Puts("Kicked a total of " + count.ToString() + " sleepers.");
  484.             return count;
  485.         }
  486.  
  487.         #endregion
  488.  
  489.         static void ForcePlayerPosition(BasePlayer player, Vector3 destination)
  490.         {
  491.             //PutToSleep(player);
  492.             player.transform.position = destination;
  493.             lastPositionValue.SetValue(player, player.transform.position);
  494.             player.ClientRPCPlayer(null, player, "ForcePositionTo", new object[] { destination });
  495.             player.TransformChanged();
  496.  
  497.             player.SetPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot, true);
  498.             player.UpdateNetworkGroup();
  499.  
  500.             player.SendNetworkUpdateImmediate(false);
  501.             player.ClientRPCPlayer(null, player, "StartLoading");
  502.             player.SendFullSnapshot();
  503.             player.SetPlayerFlag(BasePlayer.PlayerFlags.ReceivingSnapshot, false);
  504.             player.ClientRPCPlayer(null, player, "FinishLoading");
  505.         }
  506.     }
  507. }
Advertisement
Add Comment
Please, Sign In to add comment