From 15c140b72826fd730d67601e6ac2f2bf26534b38 Mon Sep 17 00:00:00 2001
From: Aaron Veden <veden@vedbyte.com>
Date: Sun, 5 Dec 2021 17:17:41 -0800
Subject: [PATCH] adding max consecutive wanders to squads

---
 changelog.txt           |  1 +
 libs/SquadAttack.lua    | 14 ++++++++++----
 libs/UnitGroupUtils.lua |  1 +
 3 files changed, 12 insertions(+), 4 deletions(-)

diff --git a/changelog.txt b/changelog.txt
index 15773d3..2f22ee8 100644
--- a/changelog.txt
+++ b/changelog.txt
@@ -11,6 +11,7 @@ Date: 23. 11. 2021
     - Optimized regional base upgrades so that the work is spread over many ticks reducing lag spikes
     - Optimized adding new chunks to the Rampant in-memory state map
     - Added minimum building cost upgrade check before base upgrade performs scanning
+    - Added max number of wander commands in a row for squads that aren't going anywhere before disbanding squad
     - Optimized energy thief faction
     - Factorissimo, Space Exploration Orbits, asteroid belts, secret maps, starmap, AAI-signal, NiceFill, Blueprint lab surfaces are no longer processed
     - Map processing around player now changes to the surface the player is standing on
diff --git a/libs/SquadAttack.lua b/libs/SquadAttack.lua
index 24a739b..482d1f9 100644
--- a/libs/SquadAttack.lua
+++ b/libs/SquadAttack.lua
@@ -364,12 +364,18 @@ function squadAttack.cleanSquads(map, tick)
             end
             squads[groupId] = nil
         elseif (group.state == 4) then
+            squad.wanders = 0
             squadAttack.squadDispatch(map, squad, tick)
         elseif (squad.commandTick and (squad.commandTick < tick)) then
-            local cmd = map.universe.wander2Command
-            squad.commandTick = tick + COMMAND_TIMEOUT
-            group.set_command(cmd)
-            group.start_moving()
+            if squad.wanders > 5 then
+                squad.group.destroy()
+            else
+                squad.wanders = squad.wanders + 1
+                local cmd = map.universe.wander2Command
+                squad.commandTick = tick + COMMAND_TIMEOUT
+                group.set_command(cmd)
+                group.start_moving()
+            end
         end
     end
 end
diff --git a/libs/UnitGroupUtils.lua b/libs/UnitGroupUtils.lua
index 17446a0..8adc9d6 100644
--- a/libs/UnitGroupUtils.lua
+++ b/libs/UnitGroupUtils.lua
@@ -83,6 +83,7 @@ function unitGroupUtils.createSquad(position, surface, group, settlers)
         penalties = {},
         base = nil,
         frenzy = false,
+        wanders = 0,
         settlers = settlers or false,
         kamikaze = false,
         frenzyPosition = {x = 0,