File: ai_force.cpp

package info (click to toggle)
boswars 2.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 96,652 kB
  • sloc: cpp: 57,250; python: 1,715; sh: 25; makefile: 17
file content (661 lines) | stat: -rw-r--r-- 14,041 bytes parent folder | download | duplicates (5)
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//     ____                _       __               
//    / __ )____  _____   | |     / /___ ___________
//   / __  / __ \/ ___/   | | /| / / __ `/ ___/ ___/
//  / /_/ / /_/ (__  )    | |/ |/ / /_/ / /  (__  ) 
// /_____/\____/____/     |__/|__/\__,_/_/  /____/  
//                                              
//       A futuristic real-time strategy game.
//          This file is part of Bos Wars.
//
/**@name ai_force.cpp - AI force functions. */
//
//      (c) Copyright 2001-2009 by Lutz Sammer and Jimmy Salmon
//
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; only version 2 of the License.
//
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
//      02111-1307, USA.
//

//@{

/*----------------------------------------------------------------------------
--  Includes
----------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "stratagus.h"
#include "unittype.h"
#include "unit.h"
#include "ai_local.h"
#include "actions.h"
#include "map.h"
#include "pathfinder.h"
#include "player.h"

/*----------------------------------------------------------------------------
--  Variables
----------------------------------------------------------------------------*/

int UnitTypeEquivs[UnitTypeMax + 1]; /// equivalence between unittypes

/*----------------------------------------------------------------------------
--  Functions
----------------------------------------------------------------------------*/


/**
**  Remove any equivalence between unittypes
*/
void AiResetUnitTypeEquiv()
{
	for (int i = 0; i <= UnitTypeMax; ++i)
	{
		UnitTypeEquivs[i] = i;
	}
}

/**
**  Make two unittypes equivalents from the AI's point of vue
**
**  @param a  the first unittype
**  @param b  the second unittype
*/
void AiNewUnitTypeEquiv(CUnitType *a, CUnitType *b)
{
	int find;
	int replace;
	int i;

	find = UnitTypeEquivs[a->Slot];
	replace = UnitTypeEquivs[b->Slot];

	// Always record equivalences with the lowest unittype.
	if (find < replace)
	{
		i = find;
		find = replace;
		replace = i;
	}

	// Then just find & replace in UnitTypeEquivs...
	for (i = 0; i <= UnitTypeMax; ++i)
	{
		if (UnitTypeEquivs[i] == find)
		{
			UnitTypeEquivs[i] = replace;
		}
	}
}


/**
**  Find All unittypes equivalent to a given one
**
**  @param unittype  the unittype to find equivalence for
**  @param result    int array which will hold the result. (Size UnitTypeMax+1)
**
**  @return          the number of unittype found
*/
int AiFindUnitTypeEquiv(const CUnitType *unittype, int *result)
{
	int i;
	int search;
	int count;

	search = UnitTypeEquivs[unittype->Slot];
	count = 0;

	for (i = 0; i <= UnitTypeMax; ++i)
	{
		if (UnitTypeEquivs[i] == search)
		{
			// Found one
			result[count] = i;
			count++;
		}
	}

	return count;
}

/**
**  Find All unittypes equivalent to a given one, and which are available
**  UnitType are returned in the prefered order ( ie palladin >> knight... )
**
**  @param unittype     The unittype to find equivalence for
**  @param usableTypes  int array which will hold the result. (Size UnitTypeMax+1)
**
**  @return             the number of unittype found
*/
int AiFindAvailableUnitTypeEquiv(const CUnitType *unittype, int *usableTypes)
{
	int usableTypesCount;
	int bestlevel;
	int curlevel;

	// 1 - Find equivalents
	usableTypesCount = AiFindUnitTypeEquiv(unittype,  usableTypes);

	// 2 - Sort by level
	// We won't have usableTypesCount>4, so simple sort should do it
	for (int i = 0; i < usableTypesCount - 1; ++i)
	{
		bestlevel = UnitTypes[usableTypes[i]]->Priority;
		for (int j = i + 1; j < usableTypesCount; ++j)
		{
			curlevel = UnitTypes[usableTypes[j]]->Priority;

			if (curlevel > bestlevel)
			{
				// Swap
				int tmp = usableTypes[j];
				usableTypes[j] = usableTypes[i];
				usableTypes[i] = tmp;

				bestlevel = curlevel;
			}
		}
	}

	return usableTypesCount;
}

/**
**  Clean units in a force.
**
**  @param force  Force number.
*/
static void AiCleanForce(int force)
{
	CUnit *aiunit;
	const AiUnitType *aitype;
	int counter[UnitTypeMax + 1];
	size_t i;

	//
	// Release all killed units.
	//
	i = 0;
	while (i != AiPlayer->Force[force].Units.size())
	{
		aiunit = AiPlayer->Force[force].Units[i];
		if (aiunit->Destroyed ||
			aiunit->Orders[0]->Action == UnitActionDie)
		{
			aiunit->RefsDecrease();
			AiPlayer->Force[force].Units.erase(
				AiPlayer->Force[force].Units.begin() + i);
			continue;
		}
		++i;
	}

	//
	// Count units in force.
	//
	memset(counter, 0, sizeof(counter));
	for (i = 0; i < AiPlayer->Force[force].Units.size(); ++i)
	{
		aiunit = AiPlayer->Force[force].Units[i];
		counter[UnitTypeEquivs[aiunit->Type->Slot]]++;
	}

	//
	// Look if the force is complete.
	//
	AiPlayer->Force[force].Completed = true;
	for (i = 0; i < AiPlayer->Force[force].UnitTypes.size(); ++i)
	{
		aitype = &AiPlayer->Force[force].UnitTypes[i];
		if (aitype->Want > counter[aitype->Type->Slot])
		{
			AiPlayer->Force[force].Completed = false;
		}
		counter[aitype->Type->Slot] -= aitype->Want;
	}

	//
	// Release units too much in force.
	//
	if (!AiPlayer->Force[force].Attacking)
	{
		i = 0;
		while (i != AiPlayer->Force[force].Units.size())
		{
			aiunit = AiPlayer->Force[force].Units[i];
			if (counter[aiunit->Type->Slot] > 0)
			{
				counter[UnitTypeEquivs[aiunit->Type->Slot]]--;
				aiunit->RefsDecrease();
				AiPlayer->Force[force].Units.erase(
					AiPlayer->Force[force].Units.begin() + i);
				continue;
			}
			++i;
		}
	}
}

/**
**  Cleanup units in forces.
*/
void AiCleanForces()
{
	// Release all killed units.
	for (int force = 0; force < AI_MAX_ATTACKING_FORCES; ++force)
	{
		AiCleanForce(force);
	}
}

/**
**  Check if the units belongs to the force.
**
**  @param force  Force to be checked.
**  @param type   Type to check.
**
**  @return       True if it fits, false otherwise.
*/
static int AiCheckBelongsToForce(int force, const CUnitType *type)
{
	CUnit *aiunit;
	AiUnitType *aitype;
	int counter[UnitTypeMax + 1];
	int flag;
	int i;

	memset(counter, 0, sizeof(counter));
	//
	// Count units in force.
	//
	for (i = 0; i < (int)AiPlayer->Force[force].Units.size(); ++i)
	{
		aiunit = AiPlayer->Force[force].Units[i];
		counter[UnitTypeEquivs[aiunit->Type->Slot]]++;
	}

	//
	// Look what should be in the force.
	//
	flag = 0;
	AiPlayer->Force[force].Completed = true;
	for (i = 0; i < (int)AiPlayer->Force[force].UnitTypes.size(); ++i)
	{
		aitype = &AiPlayer->Force[force].UnitTypes[i];
		if (aitype->Want > counter[aitype->Type->Slot])
		{
			if (UnitTypeEquivs[type->Slot] == aitype->Type->Slot)
			{
				if (aitype->Want - 1 > counter[aitype->Type->Slot])
				{
					AiPlayer->Force[force].Completed = false;
				}
				flag = 1;
			}
			else
			{
				AiPlayer->Force[force].Completed = false;
			}
		}
	}
	return flag;
}

/**
**  Ai assign unit to force.
**
**  @param unit  Unit to assign to force.
*/
void AiAssignToForce(CUnit *unit)
{
	//
	// Check to which force it belongs
	//
	for (int force = 0; force < AI_MAX_FORCES; ++force)
	{
		// No troops for attacking force
		if (!AiPlayer->Force[force].Defending &&
			AiPlayer->Force[force].Attacking)
		{
			continue;
		}

		if (AiCheckBelongsToForce(force, unit->Type))
		{
			AiPlayer->Force[force].Units.insert(
				AiPlayer->Force[force].Units.begin(), unit);
			unit->RefsIncrease();
			break;
		}
	}
}

/**
**  Assign free units to force.
*/
void AiAssignFreeUnitsToForce()
{
	const CUnit *aiunit;
	CUnit *table[UnitMax];
	int n;
	int f;
	int i;

	AiCleanForces();

	n = AiPlayer->Player->TotalNumUnits;
	memcpy(table, AiPlayer->Player->Units, sizeof(*AiPlayer->Player->Units) * n);

	//
	// Remove all units already in forces.
	//
	for (f = 0; f < AI_MAX_ATTACKING_FORCES; ++f)
	{
		for (int j = 0; j < (int)AiPlayer->Force[f].Units.size(); ++j)
		{
			aiunit = AiPlayer->Force[f].Units[j];
			for (i = 0; i < n; ++i)
			{
				if (table[i] == aiunit)
				{
					table[i] = table[--n];
				}
			}
		}
	}

	//
	// Try to assign the remaining units.
	//
	for (i = 0; i < n; ++i)
	{
		AiAssignToForce(table[i]);
	}
}

/**
**  Attack at position with force.
**
**  @param force  Force number to attack with.
**  @param x      X tile map position to be attacked.
**  @param y      Y tile map position to be attacked.
*/
void AiAttackWithForceAt(int force, int x, int y)
{
	AiCleanForce(force);

	if (!AiPlayer->Force[force].Units.empty())
	{
		AiPlayer->Force[force].Attacking = true;

		//
		// Send all units in the force to enemy.
		//
		for (int i = 0; i < (int)AiPlayer->Force[force].Units.size(); ++i)
		{
			CUnit *aiunit = AiPlayer->Force[force].Units[i];
			aiunit->Wait = i;
			if (aiunit->Type->CanAttack)
			{
				CommandAttack(aiunit, x, y, NULL, FlushCommands);
			}
			else
			{
				CommandMove(aiunit, x, y, FlushCommands);
			}
		}
	}
}

/**
**  Attack opponent with force.
**
**  @param force  Force number to attack with.
*/
void AiAttackWithForce(int force)
{
	CUnit *aiunit;
	const CUnit *enemy;
	int x;
	int y;
	int f;
	int i;

	// Move the force to a free position so it can be used for a new
	// attacking party
	if (force < AI_MAX_FORCES)
	{
		f = AI_MAX_FORCES;
		while (AiPlayer->Force[f].Attacking)
		{
			++f;
			if (f == AI_MAX_ATTACKING_FORCES)
			{
				DebugPrint("No free attacking forces\n");
				f = force;
				break;
			}
		}
		if (f != AI_MAX_ATTACKING_FORCES)
		{
			AiPlayer->Force[f] = AiPlayer->Force[force];
			AiPlayer->Force[force].Reset();
		}

		force = f;
	}

	AiCleanForce(force);

	AiPlayer->Force[force].Attacking = false;
	if (!AiPlayer->Force[force].Units.empty())
	{
		AiPlayer->Force[force].Attacking = true;

		enemy = NULL;
		for (i = 0; !enemy && i < (int)AiPlayer->Force[force].Units.size(); ++i)
		{
			aiunit = AiPlayer->Force[force].Units[i];
			if (aiunit->Type->CanAttack)
			{
				enemy = AttackUnitsInDistance(aiunit, MaxMapWidth);
			}
		}

		if (!enemy)
		{
			DebugPrint("No enemy found\n");
			return;
		}
		AiPlayer->Force[force].State = 0;
		x = enemy->X;
		y = enemy->Y;

		//
		//  Send all units in the force to enemy.
		//
		for (i = 0; i < (int)AiPlayer->Force[force].Units.size(); ++i)
		{
			aiunit = AiPlayer->Force[force].Units[i];
			aiunit->Wait = i;
			if (aiunit->Type->CanAttack)
			{
				CommandAttack(aiunit, x, y, NULL, FlushCommands);
			}
			else
			{
				CommandMove(aiunit, x, y, FlushCommands);
			}
		}
	}
}

/**
** Force on attack ride. We attack until there is no unit or enemy left.
**
** @param force Force pointer.
*/
static void AiForceAttacks(AiForce *force)
{
	CUnit *aiunit;
	int x;
	int y;
	const CUnit *unit;
	int i;

	if (force->Units.empty())
	{
		force->Attacking = false;
		return;
	}

	// Find a unit that isn't idle
	unit = NoUnitP;
	for (i = 0; i < (int)force->Units.size(); ++i)
	{
		aiunit = force->Units[i];
		if (!aiunit->IsIdle())
		{
			// Found an idle unit, use it if we find nothing better
			if (unit == NoUnitP)
			{
				unit = aiunit;
			}
			// If the unit has a goal use it
			if (aiunit->Orders[0]->Goal != NoUnitP)
			{
				unit = aiunit;
				break;
			}
		}
	}

	if (unit != NoUnitP)
	{
		// Give idle units a new goal
		// FIXME: may not be a good goal
		for (i = 0; i < (int)force->Units.size(); ++i)
		{
			aiunit = force->Units[i];
			if (aiunit->IsIdle())
			{
				if (unit->Orders[0]->Goal)
				{
					x = unit->Orders[0]->Goal->X;
					y = unit->Orders[0]->Goal->Y;
				}
				else if (unit->Orders[0]->X != -1 && unit->Orders[0]->Y != -1)
				{
					x = unit->Orders[0]->X;
					y = unit->Orders[0]->Y;
				}
				else
				{
					x = unit->X;
					y = unit->Y;
				}
				if (aiunit->Type->CanAttack)
				{
					CommandAttack(aiunit, x, y, NULL, FlushCommands);
				}
				else
				{
					CommandMove(aiunit, x, y, FlushCommands);
				}
			}
		}
	}
	else
	{
		// Everyone is idle, find a new target
		unit = NULL;
		for (i = 0; i < (int)force->Units.size(); ++i)
		{
			aiunit = force->Units[i];
			if (aiunit->Type->CanAttack)
			{
				unit = AttackUnitsInDistance(aiunit, MaxMapWidth);
				break;
			}
		}
		if (!unit)
		{
			// No enemy found, give up
			// FIXME: should the force go home or keep trying to attack?
			DebugPrint("Attack force can't find a target, giving up\n");
			force->Attacking = false;
			return;
		}
		for (i = 0; i < (int)force->Units.size(); ++i)
		{
			aiunit = force->Units[i];
			if (aiunit->Type->CanAttack)
			{
				CommandAttack(aiunit, unit->X, unit->Y, NULL, FlushCommands);
			}
			else
			{
				CommandMove(aiunit, unit->X, unit->Y, FlushCommands);
			}
		}
	}
}

/**
**  Entry point of force manager, called each second.
*/
void AiForceManager()
{
	for (int force = 0; force < AI_MAX_ATTACKING_FORCES; ++force)
	{
		// Defending
		if (AiPlayer->Force[force].Defending)
		{
			const CUnit *aiunit = NULL;

			AiCleanForce(force);

			// Check if there are still enemies in attack range.
			for (size_t i = 0; i < AiPlayer->Force[force].Units.size(); ++i)
			{
				if (AiPlayer->Force[force].Units[i]->Type->CanAttack &&
					AttackUnitsInReactRange(AiPlayer->Force[force].Units[i]))
				{
					aiunit = AiPlayer->Force[force].Units[i];
					break;
				}
			}
			if (aiunit == NULL)
			{
				// No enemies go home.
				DebugPrint("FIXME: not written, should send force home\n");
				AiPlayer->Force[force].Defending = false;
				AiPlayer->Force[force].Attacking = false;
			}
		}

		// Attacking
		if (AiPlayer->Force[force].Attacking)
		{
			AiCleanForce(force);
			AiForceAttacks(&AiPlayer->Force[force]);
		}
	}

	AiAssignFreeUnitsToForce();
}

//@}