start reducing duplication in HackyAI

This commit is contained in:
Chris Forbes
2010-11-02 07:27:31 +13:00
parent eac548ac8b
commit 002cc4842a

View File

@@ -35,28 +35,28 @@ namespace OpenRA.Mods.RA
{ {
class HackyAIInfo : ITraitInfo class HackyAIInfo : ITraitInfo
{ {
[FieldLoader.LoadUsing( "LoadUnits" )] [FieldLoader.LoadUsing("LoadUnits")]
public readonly Dictionary<string, float> UnitsToBuild; public readonly Dictionary<string, float> UnitsToBuild = null;
[FieldLoader.LoadUsing( "LoadBuildings" )] [FieldLoader.LoadUsing("LoadBuildings")]
public readonly Dictionary<string, float> BuildingFractions; public readonly Dictionary<string, float> BuildingFractions = null;
static object LoadUnits( MiniYaml y ) static object LoadUnits(MiniYaml y)
{ {
Dictionary<string,float> ret = new Dictionary<string, float>(); Dictionary<string, float> ret = new Dictionary<string, float>();
foreach (var t in y.NodesDict["UnitsToBuild"].Nodes) foreach (var t in y.NodesDict["UnitsToBuild"].Nodes)
ret.Add(t.Key, (float)FieldLoader.GetValue("units", typeof(float), t.Value.Value)); ret.Add(t.Key, (float)FieldLoader.GetValue("units", typeof(float), t.Value.Value));
return ret; return ret;
} }
static object LoadBuildings( MiniYaml y ) static object LoadBuildings(MiniYaml y)
{ {
Dictionary<string,float> ret = new Dictionary<string, float>(); Dictionary<string, float> ret = new Dictionary<string, float>();
foreach (var t in y.NodesDict["BuildingFractions"].Nodes) foreach (var t in y.NodesDict["BuildingFractions"].Nodes)
ret.Add(t.Key, (float)FieldLoader.GetValue("units", typeof(float), t.Value.Value)); ret.Add(t.Key, (float)FieldLoader.GetValue("units", typeof(float), t.Value.Value));
return ret; return ret;
} }
public object Create(ActorInitializer init) { return new HackyAI(this); } public object Create(ActorInitializer init) { return new HackyAI(this); }
} }
@@ -68,9 +68,10 @@ namespace OpenRA.Mods.RA
int ticks; int ticks;
Player p; Player p;
PowerManager playerPower; PowerManager playerPower;
int2 baseCenter; int2 baseCenter;
XRandom random = new XRandom(); //we do not use the synced random number generator. XRandom random = new XRandom(); //we do not use the synced random number generator.
BaseBuilder[] builders;
World world { get { return p.PlayerActor.World; } } World world { get { return p.PlayerActor.World; } }
@@ -79,7 +80,7 @@ namespace OpenRA.Mods.RA
{ {
this.Info = Info; this.Info = Info;
} }
enum BuildState enum BuildState
{ {
ChooseItem, ChooseItem,
@@ -87,13 +88,8 @@ namespace OpenRA.Mods.RA
WaitForFeedback, WaitForFeedback,
} }
int lastThinkTick = 0;
const int MaxBaseDistance = 15; const int MaxBaseDistance = 15;
BuildState bstate = BuildState.WaitForFeedback;
BuildState dstate = BuildState.WaitForFeedback;
public static void BotDebug(string s, params object[] args) public static void BotDebug(string s, params object[] args)
{ {
if (Game.Settings.Debug.BotDebug) if (Game.Settings.Debug.BotDebug)
@@ -106,6 +102,9 @@ namespace OpenRA.Mods.RA
this.p = p; this.p = p;
enabled = true; enabled = true;
playerPower = p.PlayerActor.Trait<PowerManager>(); playerPower = p.PlayerActor.Trait<PowerManager>();
builders = new BaseBuilder[] {
new BaseBuilder( this, "Building", ChooseBuildingToBuild ),
new BaseBuilder( this, "Defense", ChooseDefenseToBuild ) };
} }
int GetPowerProvidedBy(ActorInfo building) int GetPowerProvidedBy(ActorInfo building)
@@ -115,17 +114,17 @@ namespace OpenRA.Mods.RA
return bi.Power; return bi.Power;
} }
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue) ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue)
{ {
var buildableThings = queue.BuildableItems(); var buildableThings = queue.BuildableItems();
if (buildableThings.Count() == 0) return null; if (buildableThings.Count() == 0) return null;
return buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count())); return buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count()));
} }
bool HasAdequatePower() bool HasAdequatePower()
{ {
/* note: CNC `fact` provides a small amount of power. don't get jammed because of that. */ /* note: CNC `fact` provides a small amount of power. don't get jammed because of that. */
return playerPower.PowerProvided > 50 && return playerPower.PowerProvided > 50 &&
playerPower.PowerProvided > playerPower.PowerDrained * 1.2; playerPower.PowerProvided > playerPower.PowerDrained * 1.2;
} }
@@ -140,18 +139,13 @@ namespace OpenRA.Mods.RA
.OrderByDescending(a => GetPowerProvidedBy(a)).FirstOrDefault(); .OrderByDescending(a => GetPowerProvidedBy(a)).FirstOrDefault();
if (best != null) if (best != null)
{
BotDebug("AI: Need more power, so {0} is best choice.", best.Name);
return best; return best;
}
else
BotDebug("AI: Need more power, but can't build anything that produces it.");
} }
var myBuildings = p.World.Queries.OwnedBy[p].WithTrait<Building>() var myBuildings = p.World.Queries.OwnedBy[p].WithTrait<Building>()
.Select( a => a.Actor.Info.Name ).ToArray(); .Select(a => a.Actor.Info.Name).ToArray();
foreach (var frac in Info.BuildingFractions) foreach (var frac in Info.BuildingFractions)
if (buildableThings.Any(b => b.Name == frac.Key)) if (buildableThings.Any(b => b.Name == frac.Key))
if (myBuildings.Count(a => a == frac.Key) < frac.Value * myBuildings.Length) if (myBuildings.Count(a => a == frac.Key) < frac.Value * myBuildings.Length)
@@ -160,20 +154,20 @@ namespace OpenRA.Mods.RA
return null; return null;
} }
ActorInfo ChooseDefenseToBuild(ProductionQueue queue) ActorInfo ChooseDefenseToBuild(ProductionQueue queue)
{ {
var buildableThings = queue.BuildableItems(); var buildableThings = queue.BuildableItems();
var myBuildings = p.World.Queries.OwnedBy[p].WithTrait<Building>() var myBuildings = p.World.Queries.OwnedBy[p].WithTrait<Building>()
.Select(a => a.Actor.Info.Name).ToArray(); .Select(a => a.Actor.Info.Name).ToArray();
foreach (var frac in Info.BuildingFractions) foreach (var frac in Info.BuildingFractions)
if (buildableThings.Any(b => b.Name == frac.Key)) if (buildableThings.Any(b => b.Name == frac.Key))
if (myBuildings.Count(a => a == frac.Key) < frac.Value * myBuildings.Length) if (myBuildings.Count(a => a == frac.Key) < frac.Value * myBuildings.Length)
return Rules.Info[frac.Key]; return Rules.Info[frac.Key];
return null; return null;
} }
int2? ChooseBuildLocation(ProductionItem item) int2? ChooseBuildLocation(ProductionItem item)
{ {
@@ -197,40 +191,38 @@ namespace OpenRA.Mods.RA
ticks++; ticks++;
if (ticks == 10) if (ticks == 10)
{ {
DeployMcv(self); DeployMcv(self);
} }
if (ticks % feedbackTime == 0) if (ticks % feedbackTime == 0)
{ {
//about once every second, perform unintelligent cleanup tasks. //about once every second, perform unintelligent cleanup tasks.
//e.g. ClearAreaAroundSpawnPoints(); //e.g. ClearAreaAroundSpawnPoints();
//e.g. start repairing damaged buildings. //e.g. start repairing damaged buildings.
BuildRandom("Vehicle"); BuildRandom("Vehicle");
BuildRandom("Infantry"); BuildRandom("Infantry");
BuildRandom("Plane"); BuildRandom("Plane");
} }
AssignRolesToIdleUnits(self); AssignRolesToIdleUnits(self);
SetRallyPointsForNewProductionBuildings(self); SetRallyPointsForNewProductionBuildings(self);
foreach (var b in builders)
BuildBuildings(); b.Tick();
BuildDefense();
//build Ship
} }
//hacks etc sigh mess. //hacks etc sigh mess.
//A bunch of hardcoded lists to keep track of which units are doing what. //A bunch of hardcoded lists to keep track of which units are doing what.
List<Actor> unitsHangingAroundTheBase = new List<Actor>(); List<Actor> unitsHangingAroundTheBase = new List<Actor>();
List<Actor> attackForce = new List<Actor>(); List<Actor> attackForce = new List<Actor>();
//Units that the ai already knows about. Any unit not on this list needs to be given a role. //Units that the ai already knows about. Any unit not on this list needs to be given a role.
List<Actor> activeUnits = new List<Actor>(); List<Actor> activeUnits = new List<Actor>();
//This is purely to identify production buildings that don't have a rally point set. //This is purely to identify production buildings that don't have a rally point set.
List<Actor> activeProductionBuildings = new List<Actor>(); List<Actor> activeProductionBuildings = new List<Actor>();
bool IsHumanPlayer(Player p) bool IsHumanPlayer(Player p)
{ {
@@ -251,15 +243,15 @@ namespace OpenRA.Mods.RA
// 3. not dead. // 3. not dead.
var possibleTargets = world.WorldActor.Trait<MPStartLocations>().Start var possibleTargets = world.WorldActor.Trait<MPStartLocations>().Start
.Where(kv => kv.Key != p && (!HasHumanPlayers()|| IsHumanPlayer(kv.Key)) .Where(kv => kv.Key != p && (!HasHumanPlayers() || IsHumanPlayer(kv.Key))
&& p.WinState == WinState.Undefined) && p.WinState == WinState.Undefined)
.Select(kv => kv.Value); .Select(kv => kv.Value);
return possibleTargets.Any() ? possibleTargets.Random(random) : (int2?) null; return possibleTargets.Any() ? possibleTargets.Random(random) : (int2?)null;
} }
void AssignRolesToIdleUnits(Actor self) void AssignRolesToIdleUnits(Actor self)
{ {
//HACK: trim these lists -- we really shouldn't be hanging onto all this state //HACK: trim these lists -- we really shouldn't be hanging onto all this state
//when it's invalidated so easily, but that's Matthew/Alli's problem. //when it's invalidated so easily, but that's Matthew/Alli's problem.
activeUnits.RemoveAll(a => a.Destroyed); activeUnits.RemoveAll(a => a.Destroyed);
@@ -267,23 +259,23 @@ namespace OpenRA.Mods.RA
attackForce.RemoveAll(a => a.Destroyed); attackForce.RemoveAll(a => a.Destroyed);
activeProductionBuildings.RemoveAll(a => a.Destroyed); activeProductionBuildings.RemoveAll(a => a.Destroyed);
// don't select harvesters. // don't select harvesters.
var newUnits = self.World.Queries.OwnedBy[p] var newUnits = self.World.Queries.OwnedBy[p]
.Where(a => a.HasTrait<IMove>() && a.Info != Rules.Info["harv"] .Where(a => a.HasTrait<IMove>() && a.Info != Rules.Info["harv"]
&& !activeUnits.Contains(a)).ToArray(); && !activeUnits.Contains(a)).ToArray();
foreach (var a in newUnits) foreach (var a in newUnits)
{ {
BotDebug("AI: Found a newly built unit"); BotDebug("AI: Found a newly built unit");
unitsHangingAroundTheBase.Add(a); unitsHangingAroundTheBase.Add(a);
activeUnits.Add(a); activeUnits.Add(a);
} }
/* Create an attack force when we have enough units around our base. */ /* Create an attack force when we have enough units around our base. */
// (don't bother leaving any behind for defense.) // (don't bother leaving any behind for defense.)
if (unitsHangingAroundTheBase.Count > 8) if (unitsHangingAroundTheBase.Count > 8)
{ {
BotDebug("Launch an attack."); BotDebug("Launch an attack.");
var attackTarget = ChooseEnemyTarget(); var attackTarget = ChooseEnemyTarget();
if (attackTarget == null) if (attackTarget == null)
@@ -293,231 +285,186 @@ namespace OpenRA.Mods.RA
if (TryToMove(a, attackTarget.Value)) if (TryToMove(a, attackTarget.Value))
attackForce.Add(a); attackForce.Add(a);
unitsHangingAroundTheBase.Clear(); unitsHangingAroundTheBase.Clear();
} }
} }
private void SetRallyPointsForNewProductionBuildings(Actor self) void SetRallyPointsForNewProductionBuildings(Actor self)
{ {
var newProdBuildings = self.World.Queries.OwnedBy[p] var newProdBuildings = self.World.Queries.OwnedBy[p]
.Where(a => (a.TraitOrDefault<RallyPoint>() != null .Where(a => (a.TraitOrDefault<RallyPoint>() != null
&& !activeProductionBuildings.Contains(a) && !activeProductionBuildings.Contains(a)
)).ToArray(); )).ToArray();
foreach (var a in newProdBuildings) foreach (var a in newProdBuildings)
{ {
activeProductionBuildings.Add(a); activeProductionBuildings.Add(a);
int2 newRallyPoint = ChooseRallyLocationNear(a.Location); int2 newRallyPoint = ChooseRallyLocationNear(a.Location);
newRallyPoint.X += 4; newRallyPoint.X += 4;
newRallyPoint.Y += 4; newRallyPoint.Y += 4;
world.IssueOrder(new Order("SetRallyPoint", a, newRallyPoint)); world.IssueOrder(new Order("SetRallyPoint", a, newRallyPoint));
} }
} }
//won't work for shipyards... //won't work for shipyards...
private int2 ChooseRallyLocationNear(int2 startPos) int2 ChooseRallyLocationNear(int2 startPos)
{ {
Random r = new Random(); Random r = new Random();
foreach (var t in world.FindTilesInCircle(startPos, 8)) foreach (var t in world.FindTilesInCircle(startPos, 8))
if (world.IsCellBuildable(t, false) && t != startPos && r.Next(64) == 0) if (world.IsCellBuildable(t, false) && t != startPos && r.Next(64) == 0)
return t; return t;
return startPos; // i don't know where to put it.
}
//try very hard to find a valid move destination near the target. return startPos; // i don't know where to put it.
//(Don't accept a move onto the subject's current position. maybe this is already not allowed? ) }
private bool TryToMove(Actor a, int2 desiredMoveTarget)
{ //try very hard to find a valid move destination near the target.
//(Don't accept a move onto the subject's current position. maybe this is already not allowed? )
bool TryToMove(Actor a, int2 desiredMoveTarget)
{
if (!a.HasTrait<IMove>()) if (!a.HasTrait<IMove>())
return false; return false;
int2 xy; int2 xy;
int loopCount = 0; //avoid infinite loops. int loopCount = 0; //avoid infinite loops.
int range = 2; int range = 2;
do do
{ {
//loop until we find a valid move location //loop until we find a valid move location
xy = new int2(desiredMoveTarget.X + random.Next(-range, range), desiredMoveTarget.Y + random.Next(-range, range)); xy = new int2(desiredMoveTarget.X + random.Next(-range, range), desiredMoveTarget.Y + random.Next(-range, range));
loopCount++; loopCount++;
range = Math.Max(range, loopCount / 2); range = Math.Max(range, loopCount / 2);
if (loopCount > 10) return false; if (loopCount > 10) return false;
} while (!a.Trait<IMove>().CanEnterCell(xy) && xy != a.Location); } while (!a.Trait<IMove>().CanEnterCell(xy) && xy != a.Location);
world.IssueOrder(new Order("Move", a, xy)); world.IssueOrder(new Order("Move", a, xy));
return true; return true;
} }
private void DeployMcv(Actor self) void DeployMcv(Actor self)
{ {
/* find our mcv and deploy it */ /* find our mcv and deploy it */
var mcv = self.World.Queries.OwnedBy[p] var mcv = self.World.Queries.OwnedBy[p]
.FirstOrDefault(a => a.Info == Rules.Info["mcv"]); .FirstOrDefault(a => a.Info == Rules.Info["mcv"]);
if (mcv != null) if (mcv != null)
{ {
baseCenter = mcv.Location; baseCenter = mcv.Location;
world.IssueOrder(new Order("DeployTransform", mcv)); world.IssueOrder(new Order("DeployTransform", mcv));
} }
else else
BotDebug("AI: Can't find the MCV."); BotDebug("AI: Can't find the MCV.");
} }
//Build a random unit of the given type. Not going to be needed once there is actual AI... //Build a random unit of the given type. Not going to be needed once there is actual AI...
private void BuildRandom(string category) private void BuildRandom(string category)
{ {
// Pick a free queue // Pick a free queue
var queue = world.Queries.WithTraitMultiple<ProductionQueue>() var queue = world.Queries.WithTraitMultiple<ProductionQueue>()
.Where(a => a.Actor.Owner == p && .Where(a => a.Actor.Owner == p &&
a.Trait.Info.Type == category && a.Trait.Info.Type == category &&
a.Trait.CurrentItem() == null) a.Trait.CurrentItem() == null)
.Select(a => a.Trait) .Select(a => a.Trait)
.FirstOrDefault(); .FirstOrDefault();
if (queue == null) if (queue == null)
return; return;
var unit = ChooseRandomUnitToBuild(queue); var unit = ChooseRandomUnitToBuild(queue);
Boolean found = false; Boolean found = false;
if (unit != null) if (unit != null)
{ {
foreach (var un in Info.UnitsToBuild) foreach (var un in Info.UnitsToBuild)
{ {
if (un.Key == unit.Name) if (un.Key == unit.Name)
{ {
found = true; found = true;
break; break;
} }
} }
if (found == true) if (found == true)
{ {
world.IssueOrder(Order.StartProduction(queue.self, unit.Name, 1)); world.IssueOrder(Order.StartProduction(queue.self, unit.Name, 1));
} }
} }
} }
private void BuildBuildings() class BaseBuilder
{ {
// Pick a free queue BuildState state = BuildState.WaitForFeedback;
var queue = world.Queries.WithTraitMultiple<ProductionQueue>() string category;
.Where(a => a.Actor.Owner == p && a.Trait.Info.Type == "Building") HackyAI ai;
.Select(a => a.Trait) int lastThinkTick;
.FirstOrDefault(); Func<ProductionQueue, ActorInfo> chooseItem;
if (queue == null)
return;
var currentBuilding = queue.CurrentItem();
switch (bstate)
{
case BuildState.ChooseItem:
{
var item = ChooseBuildingToBuild(queue);
if (item == null)
{
bstate = BuildState.WaitForFeedback;
lastThinkTick = ticks;
}
else
{
BotDebug("AI: Starting production of {0}".F(item.Name));
bstate = BuildState.WaitForProduction;
world.IssueOrder(Order.StartProduction(queue.self, item.Name, 1));
}
}
break;
case BuildState.WaitForProduction: public BaseBuilder(HackyAI ai, string category, Func<ProductionQueue, ActorInfo> chooseItem)
if (currentBuilding == null) return; /* let it happen.. */ {
this.ai = ai;
this.category = category;
this.chooseItem = chooseItem;
}
else if (currentBuilding.Paused) public void Tick()
world.IssueOrder(Order.PauseProduction(queue.self, currentBuilding.Item, false)); {
else if (currentBuilding.Done) // Pick a free queue
{ var queue = ai.world.Queries.WithTraitMultiple<ProductionQueue>()
bstate = BuildState.WaitForFeedback; .Where(a => a.Actor.Owner == ai.p && a.Trait.Info.Type == category)
lastThinkTick = ticks; .Select(a => a.Trait)
.FirstOrDefault();
/* place the building */ if (queue == null)
var location = ChooseBuildLocation(currentBuilding); return;
if (location == null)
{
BotDebug("AI: Nowhere to place {0}".F(currentBuilding.Item));
world.IssueOrder(Order.CancelProduction(queue.self, currentBuilding.Item, 1));
}
else
{
world.IssueOrder(new Order("PlaceBuilding", p.PlayerActor, location.Value, currentBuilding.Item));
}
}
break;
case BuildState.WaitForFeedback: var currentBuilding = queue.CurrentItem();
if (ticks - lastThinkTick > feedbackTime) switch (state)
bstate = BuildState.ChooseItem; {
break; case BuildState.ChooseItem:
} {
} var item = chooseItem(queue);
if (item == null)
{
state = BuildState.WaitForFeedback;
lastThinkTick = ai.ticks;
}
else
{
BotDebug("AI: Starting production of {0}".F(item.Name));
state = BuildState.WaitForProduction;
ai.world.IssueOrder(Order.StartProduction(queue.self, item.Name, 1));
}
}
break;
private void BuildDefense() case BuildState.WaitForProduction:
{ if (currentBuilding == null) return; /* let it happen.. */
// Pick a free queue
var queue = world.Queries.WithTraitMultiple<ProductionQueue>()
.Where(a => a.Actor.Owner == p && a.Trait.Info.Type == "Defense")
.Select(a => a.Trait)
.FirstOrDefault();
if (queue == null) else if (currentBuilding.Paused)
return; ai.world.IssueOrder(Order.PauseProduction(queue.self, currentBuilding.Item, false));
else if (currentBuilding.Done)
{
state = BuildState.WaitForFeedback;
lastThinkTick = ai.ticks;
var currentBuilding = queue.CurrentItem(); /* place the building */
switch (dstate) var location = ai.ChooseBuildLocation(currentBuilding);
{ if (location == null)
case BuildState.ChooseItem: {
{ BotDebug("AI: Nowhere to place {0}".F(currentBuilding.Item));
var item = ChooseDefenseToBuild(queue); ai.world.IssueOrder(Order.CancelProduction(queue.self, currentBuilding.Item, 1));
if (item == null) }
{ else
dstate = BuildState.WaitForFeedback; {
lastThinkTick = ticks; ai.world.IssueOrder(new Order("PlaceBuilding", ai.p.PlayerActor,
} location.Value, currentBuilding.Item));
else }
{ }
BotDebug("AI: Starting production of {0}".F(item.Name)); break;
dstate = BuildState.WaitForProduction;
world.IssueOrder(Order.StartProduction(queue.self, item.Name, 1));
}
}
break;
case BuildState.WaitForProduction: case BuildState.WaitForFeedback:
if (currentBuilding == null) return; /* let it happen.. */ if (ai.ticks - lastThinkTick > feedbackTime)
state = BuildState.ChooseItem;
else if (currentBuilding.Paused) break;
world.IssueOrder(Order.PauseProduction(queue.self, currentBuilding.Item, false)); }
else if (currentBuilding.Done) }
{ }
dstate = BuildState.WaitForFeedback;
lastThinkTick = ticks;
/* place the building */
var location = ChooseBuildLocation(currentBuilding);
if (location == null)
{
BotDebug("AI: Nowhere to place {0}".F(currentBuilding.Item));
world.IssueOrder(Order.CancelProduction(queue.self, currentBuilding.Item, 1));
}
else
{
world.IssueOrder(new Order("PlaceBuilding", p.PlayerActor, location.Value, currentBuilding.Item));
}
}
break;
case BuildState.WaitForFeedback:
if (ticks - lastThinkTick > feedbackTime)
dstate = BuildState.ChooseItem;
break;
}
}
} }
} }