-
Notifications
You must be signed in to change notification settings - Fork 119
/
script_ai.cpp
2032 lines (1892 loc) · 57.8 KB
/
script_ai.cpp
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// _________ __ __
// / _____// |_____________ _/ |______ ____ __ __ ______
// \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/
// / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ |
// /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ >
// \/ \/ \//_____/ \/
// ______________________ ______________________
// T H E W A R B E G I N S
// Stratagus - A free fantasy real time strategy game engine
//
/**@name script_ai.cpp - The AI ccl functions. */
//
// (c) Copyright 2000-2015 by Lutz Sammer, Ludovic Pollet,
// Jimmy Salmon and Andrettin
//
// 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 "network.h"
#include "net_lowlevel.h"
#include "stratagus.h"
#include "ai.h"
#include "ai_local.h"
#include "interface.h"
#include "pathfinder.h"
#include "player.h"
#include "script.h"
#include "unit.h"
#include "unit_manager.h"
#include "unittype.h"
#include "upgrade.h"
/**
** Insert new unit-type element.
**
** @param table Table with elements.
** @param n Index to insert new into table
** @param base Base type to insert into table.
*/
static void AiHelperInsert(std::vector<std::vector<CUnitType *> > &table,
unsigned int n, CUnitType &base)
{
if (n >= table.size()) {
table.resize(n + 1);
}
// Look if already known
std::vector<CUnitType *>::const_iterator it = ranges::find(table[n], &base);
if (it != table[n].end()) {
return;
}
table[n].push_back(&base);
}
/**
** Transform list of unit separed with coma to a true list.
*/
static std::vector<CUnitType *> getUnitTypeFromString(const std::string &list)
{
std::vector<CUnitType *> res;
if (list == "*") {
return UnitTypes;
}
size_t begin = 1;
size_t end = list.find(",", begin);
while (end != std::string::npos) {
std::string unitName = list.substr(begin, end - begin);
begin = end + 1;
end = list.find(",", begin);
if (!unitName.empty()) {
Assert(unitName[0] != ',');
res.push_back(UnitTypeByIdent(unitName.c_str()));
}
}
return res;
}
/**
** Get list of unittype which can be repared.
*/
static std::vector<CUnitType *> getReparableUnits()
{
std::vector<CUnitType *> res;
for (CUnitType *type : UnitTypes) {
if (type->RepairHP > 0) {
res.push_back(type);
}
}
return res;
}
/**
** Get sorted list of unittype with Supply not null.
**
** @note Better (supply / cost) first.
*/
static std::vector<CUnitType *> getSupplyUnits()
{
std::vector<CUnitType *> res;
std::vector<CUnitType *> sorted_res;
for (CUnitType *type : UnitTypes) {
if (type->DefaultStat.Variables[SUPPLY_INDEX].Value > 0) { //supply units are identified as being those with a default stat supply of 1 or more; so if a unit has a supply default stat of 0, but through an upgrade ends up having 1 or more supply, it won't be included here
res.push_back(type);
}
}
// Now, sort them, best first.
while (!res.empty()) {
float bestscore = 0;
CUnitType *besttype = nullptr;
for (CUnitType *type : res) {
unsigned int cost = 0;
for (unsigned j = 0; j < MaxCosts; ++j) {
cost += type->DefaultStat.Costs[j]; //this cannot be MapDefaultStat because this function is called when the AiHelper is defined, rather than when a game is started
}
const float score = ((float) type->DefaultStat.Variables[SUPPLY_INDEX].Value) / cost;
if (score > bestscore) {
bestscore = score;
besttype = type;
}
}
sorted_res.push_back(besttype);
auto it = ranges::find(res, besttype);
if (it != res.end()) {
res.erase(it);
}
}
return sorted_res;
}
/**
** Get sorted list of unittype with CanHarvest not null.
**
** @note Better (MaxOnBoard / cost) first.
*/
static std::vector<CUnitType *> getRefineryUnits()
{
std::vector<CUnitType *> res;
for (CUnitType *type : UnitTypes) {
if (type->GivesResource > 0 && type->BoolFlag[CANHARVEST_INDEX].value) {
res.push_back(type);
}
}
#if 0
std::vector<CUnitType *> sorted_res;
// Now, sort them, best first.
while (!res.empty()) {
float bestscore;
CUnitType *besttype;
bestscore = 0;
for (CUnitType *type : res) {
float score;
unsigned int cost = 0;
for (unsigned j = 0; j < MaxCosts; ++j) {
cost += type->_Costs[j];
}
score = ((float) type->MaxOnBoard) / cost;
if (score > bestscore) {
bestscore = score;
besttype = type;
}
}
sorted_res.push_back(besttype);
auto it = ranges::find(res, besttype);
if (it != res.end()) {
res.erase(it);
}
}
return sorted_res;
#else
return res;
#endif
}
/**
** Init AiHelper.
**
** @param aiHelper variable to initialise.
**
** @todo missing Equiv initialisation.
*/
static void InitAiHelper(AiHelper &aiHelper)
{
extern std::vector<ButtonAction *> UnitButtonTable;
std::vector<CUnitType *> reparableUnits = getReparableUnits();
std::vector<CUnitType *> supplyUnits = getSupplyUnits();
std::vector<CUnitType *> mineUnits = getRefineryUnits();
for (CUnitType *type : supplyUnits) {
AiHelperInsert(aiHelper.UnitLimit(), 0, *type);
}
for (int i = 1; i < MaxCosts; ++i) {
for (CUnitType *type : mineUnits) {
if (type->GivesResource == i) {
/* HACK : we can't mine TIME then use 0 as 1 */
AiHelperInsert(aiHelper.Refinery(), i - 1, *type);
}
}
for (CUnitType *type : UnitTypes) {
if (type->CanStore[i] > 0) {
/* HACK : we can't store TIME then use 0 as 1 */
AiHelperInsert(aiHelper.Depots(), i - 1, *type);
}
}
}
for (size_t i = 0; i != UnitButtonTable.size(); ++i) {
const ButtonAction &button = *UnitButtonTable[i];
const std::vector<CUnitType *> &unitmask = getUnitTypeFromString(button.UnitMask);
switch (button.Action) {
case ButtonCmd::Repair :
for (CUnitType *type : unitmask) {
for (CUnitType *reparableUnit : reparableUnits) {
AiHelperInsert(aiHelper.Repair(), reparableUnit->Slot, *type);
}
}
break;
case ButtonCmd::Build: {
CUnitType *buildingType = UnitTypeByIdent(button.ValueStr);
for (CUnitType *type : unitmask) {
AiHelperInsert(aiHelper.Build(), buildingType->Slot, *type);
}
break;
}
case ButtonCmd::Train : {
CUnitType *trainingType = UnitTypeByIdent(button.ValueStr);
for (CUnitType *type : unitmask) {
AiHelperInsert(aiHelper.Train(), trainingType->Slot, *type);
}
break;
}
case ButtonCmd::UpgradeTo : {
CUnitType *upgradeToType = UnitTypeByIdent(button.ValueStr);
for (CUnitType *type : unitmask) {
AiHelperInsert(aiHelper.Upgrade(), upgradeToType->Slot, *type);
}
break;
}
case ButtonCmd::Research : {
int researchId = UpgradeIdByIdent(button.ValueStr);
if (button.Allowed == ButtonCheckSingleResearch) {
for (CUnitType *type : unitmask) {
AiHelperInsert(aiHelper.SingleResearch(), researchId, *type);
}
} else {
for (CUnitType *type : unitmask) {
AiHelperInsert(aiHelper.Research(), researchId, *type);
}
}
break;
}
default:
break;
}
}
}
/**
** Define helper for AI.
**
** @param l Lua state.
**
** @todo FIXME: the first unit could be a list see ../doc/ccl/ai.html
*/
static int CclDefineAiHelper(lua_State *l)
{
InitAiHelper(AiHelpers);
const int args = lua_gettop(l);
for (int j = 0; j < args; ++j) {
if (!lua_istable(l, j + 1)) {
LuaError(l, "incorrect argument");
}
const int subargs = lua_rawlen(l, j + 1);
const std::string_view value = LuaToString(l, j + 1, 1);
if (value == "build"
|| value == "train"
|| value == "upgrade"
|| value == "research"
|| value == "unit-limit"
|| value == "repair") {
#ifdef DEBUG
fprintf(stderr, "DefineAiHelper: Relation is computed from buttons, you may remove safely the block beginning with '\"%s\"'\n", value.data());
#endif
continue;
} else if (value == "unit-equiv") {
} else {
LuaError(l, "unknown tag: %s" _C_ value.data());
}
// Get the base unit type, which could handle the action.
const char *baseTypeName = LuaToString(l, j + 1, 2);
const CUnitType *base = UnitTypeByIdent(baseTypeName);
if (!base) {
LuaError(l, "unknown unittype: %s" _C_ baseTypeName);
}
// Get the unit types, which could be produced
for (int k = 2; k < subargs; ++k) {
const char *equivTypeName = LuaToString(l, j + 1, k + 1);
CUnitType *type = UnitTypeByIdent(equivTypeName);
if (!type) {
LuaError(l, "unknown unittype: %s" _C_ equivTypeName);
}
AiHelperInsert(AiHelpers.Equiv(), base->Slot, *type);
AiNewUnitTypeEquiv(*base, *type);
}
}
return 0;
}
static CAiType *GetAiTypesByName(const char *name)
{
for (size_t i = 0; i < AiTypes.size(); ++i) {
CAiType *ait = AiTypes[i];
if (ait->Name == name) {
return ait;
}
}
return nullptr;
}
/**
** <b>Description</b>
**
** Define an AI engine. Every game should define at least two AIs: one called 'ai-passive' and
** one called 'ai-active'. These two are the default AI names used by the games. 'ai-passive'
** is used almost everywhere when no other AI is selected by a map, and 'ai-active' is the default
** AI used when adding AI players to a multiplayer game when no other AI is selected by the map.
**
** Example:
**
** <div class="example"><code>-- Those instructions will be executed forever
** local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the functions from start.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** -- The initial instructions the A.I has to execute
** local simple_ai = {
** function() return AiSleep(1800) end, -- Sleep for 1 in game minute
** function() return AiNeed("unit-town-hall") end, -- One Town Hall is needed
** function() return AiWait("unit-town-hall") end, -- Wait until the Town Hall is completed
** function() return AiSet("unit-peasant", 4) end, -- Make 4 peasants
** -- Basic buildings
** function() return AiSet("unit-farm", 4) end, -- Make 4 farms
** function() return AiWait("unit-farm") end, -- Wait until all 4 farms are build.
** function() return AiNeed("unit-human-barracks") end, -- Need a Barracks
** function() return AiWait("unit-human-barracks") end, -- Wait until the Barracks has been built
** -- Defense force for the base
** function() return AiForce(1, {"unit-footman", 3}) end, -- Make a force of 3 footmen
** function() return AiWaitForce(1) end, -- Wait until the 3 footmen are trained
** function() return AiForceRole(1,"defend") end, -- Make this force as a defense force
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** -- function that calls the instructions in simple_ai inside DefineAi
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** -- Make an A.I for the human race that calls the function custom_ai
** <strong>DefineAi</strong>("ai-name","human","ai-class",custom_ai)</code></div>
*/
static int CclDefineAi(lua_State *l)
{
LuaCheckArgs(l, 4);
if (!lua_isfunction(l, 4)) {
LuaError(l, "incorrect argument");
}
CAiType *aitype = new CAiType;
// AI Name
const char *aiName = LuaToString(l, 1);
aitype->Name = aiName;
#ifdef DEBUG
if (GetAiTypesByName(aiName)) {
DebugPrint("Warning two or more AI's with the same name '%s'\n" _C_ aiName);
}
#endif
AiTypes.insert(AiTypes.begin(), aitype);
// AI Race
const char *value = LuaToString(l, 2);
if (*value != '*') {
aitype->Race = value;
} else {
aitype->Race.clear();
}
// AI Class
aitype->Class = LuaToString(l, 3);
// AI Script
lua_getglobal(l, "_ai_scripts_");
if (lua_isnil(l, -1)) {
lua_pop(l, 1);
lua_newtable(l);
lua_setglobal(l, "_ai_scripts_");
lua_getglobal(l, "_ai_scripts_");
}
aitype->Script = aitype->Name + aitype->Race + aitype->Class;
lua_pushstring(l, aitype->Script.c_str());
lua_pushvalue(l, 4);
lua_rawset(l, 5);
lua_pop(l, 1);
return 0;
}
/*----------------------------------------------------------------------------
-- AI script functions
----------------------------------------------------------------------------*/
/**
** Append unit-type to request table.
**
** @param type Unit-type to be appended.
** @param count How many unit-types to build.
*/
static void InsertUnitTypeRequests(CUnitType *type, int count)
{
AiRequestType ait;
ait.Type = type;
ait.Count = count;
AiPlayer->UnitTypeRequests.push_back(ait);
}
/**
** Find unit-type in request table.
**
** @param type Unit-type to be found.
*/
static AiRequestType *FindInUnitTypeRequests(const CUnitType *type)
{
const size_t n = AiPlayer->UnitTypeRequests.size();
for (size_t i = 0; i < n; ++i) {
if (AiPlayer->UnitTypeRequests[i].Type == type) {
return &AiPlayer->UnitTypeRequests[i];
}
}
return nullptr;
}
/**
** Find unit-type in upgrade-to table.
**
** @param type Unit-type to be found.
*/
static int FindInUpgradeToRequests(const CUnitType *type)
{
const size_t n = AiPlayer->UpgradeToRequests.size();
for (size_t i = 0; i < n; ++i) {
if (AiPlayer->UpgradeToRequests[i] == type) {
return 1;
}
}
return 0;
}
/**
** Append unit-type to request table.
**
** @param type Unit-type to be appended.
*/
static void InsertUpgradeToRequests(CUnitType *type)
{
AiPlayer->UpgradeToRequests.push_back(type);
}
/**
** Append unit-type to request table.
**
** @param upgrade Upgrade to be appended.
*/
static void InsertResearchRequests(CUpgrade *upgrade)
{
AiPlayer->ResearchRequests.push_back(upgrade);
}
//----------------------------------------------------------------------------
/**
** Get the race of the current AI player.
**
** @param l Lua state.
*/
static int CclAiGetRace(lua_State *l)
{
LuaCheckArgs(l, 0);
lua_pushstring(l, PlayerRaces.Name[AiPlayer->Player->Race].c_str());
return 1;
}
/**
** <b>Description</b>
**
** Get the number of cycles to sleep.
**
** @param l Lua state
**
** @return Number of return values
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the instructions forever.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** -- Get the number of cycles to sleep.
** function() return AiSleep(<strong>AiGetSleepCycles()</strong>) end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiGetSleepCycles(lua_State *l)
{
LuaCheckArgs(l, 0);
lua_pushnumber(l, AiSleepCycles);
return 1;
}
//----------------------------------------------------------------------------
/**
** Set debugging flag of AI script
**
** @param l Lua state
**
** @return Number of return values
*/
static int CclAiDebug(lua_State *l)
{
LuaCheckArgs(l, 1);
AiPlayer->ScriptDebug = LuaToBoolean(l, 1);
return 0;
}
/**
** Activate AI debugging for the given player(s)
** Player can be a number for a specific player
** "self" for current human player (ai me)
** "none" to disable
**
** @param l Lua State
**
** @return Number of return values
*/
static int CclAiDebugPlayer(lua_State *l)
{
const int args = lua_gettop(l);
for (int j = 0; j < args; ++j) {
std::string_view item;
if (lua_isstring(l, j + 1)) {
item = LuaToString(l, j + 1);
}
if (item == "none") {
for (int i = 0; i != NumPlayers; ++i) {
if (!Players[i].AiEnabled || !Players[i].Ai) {
continue;
}
Players[i].Ai->ScriptDebug = 0;
}
} else {
int playerid;
if (item == "self") {
if (!ThisPlayer) {
continue;
}
playerid = ThisPlayer->Index;
} else {
playerid = LuaToNumber(l, j + 1);
}
if (!Players[playerid].AiEnabled || !Players[playerid].Ai) {
continue;
}
Players[playerid].Ai->ScriptDebug = 1;
}
}
return 0;
}
/**
** <b>Description</b>
**
** Need a unit.
**
** @param l Lua state.
**
** @return Number of return values
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the instructions forever.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** function() return AiSleep(AiGetSleepCycles()) end,
** -- Tell to the A.I that it needs a Town Hall.
** function() return <strong>AiNeed</strong>("unit-town-hall") end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiNeed(lua_State *l)
{
LuaCheckArgs(l, 1);
InsertUnitTypeRequests(CclGetUnitType(l), 1);
lua_pushboolean(l, 0);
return 1;
}
/**
** <b>Description</b>
**
** Set the number of units.
**
** @param l Lua state
**
** @return Number of return values
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the instructions forever.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** function() return AiSleep(AiGetSleepCycles()) end,
** -- Tell to the A.I that it needs a Town Hall.
** function() return AiNeed("unit-town-hall") end,
** -- Wait until the town-hall has been built.
** function() return AiWait("unit-town-hall") end,
** -- Tell to the A.I that it needs 4 peasants
** function() return <strong>AiSet</strong>("unit-peasant",4) end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiSet(lua_State *l)
{
LuaCheckArgs(l, 2);
lua_pushvalue(l, 1);
CUnitType *type = CclGetUnitType(l);
lua_pop(l, 1);
AiRequestType *autt = FindInUnitTypeRequests(type);
if (autt) {
autt->Count = LuaToNumber(l, 2);
// FIXME: 0 should remove it.
} else {
InsertUnitTypeRequests(type, LuaToNumber(l, 2));
}
lua_pushboolean(l, 0);
return 1;
}
/**
** <b>Description</b>
**
** Wait for a unit.
**
** @param l Lua State.
**
** @return Number of return values
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the instructions forever.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** function() return AiSleep(AiGetSleepCycles()) end,
** -- Tell to the A.I that it needs a Town Hall.
** function() return AiNeed("unit-town-hall") end,
** -- Wait until the Town Hall has been built.
** function() return <strong>AiWait</strong>("unit-town-hall") end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiWait(lua_State *l)
{
LuaCheckArgs(l, 1);
const CUnitType *type = CclGetUnitType(l);
const int *unit_types_count = AiPlayer->Player->UnitTypesAiActiveCount;
const AiRequestType *autt = FindInUnitTypeRequests(type);
if (!autt) {
// Look if we have this unit-type.
if (unit_types_count[type->Slot]) {
lua_pushboolean(l, 0);
return 1;
}
// Look if we have equivalent unit-types.
if (type->Slot < (int)AiHelpers.Equiv().size()) {
for (size_t j = 0; j < AiHelpers.Equiv()[type->Slot].size(); ++j) {
if (unit_types_count[AiHelpers.Equiv()[type->Slot][j]->Slot]) {
lua_pushboolean(l, 0);
return 1;
}
}
}
// Look if we have an upgrade-to request.
if (FindInUpgradeToRequests(type)) {
lua_pushboolean(l, 1);
return 1;
}
DebugPrint("Broken? waiting on %s which wasn't requested.\n" _C_ type->Ident.c_str());
lua_pushboolean(l, 0);
return 1;
}
//
// Add equivalent units
//
unsigned int n = unit_types_count[type->Slot];
if (type->Slot < (int)AiHelpers.Equiv().size()) {
for (size_t j = 0; j < AiHelpers.Equiv()[type->Slot].size(); ++j) {
n += unit_types_count[AiHelpers.Equiv()[type->Slot][j]->Slot];
}
}
// units available?
if (n >= autt->Count) {
lua_pushboolean(l, 0);
return 1;
}
lua_pushboolean(l, 1);
return 1;
}
/**
** Get number of active build requests for a unit type.
**
** @param l Lua State.
**
** @return Number of return values
*/
static int CclAiPendingBuildCount(lua_State *l)
{
LuaCheckArgs(l, 1);
const CUnitType *type = CclGetUnitType(l);
// The assumption of this function is that UnitTypeBuilt will be always be
// fairly small so we iterate each time instead of doing any caching
for (auto b : AiPlayer->UnitTypeBuilt) {
if (b.Type == type) {
lua_pushinteger(l, b.Want);
return 1;
}
}
lua_pushinteger(l, 0);
return 1;
}
/**
** <b>Description</b>
**
** Define a force, a groups of units.
**
** @param l Lua state.
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** -- Sleep for 5 in game minutes
** function() return AiSleep(9000) end,
** -- Repeat the instructions forever.
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** function() return AiSleep(AiGetSleepCycles()) end,
** -- Tell to the A.I that it needs a Town Hall.
** function() return AiNeed("unit-town-hall") end,
** -- Wait until the Town Hall has been built.
** function() return AiWait("unit-town-hall") end,
** -- Tell to the A.I that it needs 4 peasants
** function() return AiSet("unit-peasant",4) end,
** -- Tell to the A.I that it needs a Barracks.
** function() return AiNeed("unit-human-barracks") end,
** -- Tell to the A.I that it needs a Lumbermill.
** function() return AiNeed("unit-elven-lumber-mill") end,
** -- Wait until the Barracks has been built.
** function() return AiWait("unit-human-barracks") end,
** -- Wait until the Lumbermill has been built.
** function() return AiWait("unit-elven-lumber-mill") end,
** -- Specify the force number 1 made only of 3 footmen
** function() return <strong>AiForce</strong>(1,{"unit-footman", 3}) end,
** -- Specify the force number 2 made only of 2 archers
** function() return <strong>AiForce</strong>(2,{"unit-archer", 2}) end,
** -- Specify the force number 3 made of 2 footmen and 1 archer
** function() return <strong>AiForce</strong>(3,{"unit-footman", 2, "unit-archer", 1}) end,
** -- Wait for all three forces
** function() return AiWaitForce(1) end,
** function() return AiWaitForce(2) end,
** function() return AiWaitForce(3) end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiForce(lua_State *l)
{
bool resetForce = false;
const int arg = lua_gettop(l);
Assert(0 < arg && arg <= 3);
if (!lua_istable(l, 2)) {
LuaError(l, "incorrect argument");
}
if (arg == 3) {
resetForce = LuaToBoolean(l, 3);
}
int force = LuaToNumber(l, 1);
if (force < 0 || force >= AI_MAX_FORCE_INTERNAL) {
LuaError(l, "Force out of range: %d" _C_ force);
}
AiForce &aiforce = AiPlayer->Force[AiPlayer->Force.getScriptForce(force)];
if (resetForce) {
aiforce.Reset(true);
}
AiForceRole role = aiforce.Role;
aiforce.State = AiForceAttackingState::Waiting;
aiforce.Role = role;
int args = lua_rawlen(l, 2);
for (int j = 0; j < args; ++j) {
lua_rawgeti(l, 2, j + 1);
CUnitType *type = CclGetUnitType(l);
lua_pop(l, 1);
++j;
int count = LuaToNumber(l, 2, j + 1);
if (!type) { // bulletproof
continue;
}
// Use the equivalent unittype.
type = UnitTypes[UnitTypeEquivs[type->Slot]];
if (resetForce) {
// Append it.
AiUnitType newaiut;
newaiut.Want = count;
newaiut.Type = type;
aiforce.UnitTypes.push_back(newaiut);
} else {
// Look if already in force.
size_t i;
for (i = 0; i < aiforce.UnitTypes.size(); ++i) {
AiUnitType *aiut = &aiforce.UnitTypes[i];
if (aiut->Type->Slot == type->Slot) { // found
if (count) {
aiut->Want = count;
} else {
aiforce.UnitTypes.erase(aiforce.UnitTypes.begin() + i);
}
break;
}
}
// New type append it.
if (i == aiforce.UnitTypes.size()) {
AiUnitType newaiut;
newaiut.Want = count;
newaiut.Type = type;
aiforce.UnitTypes.push_back(newaiut);
}
}
}
AiAssignFreeUnitsToForce(force);
lua_pushboolean(l, 0);
return 1;
}
/**
** <b>Description</b>
**
** Define the role of a force.
**
** @param l Lua state.
**
** Example:
**
** <div class="example"><code>local simple_ai_loop = {
** function() return AiSleep(9000) end,
** function() stratagus.gameData.AIState.loop_index[1 + AiPlayer()] = 0; return false; end,
** }
**
** local simple_ai = {
** function() return AiSleep(AiGetSleepCycles()) end,
** function() return AiNeed("unit-town-hall") end,
** function() return AiWait("unit-town-hall") end,
** function() return AiSet("unit-peasant",4) end,
** function() return AiNeed("unit-human-barracks") end,
** function() return AiNeed("unit-elven-lumber-mill") end,
** -- Force 1 has the role of attacker
** function() return <strong>AiForceRole</strong>(1,"<u>attack</u>") end,
** -- Force 2 has the role of defender
** function() return <strong>AiForceRole</strong>(2,"<u>defend</u>") end,
** function() return AiForce(1,{"unit-footman", 3}) end,
** function() return AiForce(2,{"unit-archer", 2}) end,
** function() return AiWaitForce(1) end,
** function() return AiWaitForce(2) end,
** -- Execute the instructions in simple_ai_loop
** function() return AiLoop(simple_ai_loop, stratagus.gameData.AIState.loop_index) end,
** }
**
** function custom_ai() return AiLoop(simple_ai,stratagus.gameData.AIState.index) end
** DefineAi("example_ai","human","class_ai",custom_ai)</code></div>
*/
static int CclAiForceRole(lua_State *l)
{
LuaCheckArgs(l, 2);
int force = LuaToNumber(l, 1);
if (force < 0 || force >= AI_MAX_FORCE_INTERNAL) {
LuaError(l, "Force %i out of range" _C_ force);
}
AiForce &aiforce = AiPlayer->Force[AiPlayer->Force.getScriptForce(force)];
const std::string_view flag = LuaToString(l, 2);
if (flag == "attack") {
aiforce.Role = AiForceRole::Attack;
} else if (flag == "defend") {
aiforce.Role = AiForceRole::Defend;
} else {
LuaError(l, "Unknown force role '%s'" _C_ flag.data());
}
lua_pushboolean(l, 0);
return 1;