Move the AI namespace to Mods.Common

This commit is contained in:
penev92
2015-02-06 18:23:23 +02:00
parent d921e0f838
commit 6c6a4322ed
13 changed files with 26 additions and 43 deletions

View File

@@ -1,257 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using AI.Fuzzy.Library;
using OpenRA.GameRules;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
class AttackOrFleeFuzzy
{
MamdaniFuzzySystem fuzzyEngine;
public AttackOrFleeFuzzy()
{
InitializateFuzzyVariables();
}
protected void AddFuzzyRule(string rule)
{
fuzzyEngine.Rules.Add(fuzzyEngine.ParseRule(rule));
}
protected void InitializateFuzzyVariables()
{
fuzzyEngine = new MamdaniFuzzySystem();
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);
AddingRulesForNormalOwnHealth();
AddingRulesForInjuredOwnHealth();
AddingRulesForNearDeadOwnHealth();
}
protected virtual void AddingRulesForNormalOwnHealth()
{
AddFuzzyRule("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");
}
protected virtual void AddingRulesForInjuredOwnHealth()
{
AddFuzzyRule("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");
AddFuzzyRule("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");
AddFuzzyRule("if ((OwnHealth is Injured) " +
"and ((EnemyHealth is Injured) or (EnemyHealth is Normal)) " +
"and (RelativeAttackPower is Weak) " +
"and (RelativeSpeed is Slow)) " +
"then AttackOrFlee is Attack");
AddFuzzyRule("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");
AddFuzzyRule("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");
}
protected virtual void AddingRulesForNearDeadOwnHealth()
{
AddFuzzyRule("if ((OwnHealth is NearDead) " +
"and (EnemyHealth is Injured) " +
"and (RelativeAttackPower is Equal) " +
"and ((RelativeSpeed is Slow) or (RelativeSpeed is Equal))) " +
"then AttackOrFlee is Attack");
AddFuzzyRule("if ((OwnHealth is NearDead) " +
"and (EnemyHealth is NearDead) " +
"and (RelativeAttackPower is Weak) " +
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
"then AttackOrFlee is Flee");
AddFuzzyRule("if ((OwnHealth is NearDead) " +
"and (EnemyHealth is Injured) " +
"and (RelativeAttackPower is Weak) " +
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
"then AttackOrFlee is Flee");
AddFuzzyRule("if ((OwnHealth is NearDead) " +
"and (EnemyHealth is Normal) " +
"and (RelativeAttackPower is Weak) " +
"and ((RelativeSpeed is Equal) or (RelativeSpeed is Fast))) " +
"then AttackOrFlee is Flee");
AddFuzzyRule("if (OwnHealth is NearDead) " +
"and (EnemyHealth is Normal) " +
"and (RelativeAttackPower is Equal) " +
"and (RelativeSpeed is Fast) " +
"then AttackOrFlee is Flee");
AddFuzzyRule("if (OwnHealth is NearDead) " +
"and (EnemyHealth is Normal) " +
"and (RelativeAttackPower is Strong) " +
"and (RelativeSpeed is Fast) " +
"then AttackOrFlee is Flee");
AddFuzzyRule("if (OwnHealth is NearDead) " +
"and (EnemyHealth is Injured) " +
"and (RelativeAttackPower is Equal) " +
"and (RelativeSpeed is Fast) " +
"then AttackOrFlee is Flee");
}
public bool CanAttack(IEnumerable<Actor> ownUnits, IEnumerable<Actor> enemyUnits)
{
var inputValues = new Dictionary<FuzzyVariable, double>();
inputValues.Add(fuzzyEngine.InputByName("OwnHealth"), (double)NormalizedHealth(ownUnits, 100));
inputValues.Add(fuzzyEngine.InputByName("EnemyHealth"), (double)NormalizedHealth(enemyUnits, 100));
inputValues.Add(fuzzyEngine.InputByName("RelativeAttackPower"), (double)RelativePower(ownUnits, enemyUnits));
inputValues.Add(fuzzyEngine.InputByName("RelativeSpeed"), (double)RelativeSpeed(ownUnits, enemyUnits));
var result = fuzzyEngine.Calculate(inputValues);
var attackChance = result[fuzzyEngine.OutputByName("AttackOrFlee")];
return !double.IsNaN(attackChance) && attackChance < 30.0;
}
protected static float NormalizedHealth(IEnumerable<Actor> actors, float normalizeByValue)
{
var sumOfMaxHp = 0;
var sumOfHp = 0;
foreach (var a in actors)
{
if (a.HasTrait<Health>())
{
sumOfMaxHp += a.Trait<Health>().MaxHP;
sumOfHp += a.Trait<Health>().HP;
}
}
if (sumOfMaxHp == 0)
return 0.0f;
return (sumOfHp * normalizeByValue) / sumOfMaxHp;
}
protected float RelativePower(IEnumerable<Actor> own, IEnumerable<Actor> enemy)
{
return RelativeValue(own, enemy, 100, SumOfValues<AttackBase>, (Actor a) =>
{
var sumOfDamage = 0;
var arms = a.TraitsImplementing<Armament>();
foreach (var arm in arms)
{
var warhead = arm.Weapon.Warheads.Select(w => w as DamageWarhead).FirstOrDefault(w => w != null);
if (warhead != null)
sumOfDamage += warhead.Damage;
}
return sumOfDamage;
});
}
protected float RelativeSpeed(IEnumerable<Actor> own, IEnumerable<Actor> enemy)
{
return RelativeValue(own, enemy, 100, Average<Mobile>, (Actor a) => a.Trait<Mobile>().Info.Speed);
}
protected 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);
}
protected float SumOfValues<Trait>(IEnumerable<Actor> actors, Func<Actor, int> getValue)
{
var sum = 0;
foreach (var a in actors)
if (a.HasTrait<Trait>())
sum += getValue(a);
return sum;
}
protected float Average<Trait>(IEnumerable<Actor> actors, Func<Actor, int> getValue)
{
var sum = 0;
var countActors = 0;
foreach (var a in actors)
{
if (a.HasTrait<Trait>())
{
sum += getValue(a);
countActors++;
}
}
if (countActors == 0)
return 0.0f;
return sum / countActors;
}
}
}

View File

@@ -1,233 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
class BaseBuilder
{
readonly string category;
readonly HackyAI ai;
readonly World world;
readonly Player player;
readonly PowerManager playerPower;
readonly PlayerResources playerResources;
int waitTicks;
Actor[] playerBuildings;
public BaseBuilder(HackyAI ai, string category, Player p, PowerManager pm, PlayerResources pr)
{
this.ai = ai;
world = p.World;
player = p;
playerPower = pm;
playerResources = pr;
this.category = category;
}
public void Tick()
{
// Only update once per second or so
if (--waitTicks > 0)
return;
playerBuildings = world.ActorsWithTrait<Building>()
.Where(a => a.Actor.Owner == player)
.Select(a => a.Actor)
.ToArray();
var active = false;
foreach (var queue in ai.FindQueues(category))
if (TickQueue(queue))
active = true;
waitTicks = active ? ai.Info.StructureProductionActiveDelay : ai.Info.StructureProductionInactiveDelay;
}
bool TickQueue(ProductionQueue queue)
{
var currentBuilding = queue.CurrentItem();
// Waiting to build something
if (currentBuilding == null)
{
var item = ChooseBuildingToBuild(queue);
if (item == null)
return false;
HackyAI.BotDebug("AI: {0} is starting production of {1}".F(player, item.Name));
world.IssueOrder(Order.StartProduction(queue.Actor, item.Name, 1));
}
else if (currentBuilding.Done)
{
// Production is complete
// Choose the placement logic
// HACK: HACK HACK HACK
var type = BuildingType.Building;
if (world.Map.Rules.Actors[currentBuilding.Item].Traits.Contains<AttackBaseInfo>())
type = BuildingType.Defense;
else if (world.Map.Rules.Actors[currentBuilding.Item].Traits.Contains<RefineryInfo>())
type = BuildingType.Refinery;
var location = ai.ChooseBuildLocation(currentBuilding.Item, true, type);
if (location == null)
{
HackyAI.BotDebug("AI: {0} has nowhere to place {1}".F(player, currentBuilding.Item));
world.IssueOrder(Order.CancelProduction(queue.Actor, currentBuilding.Item, 1));
}
else
{
world.IssueOrder(new Order("PlaceBuilding", player.PlayerActor, false)
{
TargetLocation = location.Value,
TargetString = currentBuilding.Item,
TargetActor = queue.Actor,
SuppressVisualFeedback = true
});
return true;
}
}
return true;
}
ActorInfo GetProducibleBuilding(string commonName, IEnumerable<ActorInfo> buildables, Func<ActorInfo, int> orderBy = null)
{
string[] actors;
if (!ai.Info.BuildingCommonNames.TryGetValue(commonName, out actors))
throw new InvalidOperationException("Can't find {0} in the HackyAI BuildingCommonNames definition.".F(commonName));
var available = buildables.Where(actor =>
{
// Are we able to build this?
if (!actors.Contains(actor.Name))
return false;
if (!ai.Info.BuildingLimits.ContainsKey(actor.Name))
return true;
return playerBuildings.Count(a => a.Info.Name == actor.Name) <= ai.Info.BuildingLimits[actor.Name];
});
if (orderBy != null)
return available.MaxByOrDefault(orderBy);
return available.RandomOrDefault(ai.Random);
}
ActorInfo ChooseBuildingToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
// First priority is to get out of a low power situation
if (playerPower.ExcessPower < 0)
{
var power = GetProducibleBuilding("Power", buildableThings, a => a.Traits.WithInterface<PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1).Sum(p => p.Amount));
if (power != null && power.Traits.WithInterface<PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1).Sum(p => p.Amount) > 0)
{
// TODO: Handle the case when of when we actually do need a power plant because we don't have enough but are also suffering from a power outage
if (playerPower.PowerOutageRemainingTicks <= 0)
{
HackyAI.BotDebug("AI: {0} decided to build {1}: Priority override (low power)", queue.Actor.Owner, power.Name);
return power;
}
}
}
// Next is to build up a strong economy
if (!ai.HasAdequateProc() || !ai.HasMinimumProc())
{
var refinery = GetProducibleBuilding("Refinery", buildableThings);
if (refinery != null)
{
HackyAI.BotDebug("AI: {0} decided to build {1}: Priority override (refinery)", queue.Actor.Owner, refinery.Name);
return refinery;
}
}
// Make sure that we can can spend as fast as we are earning
if (ai.Info.NewProductionCashThreshold > 0 && playerResources.Resources > ai.Info.NewProductionCashThreshold)
{
var production = GetProducibleBuilding("Production", buildableThings);
if (production != null)
{
HackyAI.BotDebug("AI: {0} decided to build {1}: Priority override (production)", queue.Actor.Owner, production.Name);
return production;
}
}
// Create some head room for resource storage if we really need it
if (playerResources.AlertSilo)
{
var silo = GetProducibleBuilding("Silo", buildableThings);
if (silo != null)
{
HackyAI.BotDebug("AI: {0} decided to build {1}: Priority override (silo)", queue.Actor.Owner, silo.Name);
return silo;
}
}
// Build everything else
foreach (var frac in ai.Info.BuildingFractions.Shuffle(ai.Random))
{
var name = frac.Key;
// Can we build this structure?
if (!buildableThings.Any(b => b.Name == name))
continue;
// Do we want to build this structure?
var count = playerBuildings.Count(a => a.Info.Name == name);
if (count > frac.Value * playerBuildings.Length)
continue;
if (ai.Info.BuildingLimits.ContainsKey(name) && ai.Info.BuildingLimits[name] <= count)
continue;
// Will this put us into low power?
var actor = world.Map.Rules.Actors[frac.Key];
var pis = actor.Traits.WithInterface<PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1);
if (playerPower.ExcessPower < 0 || playerPower.ExcessPower < pis.Sum(pi => pi.Amount))
{
// Try building a power plant instead
var power = GetProducibleBuilding("Power", buildableThings, a => a.Traits.WithInterface<PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1).Sum(pi => pi.Amount));
if (power != null && power.Traits.WithInterface<PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1).Sum(pi => pi.Amount) > 0)
{
// TODO: Handle the case when of when we actually do need a power plant because we don't have enough but are also suffering from a power outage
if (playerPower.PowerOutageRemainingTicks > 0)
HackyAI.BotDebug("AI: {0} is suffering from a power outage; not going to build {1}", queue.Actor.Owner, power.Name);
else
{
HackyAI.BotDebug("{0} decided to build {1}: Priority override (would be low power)", queue.Actor.Owner, power.Name);
return power;
}
}
}
// Lets build this
HackyAI.BotDebug("{0} decided to build {1}: Desired is {2} ({3} / {4}); current is {5} / {4}", queue.Actor.Owner, name, frac.Value, frac.Value * playerBuildings.Length, playerBuildings.Length, count);
return actor;
}
// Too spammy to keep enabled all the time, but very useful when debugging specific issues.
// HackyAI.BotDebug("{0} couldn't decide what to build for queue {1}.", queue.Actor.Owner, queue.Info.Group);
return null;
}
}
}

View File

@@ -1,936 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.Activities;
using OpenRA.Mods.RA.Traits;
using OpenRA.Primitives;
using OpenRA.Support;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
public sealed class HackyAIInfo : IBotInfo, ITraitInfo
{
[Desc("Ingame name this bot uses.")]
public readonly string Name = "Unnamed Bot";
[Desc("Minimum number of units AI must have before attacking.")]
public readonly int SquadSize = 8;
[Desc("Production queues AI uses for buildings.")]
public readonly string[] BuildingQueues = { "Building" };
[Desc("Production queues AI uses for defenses.")]
public readonly string[] DefenseQueues = { "Defense" };
[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("How long to wait (in ticks) between structure production checks when there is no active production.")]
public readonly int StructureProductionInactiveDelay = 125;
[Desc("How long to wait (in ticks) between structure production checks ticks when actively building things.")]
public readonly int StructureProductionActiveDelay = 10;
[Desc("Minimum range at which to build defensive structures near a combat hotspot.")]
public readonly int MinimumDefenseRadius = 5;
[Desc("Maximum range at which to build defensive structures near a combat hotspot.")]
public readonly int MaximumDefenseRadius = 20;
[Desc("Try to build another production building if there is too much cash.")]
public readonly int NewProductionCashThreshold = 5000;
[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("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("Radius in cells around a factory scanned for rally points by the AI.")]
public readonly int RallyPointScanRadius = 8;
[Desc("Radius in cells around the center of the base to expand.")]
public readonly int MaxBaseRadius = 20;
[Desc("Production queues AI uses for producing units.")]
public readonly string[] UnitQueues = { "Vehicle", "Infantry", "Plane", "Ship", "Aircraft" };
[Desc("Should the AI repair its buildings if damaged?")]
public readonly bool ShouldRepairBuildings = true;
string IBotInfo.Name { get { return this.Name; } }
[Desc("What units to the AI should build.", "What % of the total army must be this type of unit.")]
[FieldLoader.LoadUsing("LoadUnits")]
public readonly Dictionary<string, float> UnitsToBuild = null;
[Desc("What buildings to the AI should build.", "What % of the total base must be this type of building.")]
[FieldLoader.LoadUsing("LoadBuildings")]
public readonly Dictionary<string, float> BuildingFractions = null;
[Desc("Tells the AI what unit types fall under the same common name.")]
[FieldLoader.LoadUsing("LoadUnitsCommonNames")]
public readonly Dictionary<string, string[]> UnitsCommonNames = null;
[Desc("Tells the AI what building types fall under the same common name.")]
[FieldLoader.LoadUsing("LoadBuildingsCommonNames")]
public readonly Dictionary<string, string[]> BuildingCommonNames = null;
[Desc("What buildings should the AI have max limits n.", "What is the limit of the building.")]
[FieldLoader.LoadUsing("LoadBuildingLimits")]
public readonly Dictionary<string, int> BuildingLimits = null;
// TODO Update OpenRA.Utility/Command.cs#L300 to first handle lists and also read nested ones
[Desc("Tells the AI how to use its support powers.")]
[FieldLoader.LoadUsing("LoadDecisions")]
public readonly List<SupportPowerDecision> PowerDecisions = new List<SupportPowerDecision>();
static object LoadList<T>(MiniYaml y, string field)
{
var nd = y.ToDictionary();
return nd.ContainsKey(field)
? nd[field].ToDictionary(my => FieldLoader.GetValue<T>(field, my.Value))
: new Dictionary<string, T>();
}
static object LoadUnits(MiniYaml y) { return LoadList<float>(y, "UnitsToBuild"); }
static object LoadBuildings(MiniYaml y) { return LoadList<float>(y, "BuildingFractions"); }
static object LoadUnitsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "UnitsCommonNames"); }
static object LoadBuildingsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "BuildingCommonNames"); }
static object LoadBuildingLimits(MiniYaml y) { return LoadList<int>(y, "BuildingLimits"); }
static object LoadDecisions(MiniYaml yaml)
{
var ret = new List<SupportPowerDecision>();
foreach (var d in yaml.Nodes)
if (d.Key.Split('@')[0] == "SupportPowerDecision")
ret.Add(new SupportPowerDecision(d.Value));
return ret;
}
public object Create(ActorInitializer init) { return new HackyAI(this, init); }
}
public class Enemy { public int Aggro; }
public enum BuildingType { Building, Defense, Refinery }
public sealed class HackyAI : ITick, IBot, INotifyDamage
{
public MersenneTwister Random { get; private set; }
public readonly HackyAIInfo Info;
public CPos BaseCenter { get; private set; }
public Player Player { get; private set; }
Dictionary<SupportPowerInstance, int> waitingPowers = new Dictionary<SupportPowerInstance, int>();
Dictionary<string, SupportPowerDecision> powerDecisions = new Dictionary<string, SupportPowerDecision>();
PowerManager playerPower;
SupportPowerManager supportPowerMngr;
PlayerResources playerResource;
bool enabled;
int ticks;
BitArray resourceTypeIndices;
RushFuzzy rushFuzzy = new RushFuzzy();
Cache<Player, Enemy> aggro = new Cache<Player, Enemy>(_ => new Enemy());
List<BaseBuilder> builders = new List<BaseBuilder>();
List<Squad> squads = new List<Squad>();
List<Actor> unitsHangingAroundTheBase = new List<Actor>();
// 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>();
public const int FeedbackTime = 30; // ticks; = a bit over 1s. must be >= netlag.
public readonly World World;
public Map Map { get { return World.Map; } }
IBotInfo IBot.Info { get { return this.Info; } }
public HackyAI(HackyAIInfo info, ActorInitializer init)
{
Info = info;
World = init.World;
foreach (var decision in info.PowerDecisions)
powerDecisions.Add(decision.OrderName, decision);
}
public static void BotDebug(string s, params object[] args)
{
if (Game.Settings.Debug.BotDebug)
Game.Debug(s, args);
}
// Called by the host's player creation code
public void Activate(Player p)
{
Player = p;
enabled = true;
playerPower = p.PlayerActor.Trait<PowerManager>();
supportPowerMngr = p.PlayerActor.Trait<SupportPowerManager>();
playerResource = p.PlayerActor.Trait<PlayerResources>();
foreach (var building in Info.BuildingQueues)
builders.Add(new BaseBuilder(this, building, p, playerPower, playerResource));
foreach (var defense in Info.DefenseQueues)
builders.Add(new BaseBuilder(this, defense, p, playerPower, playerResource));
Random = new MersenneTwister((int)p.PlayerActor.ActorID);
resourceTypeIndices = new BitArray(World.TileSet.TerrainInfo.Length); // Big enough
foreach (var t in Map.Rules.Actors["world"].Traits.WithInterface<ResourceTypeInfo>())
resourceTypeIndices.Set(World.TileSet.GetTerrainIndex(t.TerrainType), true);
}
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
if (!buildableThings.Any())
return null;
var unit = buildableThings.Random(Random);
return HasAdequateAirUnits(unit) ? unit : null;
}
ActorInfo ChooseUnitToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
if (!buildableThings.Any())
return null;
var myUnits = Player.World
.ActorsWithTrait<IPositionable>()
.Where(a => a.Actor.Owner == Player)
.Select(a => a.Actor.Info.Name).ToList();
foreach (var unit in Info.UnitsToBuild.Shuffle(Random))
if (buildableThings.Any(b => b.Name == unit.Key))
if (myUnits.Count(a => a == unit.Key) < unit.Value * myUnits.Count)
if (HasAdequateAirUnits(Map.Rules.Actors[unit.Key]))
return Map.Rules.Actors[unit.Key];
return null;
}
int CountBuilding(string frac, Player owner)
{
return World.ActorsWithTrait<Building>()
.Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == frac);
}
int CountUnits(string unit, Player owner)
{
return World.ActorsWithTrait<IPositionable>()
.Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == unit);
}
int? CountBuildingByCommonName(string commonName, Player owner)
{
if (!Info.BuildingCommonNames.ContainsKey(commonName))
return null;
return World.ActorsWithTrait<Building>()
.Count(a => a.Actor.Owner == owner && Info.BuildingCommonNames[commonName].Contains(a.Actor.Info.Name));
}
public ActorInfo GetBuildingInfoByCommonName(string commonName, Player owner)
{
if (commonName == "ConstructionYard")
return Map.Rules.Actors.Where(k => Info.BuildingCommonNames[commonName].Contains(k.Key)).Random(Random).Value;
return GetInfoByCommonName(Info.BuildingCommonNames, commonName, owner);
}
public ActorInfo GetUnitInfoByCommonName(string commonName, Player owner)
{
return GetInfoByCommonName(Info.UnitsCommonNames, commonName, owner);
}
public ActorInfo GetInfoByCommonName(Dictionary<string, string[]> names, string commonName, Player owner)
{
if (!names.Any() || !names.ContainsKey(commonName))
throw new InvalidOperationException("Can't find {0} in the HackyAI UnitsCommonNames definition.".F(commonName));
return Map.Rules.Actors.Where(k => names[commonName].Contains(k.Key)).Random(Random).Value;
}
public bool HasAdequateFact()
{
// Require at least one construction yard, unless we have no vehicles factory (can't build it).
return CountBuildingByCommonName("ConstructionYard", Player) > 0 ||
CountBuildingByCommonName("VehiclesFactory", Player) == 0;
}
public bool HasAdequateProc()
{
// Require at least one refinery, unless we have no power (can't build it).
return CountBuildingByCommonName("Refinery", Player) > 0 ||
CountBuildingByCommonName("Power", Player) == 0;
}
public bool HasMinimumProc()
{
// Require at least two refineries, unless we have no power (can't build it)
// or barracks (higher priority?)
return CountBuildingByCommonName("Refinery", Player) >= 2 ||
CountBuildingByCommonName("Power", Player) == 0 ||
CountBuildingByCommonName("Barracks", Player) == 0;
}
// For mods like RA (number of building must match the number of aircraft)
bool HasAdequateAirUnits(ActorInfo actorInfo)
{
if (!actorInfo.Traits.Contains<ReloadsInfo>() && actorInfo.Traits.Contains<LimitedAmmoInfo>()
&& actorInfo.Traits.Contains<AircraftInfo>())
{
var countOwnAir = CountUnits(actorInfo.Name, Player);
var countBuildings = CountBuilding(actorInfo.Traits.Get<AircraftInfo>().RearmBuildings.FirstOrDefault(), Player);
if (countOwnAir >= countBuildings)
return false;
}
return true;
}
CPos defenseCenter;
public CPos? ChooseBuildLocation(string actorType, bool distanceToBaseIsImportant, BuildingType type)
{
var bi = Map.Rules.Actors[actorType].Traits.GetOrDefault<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 = 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(Random);
foreach (var cell in cells)
{
if (!World.CanPlaceBuilding(actorType, bi, cell, null))
continue;
if (distanceToBaseIsImportant && !bi.IsCloseEnoughToBase(World, Player, actorType, cell))
continue;
return cell;
}
return null;
};
switch (type)
{
case BuildingType.Defense:
// Build near the closest enemy structure
var closestEnemy = World.Actors.Where(a => !a.Destroyed && a.HasTrait<Building>() && Player.Stances[a.Owner] == Stance.Enemy)
.ClosestTo(World.Map.CenterOfCell(defenseCenter));
var targetCell = closestEnemy != null ? closestEnemy.Location : BaseCenter;
return findPos(defenseCenter, targetCell, Info.MinimumDefenseRadius, Info.MaximumDefenseRadius);
case BuildingType.Refinery:
// Try and place the refinery near a resource field
var nearbyResources = Map.FindTilesInCircle(BaseCenter, Info.MaxBaseRadius)
.Where(a => resourceTypeIndices.Get(Map.GetTerrainIndex(a)))
.Shuffle(Random);
foreach (var c in nearbyResources)
{
var found = findPos(c, BaseCenter, 0, Info.MaxBaseRadius);
if (found != null)
return found;
}
// Try and find a free spot somewhere else in the base
return findPos(BaseCenter, BaseCenter, 0, Info.MaxBaseRadius);
case BuildingType.Building:
return findPos(BaseCenter, BaseCenter, 0, distanceToBaseIsImportant ? Info.MaxBaseRadius : Map.MaxTilesInCircleRange);
}
// Can't find a build location
return null;
}
public void Tick(Actor self)
{
if (!enabled)
return;
ticks++;
if (ticks == 1)
InitializeBase(self);
if (ticks % FeedbackTime == 0)
ProductionUnits(self);
AssignRolesToIdleUnits(self);
SetRallyPointsForNewProductionBuildings(self);
TryToUseSupportPower(self);
foreach (var b in builders)
b.Tick();
}
internal Actor ChooseEnemyTarget()
{
if (Player.WinState != WinState.Undefined)
return null;
var liveEnemies = World.Players
.Where(p => Player != p && Player.Stances[p] == Stance.Enemy && p.WinState == WinState.Undefined);
if (!liveEnemies.Any())
return null;
var leastLikedEnemies = liveEnemies
.GroupBy(e => aggro[e].Aggro)
.MaxByOrDefault(g => g.Key);
var enemy = (leastLikedEnemies != null) ?
leastLikedEnemies.Random(Random) : liveEnemies.FirstOrDefault();
// Pick something worth attacking owned by that player
var target = World.Actors
.Where(a => a.Owner == enemy && a.HasTrait<IOccupySpace>())
.ClosestTo(World.Map.CenterOfCell(BaseCenter));
if (target == null)
{
/* Assume that "enemy" has nothing. Cool off on attacks. */
aggro[enemy].Aggro = aggro[enemy].Aggro / 2 - 1;
Log.Write("debug", "Bot {0} couldn't find target for player {1}", Player.ClientIndex, enemy.ClientIndex);
return null;
}
// Bump the aggro slightly to avoid changing our mind
if (leastLikedEnemies.Count() > 1)
aggro[enemy].Aggro++;
return target;
}
internal Actor FindClosestEnemy(WPos pos)
{
var allEnemyUnits = World.Actors
.Where(unit => Player.Stances[unit.Owner] == Stance.Enemy && !unit.HasTrait<Husk>() &&
unit.HasTrait<ITargetable>());
return allEnemyUnits.ClosestTo(pos);
}
internal Actor FindClosestEnemy(WPos pos, WRange radius)
{
var enemyUnits = World.FindActorsInCircle(pos, radius)
.Where(unit => Player.Stances[unit.Owner] == Stance.Enemy &&
!unit.HasTrait<Husk>() && unit.HasTrait<ITargetable>());
return enemyUnits.ClosestTo(pos);
}
List<Actor> FindEnemyConstructionYards()
{
return World.Actors.Where(a => Player.Stances[a.Owner] == Stance.Enemy && !a.IsDead
&& a.HasTrait<BaseBuilding>() && !a.HasTrait<Mobile>()).ToList();
}
void CleanSquads()
{
squads.RemoveAll(s => !s.IsValid);
foreach (var s in squads)
s.Units.RemoveAll(a => a.IsDead || a.Owner != Player);
}
// Use of this function requires that one squad of this type. Hence it is a piece of shit
Squad GetSquadOfType(SquadType type)
{
return squads.FirstOrDefault(s => s.Type == type);
}
Squad RegisterNewSquad(SquadType type, Actor target = null)
{
var ret = new Squad(this, type, target);
squads.Add(ret);
return ret;
}
int assignRolesTicks = 0;
int rushTicks = 0;
int attackForceTicks = 0;
void AssignRolesToIdleUnits(Actor self)
{
CleanSquads();
activeUnits.RemoveAll(a => a.IsDead || a.Owner != Player);
unitsHangingAroundTheBase.RemoveAll(a => a.IsDead || a.Owner != Player);
if (--rushTicks <= 0)
{
rushTicks = Info.RushInterval;
TryToRushAttack();
}
if (--attackForceTicks <= 0)
{
attackForceTicks = Info.AttackForceInterval;
foreach (var s in squads)
s.Update();
}
if (--assignRolesTicks > 0)
return;
assignRolesTicks = Info.AssignRolesInterval;
GiveOrdersToIdleHarvesters();
FindNewUnits(self);
CreateAttackForce();
FindAndDeployBackupMcv(self);
}
void GiveOrdersToIdleHarvesters()
{
// Find idle harvesters and give them orders:
foreach (var a in activeUnits)
{
var harv = a.TraitOrDefault<Harvester>();
if (harv == null)
continue;
if (!a.IsIdle)
{
var act = a.GetCurrentActivity();
// A Wait activity is technically idle:
if ((act.GetType() != typeof(Wait)) &&
(act.NextActivity == null || act.NextActivity.GetType() != typeof(FindResources)))
continue;
}
if (!harv.IsEmpty)
continue;
// Tell the idle harvester to quit slacking:
World.IssueOrder(new Order("Harvest", a, false));
}
}
void FindNewUnits(Actor self)
{
var newUnits = self.World.ActorsWithTrait<IPositionable>()
.Where(a => a.Actor.Owner == Player && !a.Actor.HasTrait<BaseBuilding>()
&& !activeUnits.Contains(a.Actor))
.Select(a => a.Actor);
foreach (var a in newUnits)
{
if (a.HasTrait<Harvester>())
World.IssueOrder(new Order("Harvest", a, false));
else
unitsHangingAroundTheBase.Add(a);
if (a.HasTrait<Aircraft>() && a.HasTrait<AttackBase>())
{
var air = GetSquadOfType(SquadType.Air);
if (air == null)
air = RegisterNewSquad(SquadType.Air);
air.Units.Add(a);
}
activeUnits.Add(a);
}
}
void CreateAttackForce()
{
// Create an attack force when we have enough units around our base.
// (don't bother leaving any behind for defense)
var randomizedSquadSize = Info.SquadSize + Random.Next(30);
if (unitsHangingAroundTheBase.Count >= randomizedSquadSize)
{
var attackForce = RegisterNewSquad(SquadType.Assault);
foreach (var a in unitsHangingAroundTheBase)
if (!a.HasTrait<Aircraft>())
attackForce.Units.Add(a);
unitsHangingAroundTheBase.Clear();
}
}
void TryToRushAttack()
{
var allEnemyBaseBuilder = FindEnemyConstructionYards();
var ownUnits = activeUnits
.Where(unit => unit.HasTrait<AttackBase>() && !unit.HasTrait<Aircraft>() && unit.IsIdle).ToList();
if (!allEnemyBaseBuilder.Any() || (ownUnits.Count < Info.SquadSize))
return;
foreach (var b in allEnemyBaseBuilder)
{
var enemies = World.FindActorsInCircle(b.CenterPosition, WRange.FromCells(Info.RushAttackScanRadius))
.Where(unit => Player.Stances[unit.Owner] == Stance.Enemy && unit.HasTrait<AttackBase>()).ToList();
if (rushFuzzy.CanAttack(ownUnits, enemies))
{
var target = enemies.Any() ? enemies.Random(Random) : b;
var rush = GetSquadOfType(SquadType.Rush);
if (rush == null)
rush = RegisterNewSquad(SquadType.Rush, target);
foreach (var a3 in ownUnits)
rush.Units.Add(a3);
return;
}
}
}
void ProtectOwn(Actor attacker)
{
var protectSq = GetSquadOfType(SquadType.Protection);
if (protectSq == null)
protectSq = RegisterNewSquad(SquadType.Protection, attacker);
if (!protectSq.TargetIsValid)
protectSq.TargetActor = attacker;
if (!protectSq.IsValid)
{
var ownUnits = World.FindActorsInCircle(World.Map.CenterOfCell(BaseCenter), WRange.FromCells(Info.ProtectUnitScanRadius))
.Where(unit => unit.Owner == Player && !unit.HasTrait<Building>()
&& unit.HasTrait<AttackBase>());
foreach (var a in ownUnits)
protectSq.Units.Add(a);
}
}
bool IsRallyPointValid(CPos x, BuildingInfo info)
{
return info != null && World.IsCellBuildable(x, info);
}
void SetRallyPointsForNewProductionBuildings(Actor self)
{
var buildings = self.World.ActorsWithTrait<RallyPoint>()
.Where(rp => rp.Actor.Owner == Player &&
!IsRallyPointValid(rp.Trait.Location, rp.Actor.Info.Traits.GetOrDefault<BuildingInfo>())).ToArray();
foreach (var a in buildings)
World.IssueOrder(new Order("SetRallyPoint", a.Actor, false) { TargetLocation = ChooseRallyLocationNear(a.Actor), SuppressVisualFeedback = true });
}
// Won't work for shipyards...
CPos ChooseRallyLocationNear(Actor producer)
{
var possibleRallyPoints = Map.FindTilesInCircle(producer.Location, Info.RallyPointScanRadius)
.Where(c => IsRallyPointValid(c, producer.Info.Traits.GetOrDefault<BuildingInfo>()));
if (!possibleRallyPoints.Any())
{
BotDebug("Bot Bug: No possible rallypoint near {0}", producer.Location);
return producer.Location;
}
return possibleRallyPoints.Random(Random);
}
void InitializeBase(Actor self)
{
// Find and deploy our mcv
var mcv = self.World.Actors
.FirstOrDefault(a => a.Owner == Player && a.HasTrait<BaseBuilding>());
if (mcv != null)
{
BaseCenter = mcv.Location;
defenseCenter = BaseCenter;
// Don't transform the mcv if it is a fact
// HACK: This needs to query against MCVs directly
if (mcv.HasTrait<Mobile>())
World.IssueOrder(new Order("DeployTransform", mcv, false));
}
else
BotDebug("AI: Can't find BaseBuildUnit.");
}
// Find any newly constructed MCVs and deploy them at a sensible
// backup location within the main base.
void FindAndDeployBackupMcv(Actor self)
{
// HACK: This needs to query against MCVs directly
var mcvs = self.World.Actors.Where(a => a.Owner == Player && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>());
if (!mcvs.Any())
return;
foreach (var mcv in mcvs)
{
if (mcv.IsMoving())
continue;
var factType = mcv.Info.Traits.Get<TransformsInfo>().IntoActor;
var desiredLocation = ChooseBuildLocation(factType, false, BuildingType.Building);
if (desiredLocation == null)
continue;
World.IssueOrder(new Order("Move", mcv, true) { TargetLocation = desiredLocation.Value });
World.IssueOrder(new Order("DeployTransform", mcv, true));
}
}
void TryToUseSupportPower(Actor self)
{
if (supportPowerMngr == null)
return;
var powers = supportPowerMngr.Powers.Where(p => !p.Value.Disabled);
foreach (var kv in powers)
{
var sp = kv.Value;
// Add power to dictionary if not in delay dictionary yet
if (!waitingPowers.ContainsKey(sp))
waitingPowers.Add(sp, 0);
if (waitingPowers[sp] > 0)
waitingPowers[sp]--;
// If we have recently tried and failed to find a use location for a power, then do not try again until later
var isDelayed = waitingPowers[sp] > 0;
if (sp.Ready && !isDelayed && powerDecisions.ContainsKey(sp.Info.OrderName))
{
var powerDecision = powerDecisions[sp.Info.OrderName];
if (powerDecision == null)
{
BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", sp.Info.OrderName);
continue;
}
var attackLocation = FindCoarseAttackLocationToSupportPower(sp);
if (attackLocation == null)
{
BotDebug("AI: {1} can't find suitable coarse attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, Player.PlayerName);
waitingPowers[sp] += powerDecision.GetNextScanTime(this);
continue;
}
// Found a target location, check for precise target
attackLocation = FindFineAttackLocationToSupportPower(sp, (CPos)attackLocation);
if (attackLocation == null)
{
BotDebug("AI: {1} can't find suitable final attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, Player.PlayerName);
waitingPowers[sp] += powerDecision.GetNextScanTime(this);
continue;
}
// Valid target found, delay by a few ticks to avoid rescanning before power fires via order
BotDebug("AI: {2} found new target location {0} for support power {1}.", attackLocation, sp.Info.OrderName, Player.PlayerName);
waitingPowers[sp] += 10;
World.IssueOrder(new Order(sp.Info.OrderName, supportPowerMngr.Self, false) { TargetLocation = attackLocation.Value, SuppressVisualFeedback = true });
}
}
}
/// <summary>Scans the map in chunks, evaluating all actors in each.</summary>
CPos? FindCoarseAttackLocationToSupportPower(SupportPowerInstance readyPower)
{
CPos? bestLocation = null;
var bestAttractiveness = 0;
var powerDecision = powerDecisions[readyPower.Info.OrderName];
if (powerDecision == null)
{
BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName);
return null;
}
var checkRadius = powerDecision.CoarseScanRadius;
for (var i = 0; i < World.Map.MapSize.X; i += checkRadius)
{
for (var j = 0; j < World.Map.MapSize.Y; j += checkRadius)
{
var consideredAttractiveness = 0;
var tl = World.Map.CenterOfCell(new CPos(i, j));
var br = World.Map.CenterOfCell(new CPos(i + checkRadius, j + checkRadius));
var targets = World.ActorMap.ActorsInBox(tl, br);
consideredAttractiveness = powerDecision.GetAttractiveness(targets, Player);
if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness)
continue;
bestAttractiveness = consideredAttractiveness;
bestLocation = new CPos(i, j);
}
}
return bestLocation;
}
/// <summary>Detail scans an area, evaluating positions.</summary>
CPos? FindFineAttackLocationToSupportPower(SupportPowerInstance readyPower, CPos checkPos, int extendedRange = 1)
{
CPos? bestLocation = null;
var bestAttractiveness = 0;
var powerDecision = powerDecisions[readyPower.Info.OrderName];
if (powerDecision == null)
{
BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName);
return null;
}
var checkRadius = powerDecision.CoarseScanRadius;
var fineCheck = powerDecision.FineScanRadius;
for (var i = 0 - extendedRange; i <= (checkRadius + extendedRange); i += fineCheck)
{
var x = checkPos.X + i;
for (var j = 0 - extendedRange; j <= (checkRadius + extendedRange); j += fineCheck)
{
var y = checkPos.Y + j;
var pos = World.Map.CenterOfCell(new CPos(x, y));
var consideredAttractiveness = 0;
consideredAttractiveness += powerDecision.GetAttractiveness(pos, Player);
if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness)
continue;
bestAttractiveness = consideredAttractiveness;
bestLocation = new CPos(x, y);
}
}
return bestLocation;
}
internal IEnumerable<ProductionQueue> FindQueues(string category)
{
return World.ActorsWithTrait<ProductionQueue>()
.Where(a => a.Actor.Owner == Player && a.Trait.Info.Type == category && a.Trait.Enabled)
.Select(a => a.Trait);
}
void ProductionUnits(Actor self)
{
// Stop building until economy is restored
if (!HasAdequateProc())
return;
// No construction yards - Build a new MCV
if (!HasAdequateFact() && !self.World.Actors.Any(a => a.Owner == Player && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>()))
BuildUnit("Vehicle", GetUnitInfoByCommonName("Mcv", Player).Name);
foreach (var q in Info.UnitQueues)
BuildUnit(q, unitsHangingAroundTheBase.Count < Info.IdleBaseUnitsMaximum);
}
void BuildUnit(string category, bool buildRandom)
{
// Pick a free queue
var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null);
if (queue == null)
return;
var unit = buildRandom ?
ChooseRandomUnitToBuild(queue) :
ChooseUnitToBuild(queue);
if (unit != null && Info.UnitsToBuild.Any(u => u.Key == unit.Name))
World.IssueOrder(Order.StartProduction(queue.Actor, unit.Name, 1));
}
void BuildUnit(string category, string name)
{
var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null);
if (queue == null)
return;
if (Map.Rules.Actors[name] != null)
World.IssueOrder(Order.StartProduction(queue.Actor, name, 1));
}
public void Damaged(Actor self, AttackInfo e)
{
if (!enabled)
return;
if (e.Attacker.Owner.Stances[self.Owner] == Stance.Neutral)
return;
var rb = self.TraitOrDefault<RepairableBuilding>();
if (Info.ShouldRepairBuildings && rb != null)
{
if (e.DamageState > DamageState.Light && e.PreviousDamageState <= DamageState.Light && !rb.RepairActive)
{
BotDebug("Bot noticed damage {0} {1}->{2}, repairing.",
self, e.PreviousDamageState, e.DamageState);
World.IssueOrder(new Order("RepairBuilding", self.Owner.PlayerActor, false) { TargetActor = self });
}
}
if (e.Attacker.Destroyed)
return;
if (!e.Attacker.HasTrait<ITargetable>())
return;
if (e.Attacker != null && e.Damage > 0)
aggro[e.Attacker.Owner].Aggro += e.Damage;
// Protected harvesters or building
if ((self.HasTrait<Harvester>() || self.HasTrait<Building>()) &&
Player.Stances[e.Attacker.Owner] == Stance.Enemy)
{
defenseCenter = e.Attacker.Location;
ProtectOwn(e.Attacker);
}
}
}
}

View File

@@ -1,30 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
namespace OpenRA.Mods.RA.AI
{
class RushFuzzy : AttackOrFleeFuzzy
{
protected override void AddingRulesForNormalOwnHealth()
{
AddFuzzyRule("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");
AddFuzzyRule("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");
}
}
}

View File

@@ -1,82 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Mods.Common.Traits;
using OpenRA.Support;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
public enum SquadType { Assault, Air, Rush, Protection }
public class Squad
{
public List<Actor> Units = new List<Actor>();
public SquadType Type;
internal World World;
internal HackyAI Bot;
internal MersenneTwister Random;
internal Target Target;
internal StateMachine FuzzyStateMachine;
internal AttackOrFleeFuzzy AttackOrFleeFuzzy = new AttackOrFleeFuzzy();
public Squad(HackyAI bot, SquadType type) : this(bot, type, null) { }
public Squad(HackyAI bot, SquadType type, Actor target)
{
Bot = bot;
World = bot.World;
Random = bot.Random;
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;
}
}
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 TargetIsValid
{
get { return Target.IsValidFor(Units.FirstOrDefault()) && !Target.Actor.HasTrait<Husk>(); }
}
public WPos CenterPosition { get { return Units.Select(u => u.CenterPosition).Average(); } }
}
}

View File

@@ -1,49 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
namespace OpenRA.Mods.RA.AI
{
class StateMachine
{
IState currentState;
IState previousState;
public void Update(Squad squad)
{
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;
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);
}
}

View File

@@ -1,261 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.Activities;
using OpenRA.Mods.RA.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
abstract class AirStateBase : StateBase
{
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.HasTrait<AttackBase>() && !unit.HasTrait<Aircraft>()
&& !unit.IsDisabled())
{
var arms = unit.TraitsImplementing<Armament>();
foreach (var a in arms)
{
if (a.Weapon.ValidTargets.Contains("Air"))
{
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;
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 unitsAroundPos = owner.World.FindActorsInCircle(loc, WRange.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 limitedAmmo = a.TraitOrDefault<LimitedAmmo>();
return limitedAmmo != null && limitedAmmo.FullAmmo();
}
protected static bool HasAmmo(Actor a)
{
var limitedAmmo = a.TraitOrDefault<LimitedAmmo>();
return limitedAmmo != null && limitedAmmo.HasAmmo();
}
protected static bool ReloadsAutomatically(Actor a)
{
return a.HasTrait<Reloads>();
}
protected static bool IsRearm(Actor a)
{
var activity = a.GetCurrentActivity();
if (activity == null)
return false;
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.TargetIsValid)
{
var a = owner.Units.Random(owner.Random);
var closestEnemy = owner.Bot.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 (!HasAmmo(a))
{
if (IsRearm(a))
continue;
owner.World.IssueOrder(new Order("ReturnToBase", a, false));
continue;
}
if (IsRearm(a))
continue;
}
if (owner.TargetActor.HasTrait<ITargetable>() && CanAttackTarget(a, owner.TargetActor))
owner.World.IssueOrder(new Order("Attack", a, false) { TargetActor = owner.TargetActor });
}
}
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.World.IssueOrder(new Order("ReturnToBase", a, false));
continue;
}
owner.World.IssueOrder(new Order("Move", a, false) { TargetLocation = RandomBuildingLocation(owner) });
}
owner.FuzzyStateMachine.ChangeState(owner, new AirIdleState(), true);
}
public void Deactivate(Squad owner) { }
}
}

View File

@@ -1,171 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System.Linq;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
abstract class GroundStateBase : StateBase
{
protected virtual bool ShouldFlee(Squad owner)
{
return base.ShouldFlee(owner, enemies => !owner.AttackOrFleeFuzzy.CanAttack(owner.Units, enemies));
}
}
class GroundUnitsIdleState : GroundStateBase, IState
{
public void Activate(Squad owner) { }
public void Tick(Squad owner)
{
if (!owner.IsValid)
return;
if (!owner.TargetIsValid)
{
var t = owner.Bot.FindClosestEnemy(owner.Units.FirstOrDefault().CenterPosition);
if (t == null) return;
owner.TargetActor = t;
}
var enemyUnits = owner.World.FindActorsInCircle(owner.TargetActor.CenterPosition, WRange.FromCells(10))
.Where(unit => owner.Bot.Player.Stances[unit.Owner] == Stance.Enemy).ToList();
if (enemyUnits.Any())
{
if (owner.AttackOrFleeFuzzy.CanAttack(owner.Units, enemyUnits))
{
foreach (var u in owner.Units)
owner.World.IssueOrder(new Order("AttackMove", u, false) { TargetLocation = owner.TargetActor.Location });
// We have gathered sufficient units. Attack the nearest enemy unit.
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsAttackMoveState(), true);
return;
}
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.TargetIsValid)
{
var closestEnemy = owner.Bot.FindClosestEnemy(owner.Units.Random(owner.Random).CenterPosition);
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, WRange.FromCells(owner.Units.Count) / 3)
.Where(a => a.Owner == owner.Units.FirstOrDefault().Owner && owner.Units.Contains(a)).ToHashSet();
if (ownUnits.Count < owner.Units.Count)
{
owner.World.IssueOrder(new Order("Stop", leader, false));
foreach (var unit in owner.Units.Where(a => !ownUnits.Contains(a)))
owner.World.IssueOrder(new Order("AttackMove", unit, false) { TargetLocation = leader.Location });
}
else
{
var enemies = owner.World.FindActorsInCircle(leader.CenterPosition, WRange.FromCells(12))
.Where(a1 => !a1.Destroyed && !a1.IsDead);
var enemynearby = enemies.Where(a1 => a1.HasTrait<ITargetable>() && leader.Owner.Stances[a1.Owner] == Stance.Enemy);
var target = enemynearby.ClosestTo(leader.CenterPosition);
if (target != null)
{
owner.TargetActor = target;
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsAttackState(), true);
return;
}
else
foreach (var a in owner.Units)
owner.World.IssueOrder(new Order("AttackMove", a, false) { TargetLocation = owner.TargetActor.Location });
}
if (ShouldFlee(owner))
{
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
return;
}
}
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.TargetIsValid)
{
var closestEnemy = owner.Bot.FindClosestEnemy(owner.Units.Random(owner.Random).CenterPosition);
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.World.IssueOrder(new Order("Attack", a, false) { TargetActor = owner.Bot.FindClosestEnemy(a.CenterPosition) });
if (ShouldFlee(owner))
{
owner.FuzzyStateMachine.ChangeState(owner, new GroundUnitsFleeState(), true);
return;
}
}
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(); }
}
}

View File

@@ -1,62 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
namespace OpenRA.Mods.RA.AI
{
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 void Activate(Squad owner) { }
public void Tick(Squad owner)
{
if (!owner.IsValid)
return;
if (!owner.TargetIsValid)
{
owner.TargetActor = owner.Bot.FindClosestEnemy(owner.CenterPosition, WRange.FromCells(8));
if (owner.TargetActor == null)
{
owner.FuzzyStateMachine.ChangeState(owner, new UnitsForProtectionFleeState(), true);
return;
}
}
foreach (var a in owner.Units)
owner.World.IssueOrder(new Order("AttackMove", a, false) { TargetLocation = owner.TargetActor.Location });
}
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(); }
}
}

View File

@@ -1,98 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using OpenRA.Mods.Common.Activities;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.Activities;
using OpenRA.Mods.RA.Traits;
using OpenRA.Traits;
namespace OpenRA.Mods.RA.AI
{
abstract class StateBase
{
protected const int DangerRadius = 10;
protected static void GoToRandomOwnBuilding(Squad squad)
{
var loc = RandomBuildingLocation(squad);
foreach (var a in squad.Units)
squad.World.IssueOrder(new Order("Move", a, false) { TargetLocation = loc });
}
protected static CPos RandomBuildingLocation(Squad squad)
{
var location = squad.Bot.BaseCenter;
var buildings = squad.World.ActorsWithTrait<Building>()
.Where(a => a.Actor.Owner == squad.Bot.Player).Select(a => a.Actor).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 type = a.GetCurrentActivity().GetType();
if (type == typeof(Attack) || type == typeof(FlyAttack))
return true;
var next = a.GetCurrentActivity().NextActivity;
if (next == null)
return false;
var nextType = a.GetCurrentActivity().NextActivity.GetType();
if (nextType == typeof(Attack) || nextType == typeof(FlyAttack))
return true;
return false;
}
protected static bool CanAttackTarget(Actor a, Actor target)
{
if (!a.HasTrait<AttackBase>())
return false;
var targetable = target.TraitOrDefault<ITargetable>();
if (targetable == null)
return false;
var arms = a.TraitsImplementing<Armament>();
foreach (var arm in arms)
if (arm.Weapon.ValidTargets.Intersect(targetable.TargetTypes).Any())
return true;
return false;
}
protected virtual bool ShouldFlee(Squad squad, Func<IEnumerable<Actor>, bool> flee)
{
if (!squad.IsValid)
return false;
var u = squad.Units.Random(squad.Random);
var units = squad.World.FindActorsInCircle(u.CenterPosition, WRange.FromCells(DangerRadius)).ToList();
var ownBaseBuildingAround = units.Where(unit => unit.Owner == squad.Bot.Player && unit.HasTrait<Building>());
if (ownBaseBuildingAround.Any())
return false;
var enemyAroundUnit = units.Where(unit => squad.Bot.Player.Stances[unit.Owner] == Stance.Enemy && unit.HasTrait<AttackBase>());
if (!enemyAroundUnit.Any())
return false;
return flee(enemyAroundUnit);
}
}
}

View File

@@ -1,160 +0,0 @@
#region Copyright & License Information
/*
* Copyright 2007-2015 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. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenRA;
using OpenRA.Mods.Common.Traits;
using OpenRA.Mods.RA.AI;
using OpenRA.Traits;
namespace OpenRA.Mods.RA
{
[Desc("Adds metadata for the AI bots.")]
public class SupportPowerDecision
{
[Desc("What is the minimum attractiveness we will use this power for?")]
public readonly int MinimumAttractiveness = 1;
[Desc("What support power does this decision apply to?")]
public readonly string OrderName = "AirstrikePowerInfoOrder";
[Desc("What is the coarse scan radius of this power?", "For finding the general target area, before doing a detail scan", "Should be 10 or more to avoid lag")]
public readonly int CoarseScanRadius = 20;
[Desc("What is the fine scan radius of this power?", "For doing a detailed scan in the general target area.", "Minimum is 1")]
public readonly int FineScanRadius = 2;
[FieldLoader.LoadUsing("LoadConsiderations")]
[Desc("The decisions associated with this power")]
public readonly List<Consideration> Considerations = new List<Consideration>();
[Desc("Minimum ticks to wait until next Decision scan attempt.")]
public readonly int MinimumScanTimeInterval = 250;
[Desc("Maximum ticks to wait until next Decision scan attempt.")]
public readonly int MaximumScanTimeInterval = 262;
public SupportPowerDecision(MiniYaml yaml)
{
FieldLoader.Load(this, yaml);
}
static object LoadConsiderations(MiniYaml yaml)
{
var ret = new List<Consideration>();
foreach (var d in yaml.Nodes)
if (d.Key.Split('@')[0] == "Consideration")
ret.Add(new Consideration(d.Value));
return ret;
}
/// <summary>Evaluates the attractiveness of a position according to all considerations</summary>
public int GetAttractiveness(WPos pos, Player firedBy)
{
var answer = 0;
var world = firedBy.World;
var targetTile = world.Map.CellContaining(pos);
if (!world.Map.Contains(targetTile))
return 0;
foreach (var consideration in Considerations)
{
var radiusToUse = new WRange(consideration.CheckRadius.Range);
var checkActors = world.FindActorsInCircle(pos, radiusToUse);
foreach (var scrutinized in checkActors)
answer += consideration.GetAttractiveness(scrutinized, firedBy.Stances[scrutinized.Owner], firedBy);
}
return answer;
}
/// <summary>Evaluates the attractiveness of a group of actors according to all considerations</summary>
public int GetAttractiveness(IEnumerable<Actor> actors, Player firedBy)
{
var answer = 0;
foreach (var consideration in Considerations)
foreach (var scrutinized in actors)
answer += consideration.GetAttractiveness(scrutinized, firedBy.Stances[scrutinized.Owner], firedBy);
return answer;
}
public int GetNextScanTime(HackyAI ai) { return ai.Random.Next(MinimumScanTimeInterval, MaximumScanTimeInterval); }
/// <summary>Makes up part of a decision, describing how to evaluate a target.</summary>
public class Consideration
{
public enum DecisionMetric { Health, Value, None }
[Desc("Against whom should this power be used?", "Allowed keywords: Ally, Neutral, Enemy")]
public readonly Stance Against = Stance.Enemy;
[Desc("What types should the desired targets of this power be?")]
public readonly string[] Types = { "Air", "Ground", "Water" };
[Desc("How attractive are these types of targets?")]
public readonly int Attractiveness = 100;
[Desc("Weight the target attractiveness by this property", "Allowed keywords: Health, Value, None")]
public readonly DecisionMetric TargetMetric = DecisionMetric.None;
[Desc("What is the check radius of this decision?")]
public readonly WRange CheckRadius = WRange.FromCells(5);
public Consideration(MiniYaml yaml)
{
FieldLoader.Load(this, yaml);
}
/// <summary>Evaluates a single actor according to the rules defined in this consideration</summary>
public int GetAttractiveness(Actor a, Stance stance, Player firedBy)
{
if (stance != Against)
return 0;
if (a == null)
return 0;
var targetable = a.TraitOrDefault<ITargetable>();
if (targetable == null)
return 0;
if (!targetable.TargetableBy(a, firedBy.PlayerActor))
return 0;
if (Types.Intersect(targetable.TargetTypes).Any())
{
switch (TargetMetric)
{
case DecisionMetric.Value:
var valueInfo = a.Info.Traits.GetOrDefault<ValuedInfo>();
return (valueInfo != null) ? valueInfo.Cost * Attractiveness : 0;
case DecisionMetric.Health:
var health = a.TraitOrDefault<Health>();
return (health != null) ? (health.HP / health.MaxHP) * Attractiveness : 0;
default:
return Attractiveness;
}
}
return 0;
}
}
}
}

View File

@@ -40,7 +40,6 @@
<ErrorReport>prompt</ErrorReport>
<CustomCommands>
<CustomCommands>
<Command type="AfterBuild" command="cp ../thirdparty/FuzzyLogicLibrary.dll ../" workingdir="${ProjectDir}" />
<Command type="AfterBuild" command="cp ${TargetFile} ../mods/ra" workingdir="${ProjectDir}" />
<Command type="AfterBuild" command="cp ${TargetFile}.mdb ../mods/ra" workingdir="${ProjectDir}" />
</CustomCommands>
@@ -49,10 +48,6 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="FuzzyLogicLibrary">
<HintPath>..\thirdparty\FuzzyLogicLibrary.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
@@ -70,24 +65,18 @@
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="AI\AttackOrFleeFuzzy.cs" />
<Compile Include="AI\BaseBuilder.cs" />
<Compile Include="AI\HackyAI.cs" />
<Compile Include="Traits\AcceptsSupplies.cs" />
<Compile Include="Activities\DonateSupplies.cs" />
<Compile Include="Activities\Infiltrate.cs" />
<Compile Include="Activities\LayMines.cs" />
<Compile Include="Activities\Leap.cs" />
<Compile Include="Activities\Teleport.cs" />
<Compile Include="AI\SupportPowerDecision.cs" />
<Compile Include="Effects\GpsSatellite.cs" />
<Compile Include="Effects\SatelliteLaunch.cs" />
<Compile Include="Effects\TeslaZap.cs" />
<Compile Include="Traits\Render\RenderUnitReload.cs" />
<Compile Include="Graphics\TeslaZapRenderable.cs" />
<Compile Include="Traits\EjectOnDeath.cs" />
<Compile Include="AI\RushFuzzy.cs" />
<Compile Include="AI\StateMachine.cs" />
<Compile Include="Traits\Attack\AttackLeap.cs" />
<Compile Include="Traits\PaletteEffects\ChronoshiftPaletteEffect.cs" />
<Compile Include="Traits\Chronoshiftable.cs" />
@@ -136,11 +125,6 @@
<Compile Include="Widgets\Logic\CreditsLogic.cs" />
<Compile Include="Widgets\Logic\SimpleTooltipLogic.cs" />
<Compile Include="Widgets\Logic\WorldTooltipLogic.cs" />
<Compile Include="AI\Squad.cs" />
<Compile Include="AI\States\StateBase.cs" />
<Compile Include="AI\States\GroundStates.cs" />
<Compile Include="AI\States\ProtectionStates.cs" />
<Compile Include="AI\States\AirStates.cs" />
<Compile Include="Widgets\Logic\InstallLogic.cs" />
<Compile Include="CombatDebugOverlay.cs" />
<Compile Include="Widgets\Logic\GameTimerLogic.cs" />
@@ -204,8 +188,6 @@
<PropertyGroup>
<PostBuildEvent>mkdir "$(SolutionDir)mods/ra/"
copy "$(TargetPath)" "$(SolutionDir)mods/ra/"
cd "$(SolutionDir)thirdparty/"
copy "FuzzyLogicLibrary.dll" "$(SolutionDir)"
cd "$(SolutionDir)"</PostBuildEvent>
</PropertyGroup>
</Project>