From a378089f1ba004f9ac2910bc1d84f7859e631117 Mon Sep 17 00:00:00 2001 From: OverHash <46231745+OverHash@users.noreply.github.com> Date: Thu, 23 Apr 2020 22:17:20 +1200 Subject: [PATCH] Clean AutoAttack A lot of this code is messy and has unused variables. Additionally, there are memory leaks as dead entities are not removed from meory. --- MinecraftClient/ChatBots/AutoAttack.cs | 41 ++++++++++++++++---------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/MinecraftClient/ChatBots/AutoAttack.cs b/MinecraftClient/ChatBots/AutoAttack.cs index e6c937fd..d3564a64 100644 --- a/MinecraftClient/ChatBots/AutoAttack.cs +++ b/MinecraftClient/ChatBots/AutoAttack.cs @@ -12,7 +12,6 @@ namespace MinecraftClient.ChatBots class AutoAttack : ChatBot { private Dictionary entitiesToAttack = new Dictionary(); // mobs within attack range - private Dictionary entitiesToTrack = new Dictionary(); // all mobs in view distance private int attackCooldown = 6; private int attackCooldownCounter = 6; private Double attackSpeed = 4; @@ -54,28 +53,18 @@ namespace MinecraftClient.ChatBots public override void OnEntitySpawn(Entity entity) { - if (entity.IsHostile()) - { - entitiesToTrack.Add(entity.ID, entity); - } + handleEntity(entity); } public override void OnEntityDespawn(Entity entity) { - if (entitiesToTrack.ContainsKey(entity.ID)) + if (entitiesToAttack.ContainsKey(entity.ID)) { - entitiesToTrack.Remove(entity.ID); + entitiesToAttack.Remove(entity.ID); } } public override void OnEntityMove(Entity entity) { - if (entitiesToTrack.ContainsKey(entity.ID)) - { - if (GetCurrentLocation().Distance(entity.Location) < attackRange) - { - if (!entitiesToAttack.ContainsKey(entity.ID)) - entitiesToAttack.Add(entity.ID, entity); - } - } + handleEntity(entity); } public override void OnPlayerProperty(Dictionary prop) @@ -100,5 +89,27 @@ namespace MinecraftClient.ChatBots attackCooldownSecond = 1 / attackSpeed * (serverTPS / 20.0); // server tps will affect the cooldown attackCooldown = Convert.ToInt32(Math.Truncate(attackCooldownSecond / 0.1) + 1); } + + public void handleEntity(Entity entity) + { + if (!entity.IsHostile()) return; + + bool isBeingAttacked = entitiesToAttack.ContainsKey(entity.ID); + if (GetCurrentLocation().Distance(entity.Location) < attackRange) + { + // check to see if entity has not been marked as tracked, and if not, track it. + if (!isBeingAttacked) + { + entitiesToAttack.Add(entity.ID, entity); + } + } else + { + // remove marker on entity to attack it, as it is now out of range + if (isBeingAttacked) + { + entitiesToAttack.Remove(entity.ID); + } + } + } } }