Split off last bot modules
And dissolve AI namespace. There would have been so little left in Common.AI, that keeping it made no sense anymore.
This commit is contained in:
@@ -13,7 +13,6 @@ using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Support;
|
||||
using OpenRA.Traits;
|
||||
|
||||
@@ -123,7 +122,7 @@ namespace OpenRA.Mods.Common.Traits
|
||||
public override object Create(ActorInitializer init) { return new BaseBuilderBotModule(init.Self, this); }
|
||||
}
|
||||
|
||||
public class BaseBuilderBotModule : ConditionalTrait<BaseBuilderBotModuleInfo>, IBotTick, IBotPositionsUpdated, IBotRespondToAttack
|
||||
public class BaseBuilderBotModule : ConditionalTrait<BaseBuilderBotModuleInfo>, IBotTick, IBotPositionsUpdated, IBotRespondToAttack, IBotRequestPauseUnitProduction
|
||||
{
|
||||
public CPos GetRandomBaseCenter()
|
||||
{
|
||||
@@ -181,6 +180,11 @@ namespace OpenRA.Mods.Common.Traits
|
||||
defenseCenter = newLocation;
|
||||
}
|
||||
|
||||
bool IBotRequestPauseUnitProduction.PauseUnitProduction
|
||||
{
|
||||
get { return !IsTraitDisabled && !HasAdequateRefineryCount; }
|
||||
}
|
||||
|
||||
void IBotTick.BotTick(IBot bot)
|
||||
{
|
||||
SetRallyPointsForNewProductionBuildings(bot);
|
||||
@@ -200,8 +204,8 @@ namespace OpenRA.Mods.Common.Traits
|
||||
if (!e.Attacker.Info.HasTraitInfo<ITargetableInfo>())
|
||||
return;
|
||||
|
||||
// Protected priority assets, MCVs, harvesters and buildings
|
||||
if (self.Info.HasTraitInfo<BuildingInfo>() || self.Info.HasTraitInfo<BaseBuildingInfo>())
|
||||
// Protect buildings
|
||||
if (self.Info.HasTraitInfo<BuildingInfo>())
|
||||
foreach (var n in positionsUpdatedModules)
|
||||
n.UpdatedDefenseCenter(e.Attacker.Location);
|
||||
}
|
||||
@@ -240,5 +244,26 @@ namespace OpenRA.Mods.Common.Traits
|
||||
{
|
||||
return info != null && world.IsCellBuildable(x, null, info);
|
||||
}
|
||||
|
||||
public bool HasAdequateRefineryCount
|
||||
{
|
||||
get
|
||||
{
|
||||
// Require at least one refinery, unless we can't build it.
|
||||
return AIUtils.CountBuildingByCommonName(Info.RefineryTypes, player) >= MinimumRefineryCount ||
|
||||
AIUtils.CountBuildingByCommonName(Info.PowerTypes, player) == 0 ||
|
||||
AIUtils.CountBuildingByCommonName(Info.ConstructionYardTypes, player) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
int MinimumRefineryCount
|
||||
{
|
||||
get
|
||||
{
|
||||
// Unless we have no barracks (higher priority), require a 2nd refinery.
|
||||
// TODO: Possibly unhardcode this, at least the targeted minimum of 2 (the fallback can probably stay at 1).
|
||||
return AIUtils.CountBuildingByCommonName(Info.BarracksTypes, player) > 0 ? 2 : 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
@@ -219,7 +218,7 @@ namespace OpenRA.Mods.Common.Traits
|
||||
}
|
||||
|
||||
// Next is to build up a strong economy
|
||||
if (!HasAdequateRefineryCount)
|
||||
if (!baseBuilder.HasAdequateRefineryCount)
|
||||
{
|
||||
var refinery = GetProducibleBuilding(baseBuilder.Info.RefineryTypes, buildableThings);
|
||||
if (refinery != null && HasSufficientPowerForActor(refinery))
|
||||
@@ -410,26 +409,5 @@ namespace OpenRA.Mods.Common.Traits
|
||||
// Can't find a build location
|
||||
return null;
|
||||
}
|
||||
|
||||
bool HasAdequateRefineryCount
|
||||
{
|
||||
get
|
||||
{
|
||||
// Require at least one refinery, unless we can't build it.
|
||||
return AIUtils.CountBuildingByCommonName(baseBuilder.Info.RefineryTypes, player) >= MinimumRefineryCount ||
|
||||
AIUtils.CountBuildingByCommonName(baseBuilder.Info.PowerTypes, player) == 0 ||
|
||||
AIUtils.CountBuildingByCommonName(baseBuilder.Info.ConstructionYardTypes, player) == 0;
|
||||
}
|
||||
}
|
||||
|
||||
int MinimumRefineryCount
|
||||
{
|
||||
get
|
||||
{
|
||||
// Unless we have no barracks (higher priority), require a 2nd refinery.
|
||||
// TODO: Possibly unhardcode this, at least the targeted minimum of 2 (the fallback can probably stay at 1).
|
||||
return AIUtils.CountBuildingByCommonName(baseBuilder.Info.BarracksTypes, player) > 0 ? 2 : 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Primitives;
|
||||
using OpenRA.Traits;
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
|
||||
@@ -13,7 +13,6 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.Activities;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Mods.Common.Pathfinder;
|
||||
using OpenRA.Traits;
|
||||
|
||||
|
||||
222
OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs
Normal file
222
OpenRA.Mods.Common/Traits/BotModules/McvManagerBotModule.cs
Normal file
@@ -0,0 +1,222 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Support;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
{
|
||||
[Desc("Manages AI MCVs.")]
|
||||
public class McvManagerBotModuleInfo : ConditionalTraitInfo
|
||||
{
|
||||
[Desc("Actor types that are considered MCVs (deploy into base builders).")]
|
||||
public readonly HashSet<string> McvTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Actor types that are considered construction yards (base builders).")]
|
||||
public readonly HashSet<string> ConstructionYardTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Actor types that are able to produce MCVs.")]
|
||||
public readonly HashSet<string> McvFactoryTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Try to maintain at least this many ConstructionYardTypes, build an MCV if number is below this.")]
|
||||
public readonly int MinimumConstructionYardCount = 1;
|
||||
|
||||
[Desc("Delay (in ticks) between looking for and giving out orders to new MCVs.")]
|
||||
public readonly int ScanForNewMcvInterval = 20;
|
||||
|
||||
[Desc("Minimum distance in cells from center of the base when checking for MCV deployment location.")]
|
||||
public readonly int MinBaseRadius = 2;
|
||||
|
||||
[Desc("Maximum distance in cells from center of the base when checking for MCV deployment location.",
|
||||
"Only applies if RestrictMCVDeploymentFallbackToBase is enabled and there's at least one construction yard.")]
|
||||
public readonly int MaxBaseRadius = 20;
|
||||
|
||||
[Desc("Should deployment of additional MCVs be restricted to MaxBaseRadius if explicit deploy locations are missing or occupied?")]
|
||||
public readonly bool RestrictMCVDeploymentFallbackToBase = true;
|
||||
|
||||
public override object Create(ActorInitializer init) { return new McvManagerBotModule(init.Self, this); }
|
||||
}
|
||||
|
||||
public class McvManagerBotModule : ConditionalTrait<McvManagerBotModuleInfo>, IBotTick, IBotPositionsUpdated
|
||||
{
|
||||
public CPos GetRandomBaseCenter()
|
||||
{
|
||||
var randomConstructionYard = world.Actors.Where(a => a.Owner == player &&
|
||||
Info.ConstructionYardTypes.Contains(a.Info.Name))
|
||||
.RandomOrDefault(world.LocalRandom);
|
||||
|
||||
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter;
|
||||
}
|
||||
|
||||
readonly World world;
|
||||
readonly Player player;
|
||||
|
||||
readonly Predicate<Actor> unitCannotBeOrdered;
|
||||
|
||||
IBotPositionsUpdated[] notifyPositionsUpdated;
|
||||
IBotRequestUnitProduction[] requestUnitProduction;
|
||||
|
||||
CPos initialBaseCenter;
|
||||
int scanInterval;
|
||||
int ticks;
|
||||
|
||||
// MCVs that the bot already knows about. Any MCV not on this list needs to be given an order.
|
||||
List<Actor> activeMCVs = new List<Actor>();
|
||||
|
||||
public McvManagerBotModule(Actor self, McvManagerBotModuleInfo info)
|
||||
: base(info)
|
||||
{
|
||||
world = self.World;
|
||||
player = self.Owner;
|
||||
unitCannotBeOrdered = a => a.Owner != player || a.IsDead || !a.IsInWorld;
|
||||
}
|
||||
|
||||
protected override void TraitEnabled(Actor self)
|
||||
{
|
||||
notifyPositionsUpdated = player.PlayerActor.TraitsImplementing<IBotPositionsUpdated>().ToArray();
|
||||
requestUnitProduction = player.PlayerActor.TraitsImplementing<IBotRequestUnitProduction>().ToArray();
|
||||
|
||||
// Avoid all AIs reevaluating assignments on the same tick, randomize their initial evaluation delay.
|
||||
scanInterval = world.LocalRandom.Next(Info.ScanForNewMcvInterval, Info.ScanForNewMcvInterval * 2);
|
||||
}
|
||||
|
||||
void IBotPositionsUpdated.UpdatedBaseCenter(CPos newLocation)
|
||||
{
|
||||
initialBaseCenter = newLocation;
|
||||
}
|
||||
|
||||
void IBotPositionsUpdated.UpdatedDefenseCenter(CPos newLocation) { }
|
||||
|
||||
void IBotTick.BotTick(IBot bot)
|
||||
{
|
||||
ticks++;
|
||||
|
||||
if (ticks == 1)
|
||||
DeployMcvs(bot, false);
|
||||
|
||||
if (--scanInterval <= 0)
|
||||
{
|
||||
scanInterval = Info.ScanForNewMcvInterval;
|
||||
DeployMcvs(bot, true);
|
||||
|
||||
// No construction yards - Build a new MCV
|
||||
if (ShouldBuildMCV())
|
||||
{
|
||||
var unitBuilder = requestUnitProduction.FirstOrDefault(Exts.IsTraitEnabled);
|
||||
if (unitBuilder != null)
|
||||
{
|
||||
var mcvInfo = AIUtils.GetInfoByCommonName(Info.McvTypes, player);
|
||||
unitBuilder.RequestUnitProduction(bot, mcvInfo.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool ShouldBuildMCV()
|
||||
{
|
||||
// Only build MCV if we don't already have one in the field.
|
||||
var allowedToBuildMCV = AIUtils.CountActorByCommonName(Info.McvTypes, player) == 0;
|
||||
if (!allowedToBuildMCV)
|
||||
return false;
|
||||
|
||||
// Build MCV if we don't have the desired number of construction yards, unless we have no factory (can't build it).
|
||||
return AIUtils.CountBuildingByCommonName(Info.ConstructionYardTypes, player) < Info.MinimumConstructionYardCount &&
|
||||
AIUtils.CountBuildingByCommonName(Info.McvFactoryTypes, player) > 0;
|
||||
}
|
||||
|
||||
void DeployMcvs(IBot bot, bool chooseLocation)
|
||||
{
|
||||
activeMCVs.RemoveAll(unitCannotBeOrdered);
|
||||
|
||||
var newMCVs = world.ActorsHavingTrait<Transforms>()
|
||||
.Where(a => a.Owner == player &&
|
||||
a.IsIdle &&
|
||||
Info.McvTypes.Contains(a.Info.Name) &&
|
||||
!activeMCVs.Contains(a));
|
||||
|
||||
foreach (var a in newMCVs)
|
||||
activeMCVs.Add(a);
|
||||
|
||||
foreach (var mcv in activeMCVs)
|
||||
DeployMcv(bot, mcv, chooseLocation);
|
||||
}
|
||||
|
||||
// Find any MCV and deploy them at a sensible location.
|
||||
void DeployMcv(IBot bot, Actor mcv, bool move)
|
||||
{
|
||||
if (move)
|
||||
{
|
||||
// If we lack a base, we need to make sure we don't restrict deployment of the MCV to the base!
|
||||
var restrictToBase = Info.RestrictMCVDeploymentFallbackToBase && AIUtils.CountBuildingByCommonName(Info.ConstructionYardTypes, player) > 0;
|
||||
|
||||
var transformsInfo = mcv.Info.TraitInfo<TransformsInfo>();
|
||||
var desiredLocation = ChooseMcvDeployLocation(transformsInfo.IntoActor, transformsInfo.Offset, restrictToBase);
|
||||
if (desiredLocation == null)
|
||||
return;
|
||||
|
||||
bot.QueueOrder(new Order("Move", mcv, Target.FromCell(world, desiredLocation.Value), true));
|
||||
}
|
||||
|
||||
// If the MCV has to move first, we can't be sure it reaches the destination alive, so we only
|
||||
// update base and defense center if the MCV is deployed immediately (i.e. at game start).
|
||||
// TODO: This could be adressed via INotifyTransform.
|
||||
foreach (var n in notifyPositionsUpdated)
|
||||
{
|
||||
n.UpdatedBaseCenter(mcv.Location);
|
||||
n.UpdatedDefenseCenter(mcv.Location);
|
||||
}
|
||||
|
||||
bot.QueueOrder(new Order("DeployTransform", mcv, true));
|
||||
}
|
||||
|
||||
CPos? ChooseMcvDeployLocation(string actorType, CVec offset, bool distanceToBaseIsImportant)
|
||||
{
|
||||
var actorInfo = world.Map.Rules.Actors[actorType];
|
||||
var bi = actorInfo.TraitInfoOrDefault<BuildingInfo>();
|
||||
if (bi == null)
|
||||
return null;
|
||||
|
||||
// Find the buildable cell that is closest to pos and centered around center
|
||||
Func<CPos, CPos, int, int, CPos?> findPos = (center, target, minRange, maxRange) =>
|
||||
{
|
||||
var cells = world.Map.FindTilesInAnnulus(center, minRange, maxRange);
|
||||
|
||||
// Sort by distance to target if we have one
|
||||
if (center != target)
|
||||
cells = cells.OrderBy(c => (c - target).LengthSquared);
|
||||
else
|
||||
cells = cells.Shuffle(world.LocalRandom);
|
||||
|
||||
foreach (var cell in cells)
|
||||
{
|
||||
if (!world.CanPlaceBuilding(cell + offset, actorInfo, bi, null))
|
||||
continue;
|
||||
|
||||
if (distanceToBaseIsImportant && !bi.IsCloseEnoughToBase(world, player, actorInfo, cell))
|
||||
continue;
|
||||
|
||||
return cell;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
var baseCenter = GetRandomBaseCenter();
|
||||
|
||||
return findPos(baseCenter, baseCenter, Info.MinBaseRadius,
|
||||
distanceToBaseIsImportant ? Info.MaxBaseRadius : world.Map.Grid.MaximumTileSearchRange);
|
||||
}
|
||||
}
|
||||
}
|
||||
355
OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs
Normal file
355
OpenRA.Mods.Common/Traits/BotModules/SquadManagerBotModule.cs
Normal file
@@ -0,0 +1,355 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.Traits.BotModules.Squads;
|
||||
using OpenRA.Support;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
{
|
||||
[Desc("Manages AI squads.")]
|
||||
public class SquadManagerBotModuleInfo : ConditionalTraitInfo
|
||||
{
|
||||
[Desc("Actor types that are valid for naval squads.")]
|
||||
public readonly HashSet<string> NavalUnitsTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Actor types that should generally be excluded from attack squads.")]
|
||||
public readonly HashSet<string> ExcludeFromSquadsTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Actor types that are considered construction yards (base builders).")]
|
||||
public readonly HashSet<string> ConstructionYardTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Enemy building types around which to scan for targets for naval squads.")]
|
||||
public readonly HashSet<string> NavalProductionTypes = new HashSet<string>();
|
||||
|
||||
[Desc("Minimum number of units AI must have before attacking.")]
|
||||
public readonly int SquadSize = 8;
|
||||
|
||||
[Desc("Random number of up to this many units is added to squad size when creating an attack squad.")]
|
||||
public readonly int SquadSizeRandomBonus = 30;
|
||||
|
||||
[Desc("Delay (in ticks) between giving out orders to units.")]
|
||||
public readonly int AssignRolesInterval = 20;
|
||||
|
||||
[Desc("Delay (in ticks) between attempting rush attacks.")]
|
||||
public readonly int RushInterval = 600;
|
||||
|
||||
[Desc("Delay (in ticks) between updating squads.")]
|
||||
public readonly int AttackForceInterval = 30;
|
||||
|
||||
[Desc("Minimum delay (in ticks) between creating squads.")]
|
||||
public readonly int MinimumAttackForceDelay = 0;
|
||||
|
||||
[Desc("Radius in cells around enemy BaseBuilder (Construction Yard) where AI scans for targets to rush.")]
|
||||
public readonly int RushAttackScanRadius = 15;
|
||||
|
||||
[Desc("Radius in cells around the base that should be scanned for units to be protected.")]
|
||||
public readonly int ProtectUnitScanRadius = 15;
|
||||
|
||||
[Desc("Maximum distance in cells from center of the base when checking for MCV deployment location.",
|
||||
"Only applies if RestrictMCVDeploymentFallbackToBase is enabled and there's at least one construction yard.")]
|
||||
public readonly int MaxBaseRadius = 20;
|
||||
|
||||
[Desc("Maximum range at which to scan for enemies when creating protection squads.")]
|
||||
public readonly int MaximumDefenseRadius = 20;
|
||||
|
||||
[Desc("Radius in cells that squads should scan for enemies around their position while idle.")]
|
||||
public readonly int IdleScanRadius = 10;
|
||||
|
||||
[Desc("Radius in cells that squads should scan for danger around their position to make flee decisions.")]
|
||||
public readonly int DangerScanRadius = 10;
|
||||
|
||||
[Desc("Radius in cells that attack squads should scan for enemies around their position when trying to attack.")]
|
||||
public readonly int AttackScanRadius = 12;
|
||||
|
||||
[Desc("Radius in cells that protecting squads should scan for enemies around their position.")]
|
||||
public readonly int ProtectionScanRadius = 8;
|
||||
|
||||
public override object Create(ActorInitializer init) { return new SquadManagerBotModule(init.Self, this); }
|
||||
}
|
||||
|
||||
public class SquadManagerBotModule : ConditionalTrait<SquadManagerBotModuleInfo>, IBotTick, IBotRespondToAttack, IBotPositionsUpdated
|
||||
{
|
||||
public CPos GetRandomBaseCenter()
|
||||
{
|
||||
var randomConstructionYard = World.Actors.Where(a => a.Owner == Player &&
|
||||
Info.ConstructionYardTypes.Contains(a.Info.Name))
|
||||
.RandomOrDefault(World.LocalRandom);
|
||||
|
||||
return randomConstructionYard != null ? randomConstructionYard.Location : initialBaseCenter;
|
||||
}
|
||||
|
||||
public readonly World World;
|
||||
public readonly Player Player;
|
||||
|
||||
readonly Func<Actor, bool> isEnemyUnit;
|
||||
readonly Predicate<Actor> unitCannotBeOrdered;
|
||||
|
||||
public List<Squad> Squads = new List<Squad>();
|
||||
|
||||
IBotPositionsUpdated[] notifyPositionsUpdated;
|
||||
IBotNotifyIdleBaseUnits[] notifyIdleBaseUnits;
|
||||
|
||||
CPos initialBaseCenter;
|
||||
List<Actor> unitsHangingAroundTheBase = new List<Actor>();
|
||||
|
||||
// Units that the bot already knows about. Any unit not on this list needs to be given a role.
|
||||
List<Actor> activeUnits = new List<Actor>();
|
||||
|
||||
int rushTicks;
|
||||
int assignRolesTicks;
|
||||
int attackForceTicks;
|
||||
int minAttackForceDelayTicks;
|
||||
|
||||
public SquadManagerBotModule(Actor self, SquadManagerBotModuleInfo info)
|
||||
: base(info)
|
||||
{
|
||||
World = self.World;
|
||||
Player = self.Owner;
|
||||
|
||||
isEnemyUnit = unit =>
|
||||
Player.Stances[unit.Owner] == Stance.Enemy
|
||||
&& !unit.Info.HasTraitInfo<HuskInfo>()
|
||||
&& unit.Info.HasTraitInfo<ITargetableInfo>();
|
||||
|
||||
unitCannotBeOrdered = a => a.Owner != Player || a.IsDead || !a.IsInWorld;
|
||||
}
|
||||
|
||||
protected override void TraitEnabled(Actor self)
|
||||
{
|
||||
notifyPositionsUpdated = Player.PlayerActor.TraitsImplementing<IBotPositionsUpdated>().ToArray();
|
||||
notifyIdleBaseUnits = Player.PlayerActor.TraitsImplementing<IBotNotifyIdleBaseUnits>().ToArray();
|
||||
|
||||
// Avoid all AIs trying to rush in the same tick, randomize their initial rush a little.
|
||||
var smallFractionOfRushInterval = Info.RushInterval / 20;
|
||||
rushTicks = World.LocalRandom.Next(Info.RushInterval - smallFractionOfRushInterval, Info.RushInterval + smallFractionOfRushInterval);
|
||||
|
||||
// Avoid all AIs reevaluating assignments on the same tick, randomize their initial evaluation delay.
|
||||
assignRolesTicks = World.LocalRandom.Next(0, Info.AssignRolesInterval);
|
||||
attackForceTicks = World.LocalRandom.Next(0, Info.AttackForceInterval);
|
||||
minAttackForceDelayTicks = World.LocalRandom.Next(0, Info.MinimumAttackForceDelay);
|
||||
}
|
||||
|
||||
void IBotTick.BotTick(IBot bot)
|
||||
{
|
||||
AssignRolesToIdleUnits(bot);
|
||||
}
|
||||
|
||||
internal Actor FindClosestEnemy(WPos pos)
|
||||
{
|
||||
return World.Actors.Where(isEnemyUnit).ClosestTo(pos);
|
||||
}
|
||||
|
||||
internal Actor FindClosestEnemy(WPos pos, WDist radius)
|
||||
{
|
||||
return World.FindActorsInCircle(pos, radius).Where(isEnemyUnit).ClosestTo(pos);
|
||||
}
|
||||
|
||||
void CleanSquads()
|
||||
{
|
||||
Squads.RemoveAll(s => !s.IsValid);
|
||||
foreach (var s in Squads)
|
||||
s.Units.RemoveAll(unitCannotBeOrdered);
|
||||
}
|
||||
|
||||
// HACK: Use of this function requires that there is one squad of this type.
|
||||
Squad GetSquadOfType(SquadType type)
|
||||
{
|
||||
return Squads.FirstOrDefault(s => s.Type == type);
|
||||
}
|
||||
|
||||
Squad RegisterNewSquad(IBot bot, SquadType type, Actor target = null)
|
||||
{
|
||||
var ret = new Squad(bot, this, type, target);
|
||||
Squads.Add(ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
void AssignRolesToIdleUnits(IBot bot)
|
||||
{
|
||||
CleanSquads();
|
||||
|
||||
activeUnits.RemoveAll(unitCannotBeOrdered);
|
||||
unitsHangingAroundTheBase.RemoveAll(unitCannotBeOrdered);
|
||||
foreach (var n in notifyIdleBaseUnits)
|
||||
n.UpdatedIdleBaseUnits(unitsHangingAroundTheBase);
|
||||
|
||||
if (--rushTicks <= 0)
|
||||
{
|
||||
rushTicks = Info.RushInterval;
|
||||
TryToRushAttack(bot);
|
||||
}
|
||||
|
||||
if (--attackForceTicks <= 0)
|
||||
{
|
||||
attackForceTicks = Info.AttackForceInterval;
|
||||
foreach (var s in Squads)
|
||||
s.Update();
|
||||
}
|
||||
|
||||
if (--assignRolesTicks <= 0)
|
||||
{
|
||||
assignRolesTicks = Info.AssignRolesInterval;
|
||||
FindNewUnits(bot);
|
||||
}
|
||||
|
||||
if (--minAttackForceDelayTicks <= 0)
|
||||
{
|
||||
minAttackForceDelayTicks = Info.MinimumAttackForceDelay;
|
||||
CreateAttackForce(bot);
|
||||
}
|
||||
}
|
||||
|
||||
void FindNewUnits(IBot bot)
|
||||
{
|
||||
var newUnits = World.ActorsHavingTrait<IPositionable>()
|
||||
.Where(a => a.Owner == Player &&
|
||||
!Info.ExcludeFromSquadsTypes.Contains(a.Info.Name) &&
|
||||
!activeUnits.Contains(a));
|
||||
|
||||
foreach (var a in newUnits)
|
||||
{
|
||||
unitsHangingAroundTheBase.Add(a);
|
||||
|
||||
if (a.Info.HasTraitInfo<AircraftInfo>() && a.Info.HasTraitInfo<AttackBaseInfo>())
|
||||
{
|
||||
var air = GetSquadOfType(SquadType.Air);
|
||||
if (air == null)
|
||||
air = RegisterNewSquad(bot, SquadType.Air);
|
||||
|
||||
air.Units.Add(a);
|
||||
}
|
||||
else if (Info.NavalUnitsTypes.Contains(a.Info.Name))
|
||||
{
|
||||
var ships = GetSquadOfType(SquadType.Naval);
|
||||
if (ships == null)
|
||||
ships = RegisterNewSquad(bot, SquadType.Naval);
|
||||
|
||||
ships.Units.Add(a);
|
||||
}
|
||||
|
||||
activeUnits.Add(a);
|
||||
}
|
||||
|
||||
// Notifying here rather than inside the loop, should be fine and saves a bunch of notification calls
|
||||
foreach (var n in notifyIdleBaseUnits)
|
||||
n.UpdatedIdleBaseUnits(unitsHangingAroundTheBase);
|
||||
}
|
||||
|
||||
void CreateAttackForce(IBot bot)
|
||||
{
|
||||
// Create an attack force when we have enough units around our base.
|
||||
// (don't bother leaving any behind for defense)
|
||||
var randomizedSquadSize = Info.SquadSize + World.LocalRandom.Next(Info.SquadSizeRandomBonus);
|
||||
|
||||
if (unitsHangingAroundTheBase.Count >= randomizedSquadSize)
|
||||
{
|
||||
var attackForce = RegisterNewSquad(bot, SquadType.Assault);
|
||||
|
||||
foreach (var a in unitsHangingAroundTheBase)
|
||||
if (!a.Info.HasTraitInfo<AircraftInfo>())
|
||||
attackForce.Units.Add(a);
|
||||
|
||||
unitsHangingAroundTheBase.Clear();
|
||||
foreach (var n in notifyIdleBaseUnits)
|
||||
n.UpdatedIdleBaseUnits(unitsHangingAroundTheBase);
|
||||
}
|
||||
}
|
||||
|
||||
void TryToRushAttack(IBot bot)
|
||||
{
|
||||
var allEnemyBaseBuilder = AIUtils.FindEnemiesByCommonName(Info.ConstructionYardTypes, Player);
|
||||
|
||||
// TODO: This should use common names & ExcludeFromSquads instead of hardcoding TraitInfo checks
|
||||
var ownUnits = activeUnits
|
||||
.Where(unit => unit.IsIdle && unit.Info.HasTraitInfo<AttackBaseInfo>()
|
||||
&& !unit.Info.HasTraitInfo<AircraftInfo>() && !unit.Info.HasTraitInfo<HarvesterInfo>()).ToList();
|
||||
|
||||
if (!allEnemyBaseBuilder.Any() || ownUnits.Count < Info.SquadSize)
|
||||
return;
|
||||
|
||||
foreach (var b in allEnemyBaseBuilder)
|
||||
{
|
||||
var enemies = World.FindActorsInCircle(b.CenterPosition, WDist.FromCells(Info.RushAttackScanRadius))
|
||||
.Where(unit => Player.Stances[unit.Owner] == Stance.Enemy && unit.Info.HasTraitInfo<AttackBaseInfo>()).ToList();
|
||||
|
||||
if (AttackOrFleeFuzzy.Rush.CanAttack(ownUnits, enemies))
|
||||
{
|
||||
var target = enemies.Any() ? enemies.Random(World.LocalRandom) : b;
|
||||
var rush = GetSquadOfType(SquadType.Rush);
|
||||
if (rush == null)
|
||||
rush = RegisterNewSquad(bot, SquadType.Rush, target);
|
||||
|
||||
foreach (var a3 in ownUnits)
|
||||
rush.Units.Add(a3);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ProtectOwn(IBot bot, Actor attacker)
|
||||
{
|
||||
var protectSq = GetSquadOfType(SquadType.Protection);
|
||||
if (protectSq == null)
|
||||
protectSq = RegisterNewSquad(bot, SquadType.Protection, attacker);
|
||||
|
||||
if (!protectSq.IsTargetValid)
|
||||
protectSq.TargetActor = attacker;
|
||||
|
||||
if (!protectSq.IsValid)
|
||||
{
|
||||
var ownUnits = World.FindActorsInCircle(World.Map.CenterOfCell(GetRandomBaseCenter()), WDist.FromCells(Info.ProtectUnitScanRadius))
|
||||
.Where(unit => unit.Owner == Player && !unit.Info.HasTraitInfo<BuildingInfo>() && !unit.Info.HasTraitInfo<HarvesterInfo>()
|
||||
&& unit.Info.HasTraitInfo<AttackBaseInfo>());
|
||||
|
||||
foreach (var a in ownUnits)
|
||||
protectSq.Units.Add(a);
|
||||
}
|
||||
}
|
||||
|
||||
void IBotPositionsUpdated.UpdatedBaseCenter(CPos newLocation)
|
||||
{
|
||||
initialBaseCenter = newLocation;
|
||||
}
|
||||
|
||||
void IBotPositionsUpdated.UpdatedDefenseCenter(CPos newLocation) { }
|
||||
|
||||
void IBotRespondToAttack.RespondToAttack(IBot bot, Actor self, AttackInfo e)
|
||||
{
|
||||
if (e.Attacker == null)
|
||||
return;
|
||||
|
||||
if (e.Attacker.Disposed)
|
||||
return;
|
||||
|
||||
if (e.Attacker.Owner.Stances[self.Owner] != Stance.Enemy)
|
||||
return;
|
||||
|
||||
if (!e.Attacker.Info.HasTraitInfo<ITargetableInfo>())
|
||||
return;
|
||||
|
||||
// Protected priority assets, MCVs, harvesters and buildings
|
||||
// TODO: Use *CommonNames, instead of hard-coding trait(info)s.
|
||||
if (self.Info.HasTraitInfo<HarvesterInfo>() || self.Info.HasTraitInfo<BuildingInfo>() || self.Info.HasTraitInfo<BaseBuildingInfo>())
|
||||
{
|
||||
foreach (var n in notifyPositionsUpdated)
|
||||
n.UpdatedDefenseCenter(e.Attacker.Location);
|
||||
|
||||
ProtectOwn(bot, e.Attacker);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
275
OpenRA.Mods.Common/Traits/BotModules/Squads/AttackOrFleeFuzzy.cs
Normal file
275
OpenRA.Mods.Common/Traits/BotModules/Squads/AttackOrFleeFuzzy.cs
Normal file
@@ -0,0 +1,275 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using AI.Fuzzy.Library;
|
||||
using OpenRA.Mods.Common.Warheads;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
sealed class AttackOrFleeFuzzy
|
||||
{
|
||||
static readonly string[] DefaultRulesNormalOwnHealth = new[]
|
||||
{
|
||||
"if ((OwnHealth is Normal) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and ((RelativeAttackPower is Weak) or (RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Attack"
|
||||
};
|
||||
|
||||
static readonly string[] DefaultRulesInjuredOwnHealth = new[]
|
||||
{
|
||||
"if ((OwnHealth is Injured) " +
|
||||
"and (EnemyHealth is NearDead) " +
|
||||
"and ((RelativeAttackPower is Weak) or (RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Attack",
|
||||
|
||||
"if ((OwnHealth is Injured) " +
|
||||
"and ((EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and ((RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Attack",
|
||||
|
||||
"if ((OwnHealth is Injured) " +
|
||||
"and ((EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and (RelativeAttackPower is Weak) " +
|
||||
"and (RelativeSpeed is Slow)) " +
|
||||
"then AttackOrFlee is Attack",
|
||||
|
||||
"if ((OwnHealth is Injured) " +
|
||||
"and ((EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and (RelativeAttackPower is Weak) " +
|
||||
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Flee",
|
||||
|
||||
"if ((OwnHealth is Injured) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and ((RelativeAttackPower is Weak) or (RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and (RelativeSpeed is Slow)) " +
|
||||
"then AttackOrFlee is Attack"
|
||||
};
|
||||
|
||||
static readonly string[] DefaultRulesNearDeadOwnHealth = new[]
|
||||
{
|
||||
"if ((OwnHealth is NearDead) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured)) " +
|
||||
"and ((RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal))) " +
|
||||
"then AttackOrFlee is Attack",
|
||||
|
||||
"if ((OwnHealth is NearDead) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured)) " +
|
||||
"and (RelativeAttackPower is Weak) " +
|
||||
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Flee",
|
||||
|
||||
"if ((OwnHealth is NearDead) " +
|
||||
"and (EnemyHealth is Normal) " +
|
||||
"and (RelativeAttackPower is Weak) " +
|
||||
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Flee",
|
||||
|
||||
"if (OwnHealth is NearDead) " +
|
||||
"and (EnemyHealth is Normal) " +
|
||||
"and ((RelativeAttackPower is Equal) or (RelativeAttackPower is Strong)) " +
|
||||
"and (RelativeSpeed is Fast) " +
|
||||
"then AttackOrFlee is Flee",
|
||||
|
||||
"if (OwnHealth is NearDead) " +
|
||||
"and (EnemyHealth is Injured) " +
|
||||
"and (RelativeAttackPower is Equal) " +
|
||||
"and (RelativeSpeed is Fast) " +
|
||||
"then AttackOrFlee is Flee"
|
||||
};
|
||||
|
||||
public static readonly AttackOrFleeFuzzy Default = new AttackOrFleeFuzzy(null, null, null);
|
||||
public static readonly AttackOrFleeFuzzy Rush = new AttackOrFleeFuzzy(new[]
|
||||
{
|
||||
"if ((OwnHealth is Normal) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and (RelativeAttackPower is Strong) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Attack",
|
||||
|
||||
"if ((OwnHealth is Normal) " +
|
||||
"and ((EnemyHealth is NearDead) or (EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
|
||||
"and ((RelativeAttackPower is Weak) or (RelativeAttackPower is Equal)) " +
|
||||
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
|
||||
"then AttackOrFlee is Flee"
|
||||
}, null, null);
|
||||
|
||||
readonly MamdaniFuzzySystem fuzzyEngine = new MamdaniFuzzySystem();
|
||||
|
||||
public AttackOrFleeFuzzy(
|
||||
IEnumerable<string> rulesForNormalOwnHealth,
|
||||
IEnumerable<string> rulesForInjuredOwnHealth,
|
||||
IEnumerable<string> rulesForNeadDeadOwnHealth)
|
||||
{
|
||||
lock (fuzzyEngine)
|
||||
{
|
||||
var playerHealthFuzzy = new FuzzyVariable("OwnHealth", 0.0, 100.0);
|
||||
playerHealthFuzzy.Terms.Add(new FuzzyTerm("NearDead", new TrapezoidMembershipFunction(0, 0, 20, 40)));
|
||||
playerHealthFuzzy.Terms.Add(new FuzzyTerm("Injured", new TrapezoidMembershipFunction(30, 50, 50, 70)));
|
||||
playerHealthFuzzy.Terms.Add(new FuzzyTerm("Normal", new TrapezoidMembershipFunction(50, 80, 100, 100)));
|
||||
fuzzyEngine.Input.Add(playerHealthFuzzy);
|
||||
|
||||
var enemyHealthFuzzy = new FuzzyVariable("EnemyHealth", 0.0, 100.0);
|
||||
enemyHealthFuzzy.Terms.Add(new FuzzyTerm("NearDead", new TrapezoidMembershipFunction(0, 0, 20, 40)));
|
||||
enemyHealthFuzzy.Terms.Add(new FuzzyTerm("Injured", new TrapezoidMembershipFunction(30, 50, 50, 70)));
|
||||
enemyHealthFuzzy.Terms.Add(new FuzzyTerm("Normal", new TrapezoidMembershipFunction(50, 80, 100, 100)));
|
||||
fuzzyEngine.Input.Add(enemyHealthFuzzy);
|
||||
|
||||
var relativeAttackPowerFuzzy = new FuzzyVariable("RelativeAttackPower", 0.0, 1000.0);
|
||||
relativeAttackPowerFuzzy.Terms.Add(new FuzzyTerm("Weak", new TrapezoidMembershipFunction(0, 0, 70, 90)));
|
||||
relativeAttackPowerFuzzy.Terms.Add(new FuzzyTerm("Equal", new TrapezoidMembershipFunction(85, 100, 100, 115)));
|
||||
relativeAttackPowerFuzzy.Terms.Add(new FuzzyTerm("Strong", new TrapezoidMembershipFunction(110, 150, 150, 1000)));
|
||||
fuzzyEngine.Input.Add(relativeAttackPowerFuzzy);
|
||||
|
||||
var relativeSpeedFuzzy = new FuzzyVariable("RelativeSpeed", 0.0, 1000.0);
|
||||
relativeSpeedFuzzy.Terms.Add(new FuzzyTerm("Slow", new TrapezoidMembershipFunction(0, 0, 70, 90)));
|
||||
relativeSpeedFuzzy.Terms.Add(new FuzzyTerm("Equal", new TrapezoidMembershipFunction(85, 100, 100, 115)));
|
||||
relativeSpeedFuzzy.Terms.Add(new FuzzyTerm("Fast", new TrapezoidMembershipFunction(110, 150, 150, 1000)));
|
||||
fuzzyEngine.Input.Add(relativeSpeedFuzzy);
|
||||
|
||||
var attackOrFleeFuzzy = new FuzzyVariable("AttackOrFlee", 0.0, 50.0);
|
||||
attackOrFleeFuzzy.Terms.Add(new FuzzyTerm("Attack", new TrapezoidMembershipFunction(0, 15, 15, 30)));
|
||||
attackOrFleeFuzzy.Terms.Add(new FuzzyTerm("Flee", new TrapezoidMembershipFunction(25, 35, 35, 50)));
|
||||
fuzzyEngine.Output.Add(attackOrFleeFuzzy);
|
||||
|
||||
foreach (var rule in rulesForNormalOwnHealth ?? DefaultRulesNormalOwnHealth)
|
||||
AddFuzzyRule(rule);
|
||||
foreach (var rule in rulesForInjuredOwnHealth ?? DefaultRulesInjuredOwnHealth)
|
||||
AddFuzzyRule(rule);
|
||||
foreach (var rule in rulesForNeadDeadOwnHealth ?? DefaultRulesNearDeadOwnHealth)
|
||||
AddFuzzyRule(rule);
|
||||
}
|
||||
}
|
||||
|
||||
void AddFuzzyRule(string rule)
|
||||
{
|
||||
fuzzyEngine.Rules.Add(fuzzyEngine.ParseRule(rule));
|
||||
}
|
||||
|
||||
public bool CanAttack(IEnumerable<Actor> ownUnits, IEnumerable<Actor> enemyUnits)
|
||||
{
|
||||
double attackChance;
|
||||
var inputValues = new Dictionary<FuzzyVariable, double>();
|
||||
lock (fuzzyEngine)
|
||||
{
|
||||
inputValues.Add(fuzzyEngine.InputByName("OwnHealth"), NormalizedHealth(ownUnits, 100));
|
||||
inputValues.Add(fuzzyEngine.InputByName("EnemyHealth"), NormalizedHealth(enemyUnits, 100));
|
||||
inputValues.Add(fuzzyEngine.InputByName("RelativeAttackPower"), RelativePower(ownUnits, enemyUnits));
|
||||
inputValues.Add(fuzzyEngine.InputByName("RelativeSpeed"), RelativeSpeed(ownUnits, enemyUnits));
|
||||
|
||||
var result = fuzzyEngine.Calculate(inputValues);
|
||||
attackChance = result[fuzzyEngine.OutputByName("AttackOrFlee")];
|
||||
}
|
||||
|
||||
return !double.IsNaN(attackChance) && attackChance < 30.0;
|
||||
}
|
||||
|
||||
static float NormalizedHealth(IEnumerable<Actor> actors, float normalizeByValue)
|
||||
{
|
||||
var sumOfMaxHp = 0;
|
||||
var sumOfHp = 0;
|
||||
foreach (var a in actors)
|
||||
{
|
||||
if (a.Info.HasTraitInfo<IHealthInfo>())
|
||||
{
|
||||
sumOfMaxHp += a.Trait<IHealth>().MaxHP;
|
||||
sumOfHp += a.Trait<IHealth>().HP;
|
||||
}
|
||||
}
|
||||
|
||||
if (sumOfMaxHp == 0)
|
||||
return 0.0f;
|
||||
|
||||
// Cast to long to avoid overflow when multiplying by the health
|
||||
return (int)((long)sumOfHp * normalizeByValue / sumOfMaxHp);
|
||||
}
|
||||
|
||||
static float RelativePower(IEnumerable<Actor> own, IEnumerable<Actor> enemy)
|
||||
{
|
||||
return RelativeValue(own, enemy, 100, SumOfValues<AttackBaseInfo>, a =>
|
||||
{
|
||||
var sumOfDamage = 0;
|
||||
var arms = a.TraitsImplementing<Armament>();
|
||||
foreach (var arm in arms)
|
||||
{
|
||||
var burst = arm.Weapon.Burst;
|
||||
|
||||
// For simplicity's sake, we're only factoring in the first burst delay, as more than one burst delay is extremely rare.
|
||||
// Additionally, clamping total delay to minimum of 1 (ReloadDelay: 0 is technically possible) and maximum of 200.
|
||||
// High dmg/low ROF weapons shouldn't be rated too low as high dmg/shot can outweigh mere dps due to likelier 1-hit-kills.
|
||||
// TODO: Revisit this at some point to replace the arbitrary cap with something smarter.
|
||||
var totalReloadDelay = arm.Weapon.ReloadDelay + (arm.Weapon.BurstDelays[0] * (burst - 1)).Clamp(1, 200);
|
||||
var damageWarheads = arm.Weapon.Warheads.OfType<DamageWarhead>();
|
||||
foreach (var warhead in damageWarheads)
|
||||
sumOfDamage += (warhead.Damage * burst / totalReloadDelay) * 100;
|
||||
}
|
||||
|
||||
return sumOfDamage;
|
||||
});
|
||||
}
|
||||
|
||||
static float RelativeSpeed(IEnumerable<Actor> own, IEnumerable<Actor> enemy)
|
||||
{
|
||||
return RelativeValue(own, enemy, 100, Average<MobileInfo>, (Actor a) => a.Info.TraitInfo<MobileInfo>().Speed);
|
||||
}
|
||||
|
||||
static float RelativeValue(IEnumerable<Actor> own, IEnumerable<Actor> enemy, float normalizeByValue,
|
||||
Func<IEnumerable<Actor>, Func<Actor, int>, float> relativeFunc, Func<Actor, int> getValue)
|
||||
{
|
||||
if (!enemy.Any())
|
||||
return 999.0f;
|
||||
|
||||
if (!own.Any())
|
||||
return 0.0f;
|
||||
|
||||
var relative = (relativeFunc(own, getValue) / relativeFunc(enemy, getValue)) * normalizeByValue;
|
||||
return relative.Clamp(0.0f, 999.0f);
|
||||
}
|
||||
|
||||
static float SumOfValues<TTraitInfo>(IEnumerable<Actor> actors, Func<Actor, int> getValue) where TTraitInfo : ITraitInfo
|
||||
{
|
||||
var sum = 0;
|
||||
foreach (var a in actors)
|
||||
if (a.Info.HasTraitInfo<TTraitInfo>())
|
||||
sum += getValue(a);
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
static float Average<TTraitInfo>(IEnumerable<Actor> actors, Func<Actor, int> getValue) where TTraitInfo : ITraitInfo
|
||||
{
|
||||
var sum = 0;
|
||||
var countActors = 0;
|
||||
foreach (var a in actors)
|
||||
{
|
||||
if (a.Info.HasTraitInfo<TTraitInfo>())
|
||||
{
|
||||
sum += getValue(a);
|
||||
countActors++;
|
||||
}
|
||||
}
|
||||
|
||||
if (countActors == 0)
|
||||
return 0.0f;
|
||||
|
||||
return sum / countActors;
|
||||
}
|
||||
}
|
||||
}
|
||||
90
OpenRA.Mods.Common/Traits/BotModules/Squads/Squad.cs
Normal file
90
OpenRA.Mods.Common/Traits/BotModules/Squads/Squad.cs
Normal file
@@ -0,0 +1,90 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Support;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
public enum SquadType { Assault, Air, Rush, Protection, Naval }
|
||||
|
||||
public class Squad
|
||||
{
|
||||
public List<Actor> Units = new List<Actor>();
|
||||
public SquadType Type;
|
||||
|
||||
internal IBot Bot;
|
||||
internal World World;
|
||||
internal SquadManagerBotModule SquadManager;
|
||||
internal MersenneTwister Random;
|
||||
|
||||
internal Target Target;
|
||||
internal StateMachine FuzzyStateMachine;
|
||||
|
||||
public Squad(IBot bot, SquadManagerBotModule squadManager, SquadType type) : this(bot, squadManager, type, null) { }
|
||||
|
||||
public Squad(IBot bot, SquadManagerBotModule squadManager, SquadType type, Actor target)
|
||||
{
|
||||
Bot = bot;
|
||||
SquadManager = squadManager;
|
||||
World = bot.Player.PlayerActor.World;
|
||||
Random = World.LocalRandom;
|
||||
Type = type;
|
||||
Target = Target.FromActor(target);
|
||||
FuzzyStateMachine = new StateMachine();
|
||||
|
||||
switch (type)
|
||||
{
|
||||
case SquadType.Assault:
|
||||
case SquadType.Rush:
|
||||
FuzzyStateMachine.ChangeState(this, new GroundUnitsIdleState(), true);
|
||||
break;
|
||||
case SquadType.Air:
|
||||
FuzzyStateMachine.ChangeState(this, new AirIdleState(), true);
|
||||
break;
|
||||
case SquadType.Protection:
|
||||
FuzzyStateMachine.ChangeState(this, new UnitsForProtectionIdleState(), true);
|
||||
break;
|
||||
case SquadType.Naval:
|
||||
FuzzyStateMachine.ChangeState(this, new NavyUnitsIdleState(), true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void Update()
|
||||
{
|
||||
if (IsValid)
|
||||
FuzzyStateMachine.Update(this);
|
||||
}
|
||||
|
||||
public bool IsValid { get { return Units.Any(); } }
|
||||
|
||||
public Actor TargetActor
|
||||
{
|
||||
get { return Target.Actor; }
|
||||
set { Target = Target.FromActor(value); }
|
||||
}
|
||||
|
||||
public bool IsTargetValid
|
||||
{
|
||||
get { return Target.IsValidFor(Units.FirstOrDefault()) && !Target.Actor.Info.HasTraitInfo<HuskInfo>(); }
|
||||
}
|
||||
|
||||
public bool IsTargetVisible
|
||||
{
|
||||
get { return TargetActor.CanBeViewedByPlayer(Bot.Player); }
|
||||
}
|
||||
|
||||
public WPos CenterPosition { get { return Units.Select(u => u.CenterPosition).Average(); } }
|
||||
}
|
||||
}
|
||||
52
OpenRA.Mods.Common/Traits/BotModules/Squads/StateMachine.cs
Normal file
52
OpenRA.Mods.Common/Traits/BotModules/Squads/StateMachine.cs
Normal file
@@ -0,0 +1,52 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
class StateMachine
|
||||
{
|
||||
IState currentState;
|
||||
IState previousState;
|
||||
|
||||
public void Update(Squad squad)
|
||||
{
|
||||
if (currentState != null)
|
||||
currentState.Tick(squad);
|
||||
}
|
||||
|
||||
public void ChangeState(Squad squad, IState newState, bool rememberPrevious)
|
||||
{
|
||||
if (rememberPrevious)
|
||||
previousState = currentState;
|
||||
|
||||
if (currentState != null)
|
||||
currentState.Deactivate(squad);
|
||||
|
||||
if (newState != null)
|
||||
currentState = newState;
|
||||
|
||||
if (currentState != null)
|
||||
currentState.Activate(squad);
|
||||
}
|
||||
|
||||
public void RevertToPreviousState(Squad squad, bool saveCurrentState)
|
||||
{
|
||||
ChangeState(squad, previousState, saveCurrentState);
|
||||
}
|
||||
}
|
||||
|
||||
interface IState
|
||||
{
|
||||
void Activate(Squad bot);
|
||||
void Tick(Squad bot);
|
||||
void Deactivate(Squad bot);
|
||||
}
|
||||
}
|
||||
271
OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs
Normal file
271
OpenRA.Mods.Common/Traits/BotModules/Squads/States/AirStates.cs
Normal file
@@ -0,0 +1,271 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.Activities;
|
||||
using OpenRA.Primitives;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
abstract class AirStateBase : StateBase
|
||||
{
|
||||
static readonly BitSet<TargetableType> AirTargetTypes = new BitSet<TargetableType>("Air");
|
||||
|
||||
protected const int MissileUnitMultiplier = 3;
|
||||
|
||||
protected static int CountAntiAirUnits(IEnumerable<Actor> units)
|
||||
{
|
||||
if (!units.Any())
|
||||
return 0;
|
||||
|
||||
var missileUnitsCount = 0;
|
||||
foreach (var unit in units)
|
||||
{
|
||||
if (unit == null || unit.Info.HasTraitInfo<AircraftInfo>())
|
||||
continue;
|
||||
|
||||
foreach (var ab in unit.TraitsImplementing<AttackBase>())
|
||||
{
|
||||
if (ab.IsTraitDisabled || ab.IsTraitPaused)
|
||||
continue;
|
||||
|
||||
foreach (var a in ab.Armaments)
|
||||
{
|
||||
if (a.Weapon.IsValidTarget(AirTargetTypes))
|
||||
{
|
||||
missileUnitsCount++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return missileUnitsCount;
|
||||
}
|
||||
|
||||
protected static Actor FindDefenselessTarget(Squad owner)
|
||||
{
|
||||
Actor target = null;
|
||||
FindSafePlace(owner, out target, true);
|
||||
return target;
|
||||
}
|
||||
|
||||
protected static CPos? FindSafePlace(Squad owner, out Actor detectedEnemyTarget, bool needTarget)
|
||||
{
|
||||
var map = owner.World.Map;
|
||||
var dangerRadius = owner.SquadManager.Info.DangerScanRadius;
|
||||
detectedEnemyTarget = null;
|
||||
var x = (map.MapSize.X % dangerRadius) == 0 ? map.MapSize.X : map.MapSize.X + dangerRadius;
|
||||
var y = (map.MapSize.Y % dangerRadius) == 0 ? map.MapSize.Y : map.MapSize.Y + dangerRadius;
|
||||
|
||||
for (var i = 0; i < x; i += dangerRadius * 2)
|
||||
{
|
||||
for (var j = 0; j < y; j += dangerRadius * 2)
|
||||
{
|
||||
var pos = new CPos(i, j);
|
||||
if (NearToPosSafely(owner, map.CenterOfCell(pos), out detectedEnemyTarget))
|
||||
{
|
||||
if (needTarget && detectedEnemyTarget == null)
|
||||
continue;
|
||||
|
||||
return pos;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
protected static bool NearToPosSafely(Squad owner, WPos loc)
|
||||
{
|
||||
Actor a;
|
||||
return NearToPosSafely(owner, loc, out a);
|
||||
}
|
||||
|
||||
protected static bool NearToPosSafely(Squad owner, WPos loc, out Actor detectedEnemyTarget)
|
||||
{
|
||||
detectedEnemyTarget = null;
|
||||
var dangerRadius = owner.SquadManager.Info.DangerScanRadius;
|
||||
var unitsAroundPos = owner.World.FindActorsInCircle(loc, WDist.FromCells(dangerRadius))
|
||||
.Where(unit => owner.Bot.Player.Stances[unit.Owner] == Stance.Enemy).ToList();
|
||||
|
||||
if (!unitsAroundPos.Any())
|
||||
return true;
|
||||
|
||||
if (CountAntiAirUnits(unitsAroundPos) * MissileUnitMultiplier < owner.Units.Count)
|
||||
{
|
||||
detectedEnemyTarget = unitsAroundPos.Random(owner.Random);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected static bool FullAmmo(Actor a)
|
||||
{
|
||||
var ammoPools = a.TraitsImplementing<AmmoPool>();
|
||||
return ammoPools.All(x => x.FullAmmo());
|
||||
}
|
||||
|
||||
protected static bool HasAmmo(Actor a)
|
||||
{
|
||||
var ammoPools = a.TraitsImplementing<AmmoPool>();
|
||||
return ammoPools.All(x => x.HasAmmo());
|
||||
}
|
||||
|
||||
protected static bool ReloadsAutomatically(Actor a)
|
||||
{
|
||||
var ammoPools = a.TraitsImplementing<AmmoPool>();
|
||||
var rearmable = a.TraitOrDefault<Rearmable>();
|
||||
if (rearmable == null)
|
||||
return true;
|
||||
|
||||
return ammoPools.All(ap => !rearmable.Info.AmmoPools.Contains(ap.Info.Name));
|
||||
}
|
||||
|
||||
protected static bool IsRearm(Actor a)
|
||||
{
|
||||
if (a.IsIdle)
|
||||
return false;
|
||||
|
||||
var activity = a.CurrentActivity;
|
||||
var type = activity.GetType();
|
||||
if (type == typeof(Rearm) || type == typeof(ResupplyAircraft))
|
||||
return true;
|
||||
|
||||
var next = activity.NextActivity;
|
||||
if (next == null)
|
||||
return false;
|
||||
|
||||
var nextType = next.GetType();
|
||||
if (nextType == typeof(Rearm) || nextType == typeof(ResupplyAircraft))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Checks the number of anti air enemies around units
|
||||
protected virtual bool ShouldFlee(Squad owner)
|
||||
{
|
||||
return base.ShouldFlee(owner, enemies => CountAntiAirUnits(enemies) * MissileUnitMultiplier > owner.Units.Count);
|
||||
}
|
||||
}
|
||||
|
||||
class AirIdleState : AirStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (ShouldFlee(owner))
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new AirFleeState(), true);
|
||||
return;
|
||||
}
|
||||
|
||||
var e = FindDefenselessTarget(owner);
|
||||
if (e == null)
|
||||
return;
|
||||
|
||||
owner.TargetActor = e;
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new AirAttackState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class AirAttackState : AirStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var a = owner.Units.Random(owner.Random);
|
||||
var closestEnemy = owner.SquadManager.FindClosestEnemy(a.CenterPosition);
|
||||
if (closestEnemy != null)
|
||||
owner.TargetActor = closestEnemy;
|
||||
else
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new AirFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!NearToPosSafely(owner, owner.TargetActor.CenterPosition))
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new AirFleeState(), true);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var a in owner.Units)
|
||||
{
|
||||
if (BusyAttack(a))
|
||||
continue;
|
||||
|
||||
if (!ReloadsAutomatically(a))
|
||||
{
|
||||
if (IsRearm(a))
|
||||
continue;
|
||||
|
||||
if (!HasAmmo(a))
|
||||
{
|
||||
owner.Bot.QueueOrder(new Order("ReturnToBase", a, false));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (CanAttackTarget(a, owner.TargetActor))
|
||||
owner.Bot.QueueOrder(new Order("Attack", a, Target.FromActor(owner.TargetActor), false));
|
||||
}
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class AirFleeState : AirStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
foreach (var a in owner.Units)
|
||||
{
|
||||
if (!ReloadsAutomatically(a) && !FullAmmo(a))
|
||||
{
|
||||
if (IsRearm(a))
|
||||
continue;
|
||||
|
||||
owner.Bot.QueueOrder(new Order("ReturnToBase", a, false));
|
||||
continue;
|
||||
}
|
||||
|
||||
owner.Bot.QueueOrder(new Order("Move", a, Target.FromCell(owner.World, RandomBuildingLocation(owner)), false));
|
||||
}
|
||||
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new AirIdleState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System.Linq;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
abstract class GroundStateBase : StateBase
|
||||
{
|
||||
protected virtual bool ShouldFlee(Squad owner)
|
||||
{
|
||||
return base.ShouldFlee(owner, enemies => !AttackOrFleeFuzzy.Default.CanAttack(owner.Units, enemies));
|
||||
}
|
||||
|
||||
protected Actor FindClosestEnemy(Squad owner)
|
||||
{
|
||||
return owner.SquadManager.FindClosestEnemy(owner.Units.First().CenterPosition);
|
||||
}
|
||||
}
|
||||
|
||||
class GroundUnitsIdleState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy == null)
|
||||
return;
|
||||
|
||||
owner.TargetActor = closestEnemy;
|
||||
}
|
||||
|
||||
var enemyUnits = owner.World.FindActorsInCircle(owner.TargetActor.CenterPosition, WDist.FromCells(owner.SquadManager.Info.IdleScanRadius))
|
||||
.Where(unit => owner.Bot.Player.Stances[unit.Owner] == Stance.Enemy).ToList();
|
||||
|
||||
if (enemyUnits.Count == 0)
|
||||
return;
|
||||
|
||||
if (AttackOrFleeFuzzy.Default.CanAttack(owner.Units, enemyUnits))
|
||||
{
|
||||
foreach (var u in owner.Units)
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", u, Target.FromCell(owner.World, owner.TargetActor.Location), false));
|
||||
|
||||
// We have gathered sufficient units. Attack the nearest enemy unit.
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsAttackMoveState(), true);
|
||||
}
|
||||
else
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class GroundUnitsAttackMoveState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy != null)
|
||||
owner.TargetActor = closestEnemy;
|
||||
else
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var leader = owner.Units.ClosestTo(owner.TargetActor.CenterPosition);
|
||||
if (leader == null)
|
||||
return;
|
||||
|
||||
var ownUnits = owner.World.FindActorsInCircle(leader.CenterPosition, WDist.FromCells(owner.Units.Count) / 3)
|
||||
.Where(a => a.Owner == owner.Units.First().Owner && owner.Units.Contains(a)).ToHashSet();
|
||||
|
||||
if (ownUnits.Count < owner.Units.Count)
|
||||
{
|
||||
// Since units have different movement speeds, they get separated while approaching the target.
|
||||
// Let them regroup into tighter formation.
|
||||
owner.Bot.QueueOrder(new Order("Stop", leader, false));
|
||||
foreach (var unit in owner.Units.Where(a => !ownUnits.Contains(a)))
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", unit, Target.FromCell(owner.World, leader.Location), false));
|
||||
}
|
||||
else
|
||||
{
|
||||
var enemies = owner.World.FindActorsInCircle(leader.CenterPosition, WDist.FromCells(owner.SquadManager.Info.AttackScanRadius))
|
||||
.Where(a => !a.IsDead && leader.Owner.Stances[a.Owner] == Stance.Enemy && !a.GetEnabledTargetTypes().IsEmpty);
|
||||
var target = enemies.ClosestTo(leader.CenterPosition);
|
||||
if (target != null)
|
||||
{
|
||||
owner.TargetActor = target;
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsAttackState(), true);
|
||||
}
|
||||
else
|
||||
foreach (var a in owner.Units)
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", a, Target.FromCell(owner.World, owner.TargetActor.Location), false));
|
||||
}
|
||||
|
||||
if (ShouldFlee(owner))
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class GroundUnitsAttackState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy != null)
|
||||
owner.TargetActor = closestEnemy;
|
||||
else
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var a in owner.Units)
|
||||
if (!BusyAttack(a))
|
||||
owner.Bot.QueueOrder(new Order("Attack", a, Target.FromActor(owner.TargetActor), false));
|
||||
|
||||
if (ShouldFlee(owner))
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class GroundUnitsFleeState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
GoToRandomOwnBuilding(owner);
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsIdleState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { owner.Units.Clear(); }
|
||||
}
|
||||
}
|
||||
199
OpenRA.Mods.Common/Traits/BotModules/Squads/States/NavyStates.cs
Normal file
199
OpenRA.Mods.Common/Traits/BotModules/Squads/States/NavyStates.cs
Normal file
@@ -0,0 +1,199 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System.Linq;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
abstract class NavyStateBase : StateBase
|
||||
{
|
||||
protected virtual bool ShouldFlee(Squad owner)
|
||||
{
|
||||
return base.ShouldFlee(owner, enemies => !AttackOrFleeFuzzy.Default.CanAttack(owner.Units, enemies));
|
||||
}
|
||||
|
||||
protected Actor FindClosestEnemy(Squad owner)
|
||||
{
|
||||
var first = owner.Units.First();
|
||||
|
||||
// Navy squad AI can exploit enemy naval production to find path, if any.
|
||||
// (Way better than finding a nearest target which is likely to be on Ground)
|
||||
// You might be tempted to move these lookups into Activate() but that causes null reference exception.
|
||||
var domainIndex = first.World.WorldActor.Trait<DomainIndex>();
|
||||
var locomotorInfo = first.Info.TraitInfo<MobileInfo>().LocomotorInfo;
|
||||
|
||||
var navalProductions = owner.World.ActorsHavingTrait<Building>().Where(a
|
||||
=> owner.SquadManager.Info.NavalProductionTypes.Contains(a.Info.Name)
|
||||
&& domainIndex.IsPassable(first.Location, a.Location, locomotorInfo)
|
||||
&& a.AppearsHostileTo(first));
|
||||
|
||||
if (navalProductions.Any())
|
||||
{
|
||||
var nearest = navalProductions.ClosestTo(first);
|
||||
|
||||
// Return nearest when it is FAR enough.
|
||||
// If the naval production is within MaxBaseRadius, it implies that
|
||||
// this squad is close to enemy territory and they should expect a naval combat;
|
||||
// closest enemy makes more sense in that case.
|
||||
if ((nearest.Location - first.Location).LengthSquared > owner.SquadManager.Info.MaxBaseRadius * owner.SquadManager.Info.MaxBaseRadius)
|
||||
return nearest;
|
||||
}
|
||||
|
||||
return owner.SquadManager.FindClosestEnemy(first.CenterPosition);
|
||||
}
|
||||
}
|
||||
|
||||
class NavyUnitsIdleState : NavyStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy == null)
|
||||
return;
|
||||
|
||||
owner.TargetActor = closestEnemy;
|
||||
}
|
||||
|
||||
var enemyUnits = owner.World.FindActorsInCircle(owner.TargetActor.CenterPosition, WDist.FromCells(owner.SquadManager.Info.IdleScanRadius))
|
||||
.Where(unit => owner.Bot.Player.Stances[unit.Owner] == Stance.Enemy).ToList();
|
||||
|
||||
if (enemyUnits.Count == 0)
|
||||
return;
|
||||
|
||||
if (AttackOrFleeFuzzy.Default.CanAttack(owner.Units, enemyUnits))
|
||||
{
|
||||
foreach (var u in owner.Units)
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", u, Target.FromCell(owner.World, owner.TargetActor.Location), false));
|
||||
|
||||
// We have gathered sufficient units. Attack the nearest enemy unit.
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsAttackMoveState(), true);
|
||||
}
|
||||
else
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class NavyUnitsAttackMoveState : NavyStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy != null)
|
||||
owner.TargetActor = closestEnemy;
|
||||
else
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var leader = owner.Units.ClosestTo(owner.TargetActor.CenterPosition);
|
||||
if (leader == null)
|
||||
return;
|
||||
|
||||
var ownUnits = owner.World.FindActorsInCircle(leader.CenterPosition, WDist.FromCells(owner.Units.Count) / 3)
|
||||
.Where(a => a.Owner == owner.Units.First().Owner && owner.Units.Contains(a)).ToHashSet();
|
||||
|
||||
if (ownUnits.Count < owner.Units.Count)
|
||||
{
|
||||
// Since units have different movement speeds, they get separated while approaching the target.
|
||||
// Let them regroup into tighter formation.
|
||||
owner.Bot.QueueOrder(new Order("Stop", leader, false));
|
||||
foreach (var unit in owner.Units.Where(a => !ownUnits.Contains(a)))
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", unit, Target.FromCell(owner.World, leader.Location), false));
|
||||
}
|
||||
else
|
||||
{
|
||||
var enemies = owner.World.FindActorsInCircle(leader.CenterPosition, WDist.FromCells(owner.SquadManager.Info.AttackScanRadius))
|
||||
.Where(a => !a.IsDead && leader.Owner.Stances[a.Owner] == Stance.Enemy && !a.GetEnabledTargetTypes().IsEmpty);
|
||||
var target = enemies.ClosestTo(leader.CenterPosition);
|
||||
if (target != null)
|
||||
{
|
||||
owner.TargetActor = target;
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsAttackState(), true);
|
||||
}
|
||||
else
|
||||
foreach (var a in owner.Units)
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", a, Target.FromCell(owner.World, owner.TargetActor.Location), false));
|
||||
}
|
||||
|
||||
if (ShouldFlee(owner))
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class NavyUnitsAttackState : NavyStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
var closestEnemy = FindClosestEnemy(owner);
|
||||
if (closestEnemy != null)
|
||||
owner.TargetActor = closestEnemy;
|
||||
else
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var a in owner.Units)
|
||||
if (!BusyAttack(a))
|
||||
owner.Bot.QueueOrder(new Order("Attack", a, Target.FromActor(owner.TargetActor), false));
|
||||
|
||||
if (ShouldFlee(owner))
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsFleeState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class NavyUnitsFleeState : NavyStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
GoToRandomOwnBuilding(owner);
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new NavyUnitsIdleState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { owner.Units.Clear(); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
class UnitsForProtectionIdleState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
public void Tick(Squad owner) { owner.FuzzyStateMachine.ChangeState(owner, new UnitsForProtectionAttackState(), true); }
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class UnitsForProtectionAttackState : GroundStateBase, IState
|
||||
{
|
||||
public const int BackoffTicks = 4;
|
||||
internal int Backoff = BackoffTicks;
|
||||
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
if (!owner.IsTargetValid)
|
||||
{
|
||||
owner.TargetActor = owner.SquadManager.FindClosestEnemy(owner.CenterPosition, WDist.FromCells(owner.SquadManager.Info.ProtectionScanRadius));
|
||||
|
||||
if (owner.TargetActor == null)
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new UnitsForProtectionFleeState(), true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!owner.IsTargetVisible)
|
||||
{
|
||||
if (Backoff < 0)
|
||||
{
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new UnitsForProtectionFleeState(), true);
|
||||
Backoff = BackoffTicks;
|
||||
return;
|
||||
}
|
||||
|
||||
Backoff--;
|
||||
}
|
||||
else
|
||||
{
|
||||
foreach (var a in owner.Units)
|
||||
owner.Bot.QueueOrder(new Order("AttackMove", a, Target.FromCell(owner.World, owner.TargetActor.Location), false));
|
||||
}
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { }
|
||||
}
|
||||
|
||||
class UnitsForProtectionFleeState : GroundStateBase, IState
|
||||
{
|
||||
public void Activate(Squad owner) { }
|
||||
|
||||
public void Tick(Squad owner)
|
||||
{
|
||||
if (!owner.IsValid)
|
||||
return;
|
||||
|
||||
GoToRandomOwnBuilding(owner);
|
||||
owner.FuzzyStateMachine.ChangeState(owner, new UnitsForProtectionIdleState(), true);
|
||||
}
|
||||
|
||||
public void Deactivate(Squad owner) { owner.Units.Clear(); }
|
||||
}
|
||||
}
|
||||
105
OpenRA.Mods.Common/Traits/BotModules/Squads/States/StateBase.cs
Normal file
105
OpenRA.Mods.Common/Traits/BotModules/Squads/States/StateBase.cs
Normal file
@@ -0,0 +1,105 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.Activities;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits.BotModules.Squads
|
||||
{
|
||||
abstract class StateBase
|
||||
{
|
||||
protected static void GoToRandomOwnBuilding(Squad squad)
|
||||
{
|
||||
var loc = RandomBuildingLocation(squad);
|
||||
foreach (var a in squad.Units)
|
||||
squad.Bot.QueueOrder(new Order("Move", a, Target.FromCell(squad.World, loc), false));
|
||||
}
|
||||
|
||||
protected static CPos RandomBuildingLocation(Squad squad)
|
||||
{
|
||||
var location = squad.SquadManager.GetRandomBaseCenter();
|
||||
var buildings = squad.World.ActorsHavingTrait<Building>()
|
||||
.Where(a => a.Owner == squad.Bot.Player).ToList();
|
||||
if (buildings.Count > 0)
|
||||
location = buildings.Random(squad.Random).Location;
|
||||
|
||||
return location;
|
||||
}
|
||||
|
||||
protected static bool BusyAttack(Actor a)
|
||||
{
|
||||
if (a.IsIdle)
|
||||
return false;
|
||||
|
||||
var activity = a.CurrentActivity;
|
||||
var type = activity.GetType();
|
||||
if (type == typeof(Attack) || type == typeof(FlyAttack))
|
||||
return true;
|
||||
|
||||
var next = activity.NextActivity;
|
||||
if (next == null)
|
||||
return false;
|
||||
|
||||
var nextType = next.GetType();
|
||||
if (nextType == typeof(Attack) || nextType == typeof(FlyAttack))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected static bool CanAttackTarget(Actor a, Actor target)
|
||||
{
|
||||
if (!a.Info.HasTraitInfo<AttackBaseInfo>())
|
||||
return false;
|
||||
|
||||
var targetTypes = target.GetEnabledTargetTypes();
|
||||
if (targetTypes.IsEmpty)
|
||||
return false;
|
||||
|
||||
var arms = a.TraitsImplementing<Armament>();
|
||||
foreach (var arm in arms)
|
||||
{
|
||||
if (arm.IsTraitDisabled)
|
||||
continue;
|
||||
|
||||
if (arm.Weapon.IsValidTarget(targetTypes))
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected virtual bool ShouldFlee(Squad squad, Func<IEnumerable<Actor>, bool> flee)
|
||||
{
|
||||
if (!squad.IsValid)
|
||||
return false;
|
||||
|
||||
var randomSquadUnit = squad.Units.Random(squad.Random);
|
||||
var dangerRadius = squad.SquadManager.Info.DangerScanRadius;
|
||||
var units = squad.World.FindActorsInCircle(randomSquadUnit.CenterPosition, WDist.FromCells(dangerRadius)).ToList();
|
||||
|
||||
// If there are any own buildings within the DangerRadius, don't flee
|
||||
// PERF: Avoid LINQ
|
||||
foreach (var u in units)
|
||||
if (u.Owner == squad.Bot.Player && u.Info.HasTraitInfo<BuildingInfo>())
|
||||
return false;
|
||||
|
||||
var enemyAroundUnit = units.Where(unit => squad.Bot.Player.Stances[unit.Owner] == Stance.Enemy && unit.Info.HasTraitInfo<AttackBaseInfo>());
|
||||
if (!enemyAroundUnit.Any())
|
||||
return false;
|
||||
|
||||
return flee(enemyAroundUnit);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Mods.Common.AI;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
|
||||
209
OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs
Normal file
209
OpenRA.Mods.Common/Traits/BotModules/UnitBuilderBotModule.cs
Normal file
@@ -0,0 +1,209 @@
|
||||
#region Copyright & License Information
|
||||
/*
|
||||
* Copyright 2007-2018 The OpenRA Developers (see AUTHORS)
|
||||
* This file is part of OpenRA, which is free software. It is made
|
||||
* available to you 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. For more
|
||||
* information, see COPYING.
|
||||
*/
|
||||
#endregion
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using OpenRA.Traits;
|
||||
|
||||
namespace OpenRA.Mods.Common.Traits
|
||||
{
|
||||
[Desc("Controls AI unit production.")]
|
||||
public class UnitBuilderBotModuleInfo : ConditionalTraitInfo
|
||||
{
|
||||
// TODO: Investigate whether this might the (or at least one) reason why bots occasionally get into a state of doing nothing.
|
||||
// Reason: If this is less than SquadSize, the bot might get stuck between not producing more units due to this,
|
||||
// but also not creating squads since there aren't enough idle units.
|
||||
[Desc("Only produce units as long as there are less than this amount of units idling inside the base.")]
|
||||
public readonly int IdleBaseUnitsMaximum = 12;
|
||||
|
||||
[Desc("Production queues AI uses for producing units.")]
|
||||
public readonly HashSet<string> UnitQueues = new HashSet<string> { "Vehicle", "Infantry", "Plane", "Ship", "Aircraft" };
|
||||
|
||||
[Desc("What units to the AI should build.", "What relative share of the total army must be this type of unit.")]
|
||||
public readonly Dictionary<string, int> UnitsToBuild = null;
|
||||
|
||||
[Desc("What units should the AI have a maximum limit to train.")]
|
||||
public readonly Dictionary<string, int> UnitLimits = null;
|
||||
|
||||
public override object Create(ActorInitializer init) { return new UnitBuilderBotModule(init.Self, this); }
|
||||
}
|
||||
|
||||
public class UnitBuilderBotModule : ConditionalTrait<UnitBuilderBotModuleInfo>, IBotTick, IBotNotifyIdleBaseUnits, IBotRequestUnitProduction
|
||||
{
|
||||
public const int FeedbackTime = 30; // ticks; = a bit over 1s. must be >= netlag.
|
||||
|
||||
readonly World world;
|
||||
readonly Player player;
|
||||
|
||||
readonly List<string> queuedBuildRequests = new List<string>();
|
||||
|
||||
IBotRequestPauseUnitProduction[] requestPause;
|
||||
|
||||
List<Actor> idleUnits = new List<Actor>();
|
||||
|
||||
int ticks;
|
||||
|
||||
public UnitBuilderBotModule(Actor self, UnitBuilderBotModuleInfo info)
|
||||
: base(info)
|
||||
{
|
||||
world = self.World;
|
||||
player = self.Owner;
|
||||
}
|
||||
|
||||
protected override void TraitEnabled(Actor self)
|
||||
{
|
||||
requestPause = player.PlayerActor.TraitsImplementing<IBotRequestPauseUnitProduction>().ToArray();
|
||||
}
|
||||
|
||||
void IBotNotifyIdleBaseUnits.UpdatedIdleBaseUnits(List<Actor> idleUnits)
|
||||
{
|
||||
this.idleUnits = idleUnits;
|
||||
}
|
||||
|
||||
void IBotTick.BotTick(IBot bot)
|
||||
{
|
||||
if (requestPause.Any(rp => rp.PauseUnitProduction))
|
||||
return;
|
||||
|
||||
ticks++;
|
||||
|
||||
if (ticks % FeedbackTime == 0)
|
||||
{
|
||||
var buildRequest = queuedBuildRequests.FirstOrDefault();
|
||||
if (buildRequest != null)
|
||||
{
|
||||
BuildUnit(bot, buildRequest);
|
||||
queuedBuildRequests.Remove(buildRequest);
|
||||
}
|
||||
|
||||
foreach (var q in Info.UnitQueues)
|
||||
BuildUnit(bot, q, idleUnits.Count < Info.IdleBaseUnitsMaximum);
|
||||
}
|
||||
}
|
||||
|
||||
void IBotRequestUnitProduction.RequestUnitProduction(IBot bot, string requestedActor)
|
||||
{
|
||||
queuedBuildRequests.Add(requestedActor);
|
||||
}
|
||||
|
||||
void BuildUnit(IBot bot, string category, bool buildRandom)
|
||||
{
|
||||
// Pick a free queue
|
||||
var queue = AIUtils.FindQueues(player, category).FirstOrDefault(q => !q.AllQueued().Any());
|
||||
if (queue == null)
|
||||
return;
|
||||
|
||||
var unit = buildRandom ?
|
||||
ChooseRandomUnitToBuild(queue) :
|
||||
ChooseUnitToBuild(queue);
|
||||
|
||||
if (unit == null)
|
||||
return;
|
||||
|
||||
var name = unit.Name;
|
||||
|
||||
if (Info.UnitsToBuild != null && !Info.UnitsToBuild.ContainsKey(name))
|
||||
return;
|
||||
|
||||
if (Info.UnitLimits != null &&
|
||||
Info.UnitLimits.ContainsKey(name) &&
|
||||
world.Actors.Count(a => a.Owner == player && a.Info.Name == name) >= Info.UnitLimits[name])
|
||||
return;
|
||||
|
||||
bot.QueueOrder(Order.StartProduction(queue.Actor, name, 1));
|
||||
}
|
||||
|
||||
void BuildUnit(IBot bot, string category, string name)
|
||||
{
|
||||
var queue = AIUtils.FindQueues(player, category).FirstOrDefault(q => !q.AllQueued().Any());
|
||||
if (queue == null)
|
||||
return;
|
||||
|
||||
if (world.Map.Rules.Actors[name] != null)
|
||||
bot.QueueOrder(Order.StartProduction(queue.Actor, name, 1));
|
||||
}
|
||||
|
||||
// In cases where we want to build a specific unit but don't know the queue name (because there's more than one possibility)
|
||||
void BuildUnit(IBot bot, string name)
|
||||
{
|
||||
var actorInfo = world.Map.Rules.Actors[name];
|
||||
if (actorInfo == null)
|
||||
return;
|
||||
|
||||
var buildableInfo = actorInfo.TraitInfoOrDefault<BuildableInfo>();
|
||||
if (buildableInfo == null)
|
||||
return;
|
||||
|
||||
ProductionQueue queue = null;
|
||||
foreach (var pq in buildableInfo.Queue)
|
||||
{
|
||||
queue = AIUtils.FindQueues(player, pq).FirstOrDefault(q => !q.AllQueued().Any());
|
||||
if (queue != null)
|
||||
break;
|
||||
}
|
||||
|
||||
if (queue != null)
|
||||
bot.QueueOrder(Order.StartProduction(queue.Actor, name, 1));
|
||||
}
|
||||
|
||||
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue)
|
||||
{
|
||||
var buildableThings = queue.BuildableItems();
|
||||
if (!buildableThings.Any())
|
||||
return null;
|
||||
|
||||
var unit = buildableThings.Random(world.LocalRandom);
|
||||
return HasAdequateAirUnitReloadBuildings(unit) ? unit : null;
|
||||
}
|
||||
|
||||
ActorInfo ChooseUnitToBuild(ProductionQueue queue)
|
||||
{
|
||||
var buildableThings = queue.BuildableItems();
|
||||
if (!buildableThings.Any())
|
||||
return null;
|
||||
|
||||
var myUnits = player.World
|
||||
.ActorsHavingTrait<IPositionable>()
|
||||
.Where(a => a.Owner == player)
|
||||
.Select(a => a.Info.Name).ToList();
|
||||
|
||||
foreach (var unit in Info.UnitsToBuild.Shuffle(world.LocalRandom))
|
||||
if (buildableThings.Any(b => b.Name == unit.Key))
|
||||
if (myUnits.Count(a => a == unit.Key) * 100 < unit.Value * myUnits.Count)
|
||||
if (HasAdequateAirUnitReloadBuildings(world.Map.Rules.Actors[unit.Key]))
|
||||
return world.Map.Rules.Actors[unit.Key];
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// For mods like RA (number of RearmActors must match the number of aircraft)
|
||||
bool HasAdequateAirUnitReloadBuildings(ActorInfo actorInfo)
|
||||
{
|
||||
var aircraftInfo = actorInfo.TraitInfoOrDefault<AircraftInfo>();
|
||||
if (aircraftInfo == null)
|
||||
return true;
|
||||
|
||||
// If actor isn't Rearmable, it doesn't need a RearmActor to reload
|
||||
var rearmableInfo = actorInfo.TraitInfoOrDefault<RearmableInfo>();
|
||||
if (rearmableInfo == null)
|
||||
return true;
|
||||
|
||||
var countOwnAir = AIUtils.CountActorsWithTrait<IPositionable>(actorInfo.Name, player);
|
||||
var countBuildings = rearmableInfo.RearmActors.Sum(b => AIUtils.CountActorsWithTrait<Building>(b, player));
|
||||
if (countOwnAir >= countBuildings)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user