forked from OpenRA/OpenRA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HackyAI.cs
473 lines (388 loc) · 14.3 KB
/
HackyAI.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#region Copyright & License Information
/*
* Copyright 2007-2011 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.FileFormats;
using OpenRA.Mods.RA.Buildings;
using OpenRA.Traits;
using XRandom = OpenRA.Thirdparty.Random;
//TODO:
// effectively clear the area around the production buildings' spawn points.
// don't spam the build unit button, only queue one unit then wait for the backoff period.
// just make the build unit action only occur once every second.
// later:
// don't build units randomly, have a method to it.
// explore spawn points methodically
// once you find a player, attack the player instead of spawn points.
namespace OpenRA.Mods.RA.AI
{
class HackyAIInfo : IBotInfo, ITraitInfo
{
public readonly string Name = "Unnamed Bot";
public readonly int SquadSize = 8;
public readonly int AssignRolesInterval = 20;
public readonly string RallypointTestBuilding = "fact"; // temporary hack to maintain previous rallypoint behavior.
public readonly string[] UnitQueues = { "Vehicle", "Infantry", "Plane" };
public readonly bool ShouldRepairBuildings = true;
string IBotInfo.Name { get { return this.Name; } }
[FieldLoader.LoadUsing("LoadUnits")]
public readonly Dictionary<string, float> UnitsToBuild = null;
[FieldLoader.LoadUsing("LoadBuildings")]
public readonly Dictionary<string, float> BuildingFractions = null;
static object LoadActorList(MiniYaml y, string field)
{
return y.NodesDict[field].Nodes.ToDictionary(
t => t.Key,
t => FieldLoader.GetValue<float>(field, t.Value.Value));
}
static object LoadUnits(MiniYaml y) { return LoadActorList(y, "UnitsToBuild"); }
static object LoadBuildings(MiniYaml y) { return LoadActorList(y, "BuildingFractions"); }
public object Create(ActorInitializer init) { return new HackyAI(this); }
}
/* a pile of hacks, which control a local player on the host. */
class Enemy { public int Aggro; }
class HackyAI : ITick, IBot, INotifyDamage
{
bool enabled;
public int ticks;
public Player p;
PowerManager playerPower;
readonly BuildingInfo rallypointTestBuilding; // temporary hack
readonly HackyAIInfo Info;
Cache<Player,Enemy> aggro = new Cache<Player, Enemy>( _ => new Enemy() );
int2 baseCenter;
XRandom random = new XRandom(); //we do not use the synced random number generator.
BaseBuilder[] builders;
const int MaxBaseDistance = 20;
public const int feedbackTime = 30; // ticks; = a bit over 1s. must be >= netlag.
public World world { get { return p.PlayerActor.World; } }
IBotInfo IBot.Info { get { return this.Info; } }
public HackyAI(HackyAIInfo Info)
{
this.Info = Info;
// temporary hack.
this.rallypointTestBuilding = Rules.Info[Info.RallypointTestBuilding].Traits.Get<BuildingInfo>();
}
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)
{
this.p = p;
enabled = true;
playerPower = p.PlayerActor.Trait<PowerManager>();
builders = new BaseBuilder[] {
new BaseBuilder( this, "Building", q => ChooseBuildingToBuild(q, true) ),
new BaseBuilder( this, "Defense", q => ChooseBuildingToBuild(q, false) ) };
}
int GetPowerProvidedBy(ActorInfo building)
{
var bi = building.Traits.GetOrDefault<BuildingInfo>();
if (bi == null) return 0;
return bi.Power;
}
ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue)
{
var buildableThings = queue.BuildableItems();
if (buildableThings.Count() == 0) return null;
return buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count()));
}
bool HasAdequatePower()
{
/* note: CNC `fact` provides a small amount of power. don't get jammed because of that. */
return playerPower.PowerProvided > 50 &&
playerPower.PowerProvided > playerPower.PowerDrained * 1.2;
}
ActorInfo ChooseBuildingToBuild(ProductionQueue queue, bool buildPower)
{
var buildableThings = queue.BuildableItems();
if (!HasAdequatePower()) /* try to maintain 20% excess power */
{
if (!buildPower) return null;
/* find the best thing we can build which produces power */
return buildableThings.Where(a => GetPowerProvidedBy(a) > 0)
.OrderByDescending(a => GetPowerProvidedBy(a)).FirstOrDefault();
}
var myBuildings = p.World
.ActorsWithTrait<Building>()
.Where( a => a.Actor.Owner == p )
.Select(a => a.Actor.Info.Name).ToArray();
foreach (var frac in Info.BuildingFractions)
if (buildableThings.Any(b => b.Name == frac.Key))
if (myBuildings.Count(a => a == frac.Key) < frac.Value * myBuildings.Length &&
playerPower.ExcessPower >= Rules.Info[frac.Key].Traits.Get<BuildingInfo>().Power)
return Rules.Info[frac.Key];
return null;
}
bool NoBuildingsUnder(IEnumerable<int2> cells)
{
var bi = world.WorldActor.Trait<BuildingInfluence>();
return cells.All(c => bi.GetBuildingAt(c) == null);
}
public int2? ChooseBuildLocation(string actorType)
{
var bi = Rules.Info[actorType].Traits.Get<BuildingInfo>();
for (var k = 0; k < MaxBaseDistance; k++)
foreach (var t in world.FindTilesInCircle(baseCenter, k))
if (world.CanPlaceBuilding(actorType, bi, t, null))
if (bi.IsCloseEnoughToBase(world, p, actorType, t))
if (NoBuildingsUnder(Util.ExpandFootprint(
FootprintUtils.Tiles(actorType, bi, t), false)))
return t;
return null; // i don't know where to put it.
}
public void Tick(Actor self)
{
if (!enabled)
return;
ticks++;
if (ticks == 10)
DeployMcv(self);
if (ticks % feedbackTime == 0)
foreach (var q in Info.UnitQueues)
BuildRandom(q);
AssignRolesToIdleUnits(self);
SetRallyPointsForNewProductionBuildings(self);
foreach (var b in builders)
b.Tick();
}
//hacks etc sigh mess.
//A bunch of hardcoded lists to keep track of which units are doing what.
List<Actor> unitsHangingAroundTheBase = new List<Actor>();
List<Actor> attackForce = new List<Actor>();
int2? attackTarget;
//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>();
int2? ChooseEnemyTarget()
{
var liveEnemies = world.Players
.Where(q => p != q && p.Stances[q] == Stance.Enemy)
.Where(q => p.WinState == WinState.Undefined && q.WinState == WinState.Undefined);
var leastLikedEnemies = liveEnemies
.GroupBy(e => aggro[e].Aggro)
.OrderByDescending(g => g.Key)
.FirstOrDefault();
if (leastLikedEnemies == null)
return null;
var enemy = leastLikedEnemies != null ? leastLikedEnemies.Random(random) : null;
/* pick something worth attacking owned by that player */
var targets = world.Actors
.Where(a => a.Owner == enemy && a.HasTrait<IOccupySpace>());
Actor target=null;
if (targets.Count()>0)
target = targets.Random(random);
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}", this.p.ClientIndex, enemy.ClientIndex);
return null;
}
/* bump the aggro slightly to avoid changing our mind */
if (leastLikedEnemies.Count() > 1)
aggro[enemy].Aggro++;
return target.Location;
}
int assignRolesTicks = 0;
void AssignRolesToIdleUnits(Actor self)
{
//HACK: trim these lists -- we really shouldn't be hanging onto all this state
//when it's invalidated so easily, but that's Matthew/Alli's problem.
activeUnits.RemoveAll(a => a.Destroyed);
unitsHangingAroundTheBase.RemoveAll(a => a.Destroyed);
attackForce.RemoveAll(a => a.Destroyed);
if (--assignRolesTicks > 0)
return;
else
assignRolesTicks = Info.AssignRolesInterval;
var newUnits = self.World.ActorsWithTrait<IMove>()
.Where(a => a.Actor.Owner == p && a.Actor.Info != Rules.Info["mcv"]
&& !activeUnits.Contains(a.Actor))
.Select(a => a.Actor).ToArray();
foreach (var a in newUnits)
{
BotDebug("AI: Found a newly built unit");
if (a.Info == Rules.Info["harv"])
world.IssueOrder( new Order( "Harvest", a, false ) );
else
unitsHangingAroundTheBase.Add(a);
activeUnits.Add(a);
}
/* Create an attack force when we have enough units around our base. */
// (don't bother leaving any behind for defense.)
int randomizedSquadSize = 0;
while (randomizedSquadSize <= Info.SquadSize-3)
{
randomizedSquadSize = random.Next(300);
}
if (unitsHangingAroundTheBase.Count >= randomizedSquadSize)
{
BotDebug("Launch an attack.");
if (attackForce.Count == 0)
{
attackTarget = ChooseEnemyTarget();
if (attackTarget == null)
return;
foreach (var a in unitsHangingAroundTheBase)
if (TryToMove(a, attackTarget.Value, true))
attackForce.Add(a);
unitsHangingAroundTheBase.Clear();
}
}
// If we have any attackers, let them scan for enemy units and stop and regroup if they spot any
if (attackForce.Count > 0)
{
bool foundEnemy = false;
foreach (var a1 in attackForce)
{
var enemyUnits = world.FindUnitsInCircle(a1.CenterLocation, Game.CellSize * 10)
.Where(unit => p.Stances[unit.Owner] == Stance.Enemy).ToList();
if (enemyUnits.Count > 0)
{
// Found enemy units nearby.
foundEnemy = true;
var enemy = enemyUnits.ClosestTo( a1.CenterLocation );
// Check how many own units we have gathered nearby...
var ownUnits = world.FindUnitsInCircle(a1.CenterLocation, Game.CellSize * 2)
.Where(unit => unit.Owner == p).ToList();
if (ownUnits.Count < randomizedSquadSize - 3)
{
// Not enough to attack. Send more units.
world.IssueOrder(new Order("Stop", a1, false));
foreach (var a2 in attackForce)
if (a2 != a1)
world.IssueOrder(new Order("AttackMove", a2, false) { TargetLocation = a1.Location });
}
else
{
// We have gathered sufficient units. Attack the nearest enemy unit.
foreach (var a2 in attackForce)
world.IssueOrder(new Order("Attack", a2, false) { TargetActor = enemy });
}
return;
}
}
if (!foundEnemy)
{
attackTarget = ChooseEnemyTarget();
if (attackTarget != null)
foreach (var a in attackForce)
TryToMove(a, attackTarget.Value, true);
}
}
}
bool IsRallyPointValid(int2 x)
{
// this is actually WRONG as soon as HackyAI is building units with a variety of
// movement capabilities. (has always been wrong)
return world.IsCellBuildable(x, rallypointTestBuilding);
}
void SetRallyPointsForNewProductionBuildings(Actor self)
{
var buildings = self.World.ActorsWithTrait<RallyPoint>()
.Where(rp => rp.Actor.Owner == p &&
!IsRallyPointValid(rp.Trait.rallyPoint)).ToArray();
if (buildings.Length > 0)
BotDebug("Bot {0} needs to find rallypoints for {1} buildings.",
p.PlayerName, buildings.Length);
foreach (var a in buildings)
{
int2 newRallyPoint = ChooseRallyLocationNear(a.Actor.Location);
world.IssueOrder(new Order("SetRallyPoint", a.Actor, false) { TargetLocation = newRallyPoint });
}
}
//won't work for shipyards...
int2 ChooseRallyLocationNear(int2 startPos)
{
var possibleRallyPoints = world.FindTilesInCircle(startPos, 8).Where(IsRallyPointValid).ToArray();
if (possibleRallyPoints.Length == 0)
{
BotDebug("Bot Bug: No possible rallypoint near {0}", startPos);
return startPos;
}
return possibleRallyPoints.Random(random);
}
int2? ChooseDestinationNear(Actor a, int2 desiredMoveTarget)
{
var move = a.TraitOrDefault<IMove>();
if (move == null) return null;
int2 xy;
int loopCount = 0; //avoid infinite loops.
int range = 2;
do
{
//loop until we find a valid move location
xy = new int2(desiredMoveTarget.X + random.Next(-range, range), desiredMoveTarget.Y + random.Next(-range, range));
loopCount++;
range = Math.Max(range, loopCount / 2);
if (loopCount > 10) return null;
} while (!move.CanEnterCell(xy) && xy != a.Location);
return xy;
}
//try very hard to find a valid move destination near the target.
//(Don't accept a move onto the subject's current position. maybe this is already not allowed? )
bool TryToMove(Actor a, int2 desiredMoveTarget, bool attackMove)
{
var xy = ChooseDestinationNear(a, desiredMoveTarget);
if (xy == null)
return false;
world.IssueOrder(new Order(attackMove ? "AttackMove" : "Move", a, false) { TargetLocation = xy.Value });
return true;
}
void DeployMcv(Actor self)
{
/* find our mcv and deploy it */
var mcv = self.World.Actors
.FirstOrDefault(a => a.Owner == p && a.Info == Rules.Info["mcv"]);
if (mcv != null)
{
baseCenter = mcv.Location;
world.IssueOrder(new Order("DeployTransform", mcv, false));
}
else
BotDebug("AI: Can't find the MCV.");
}
internal IEnumerable<ProductionQueue> FindQueues(string category)
{
return world.ActorsWithTrait<ProductionQueue>()
.Where(a => a.Actor.Owner == p && a.Trait.Info.Type == category)
.Select(a => a.Trait);
}
//Build a random unit of the given type. Not going to be needed once there is actual AI...
void BuildRandom(string category)
{
// Pick a free queue
var queue = FindQueues( category ).FirstOrDefault( q => q.CurrentItem() == null );
if (queue == null)
return;
var unit = ChooseRandomUnitToBuild(queue);
if (unit != null && Info.UnitsToBuild.Any( u => u.Key == unit.Name ))
world.IssueOrder(Order.StartProduction(queue.self, unit.Name, 1));
}
public void Damaged(Actor self, AttackInfo e)
{
if (!enabled) return;
if (Info.ShouldRepairBuildings && self.HasTrait<RepairableBuilding>())
if (e.DamageState > DamageState.Light && e.PreviousDamageState <= DamageState.Light)
{
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 != null && e.Damage > 0)
aggro[e.Attacker.Owner].Aggro += e.Damage;
}
}
}