source: tags/1.3.1/AI/StdAI/AI.pas

Last change on this file was 442, checked in by chronos, 2 years ago
  • Modified: Code cleanup.
File size: 108.5 KB
Line 
1{$INCLUDE Switches.inc}
2{//$DEFINE PERF}
3unit AI;
4
5interface
6
7uses
8{$IFDEF DEBUG}SysUtils, Names,{$ENDIF} // necessary for debug exceptions
9{$IFDEF PERF}SysUtils, Windows,{$ENDIF} // necessary for performance measurement
10 Protocol, CustomAI, ToolAI, Barbarina;
11
12const
13 WaitAfterReject = 20;
14 // don't try to contact this number of turn after contact was rejected
15 MinCityFood = 3;
16 LeaveDespotism = 80; // stay in despotism until this turn
17 TechReportOutdated = 30;
18 MilProdShare = 50;
19 // minimum share of total production to specialize in military production
20
21 FutureTech = [futResearchTechnology, futProductionTechnology,
22 futArmorTechnology, futMissileTechnology];
23
24 nResearchOrder = 46;
25 ResearchOrder: array[0..1, 0..nResearchOrder - 1] of integer =
26 ((adWheel, adWarriorCode, adHorsebackRiding, adCeremonialBurial, adPolytheism,
27 adMonarchy, adMysticism, adPoetry, adAstronomy, adMonotheism,
28 adTheology, adChivalry, adPottery, adMedicine, adGunpowder, adChemistry,
29 adExplosives, adUniversity, adTactics, adSeafaring, adNavigation, adRefining,
30 adCombustionEngine,
31 adAutomobile, adPhysics, adMagnetism, adElectricity, adRefrigeration,
32 adRadioCommunication, adTheoryOfGravity, adAtomicTheory, adElectronics,
33 adMassProduction, adPlastics, adFlight, adEnvironmentalism,
34 adSanitation, adMin, adComputers, adRecycling, adSyntheticFood,
35 adSelfContainedEnvironment, adNuclearFission, adNuclearPower, adTheLaser,
36 adIntelligenArms),
37 (adWheel, adWarriorCode, adHorsebackRiding, adAlphabet, adMapMaking,
38 adBronzeWorking, adWriting,
39 adCodeOfLaws, adCurrency, adTrade, adLiterature, adTheRepublic, adMathematics,
40 adPhilosophy, adScience, adMasonry, adConstruction, adEngineering, adInvention,
41 adIronWorking, adBridgeBuilding, adSteamEngine, adRailroad, adSteel,
42 adBanking, adIndustrialization, adConscription, adDemocracy, adEconomics,
43 adTheCorporation, adMassProduction, adRobotics, adCommunism, adMetallurgy,
44 adBallistics, adMobileWarfare, adAmphibiousWarfare, adMin, adComputers,
45 adRocketry, adAdvancedRocketry,
46 adAdvancedFlight, adSpaceFlight, adComposites, adIntelligence, adCombinedArms));
47
48 LeaveOutTechs = [adPolytheism, adMysticism, adInvention, adEconomics,
49 adPottery, adMedicine, adEnvironmentalism, adRefining, adTrade,
50 adLiterature, adMathematics, adPhilosophy, adChemistry, adConscription,
51 adCombustionEngine, adPhysics, adTheoryOfGravity, adAtomicTheory,
52 adSyntheticFood, adNuclearFission];
53
54 TechValue_ForResearch_LeaveOut = $700;
55 TechValue_ForResearch_Urgent = $600;
56 TechValue_ForResearch_Next = $400;
57 TechValue_ForResearch = $FF;
58 ForceNeeded_NoLeaveOut = 20; // advancedness behind to state-of-art
59 ForceNeeded_LeaveOut = 30; // advancedness behind of state-of-art
60 Compromise = 6;
61
62 // basic strategies
63 bGender = $0001;
64 bMale = $0000;
65 bFemale = $0001;
66 bBarbarina = $0006;
67 bBarbarina_Hide = $0002;
68
69 // model categories
70 nModelCat = 4;
71 mctNone = -1;
72 mctGroundDefender = 0;
73 mctGroundAttacker = 1;
74 mctTransport = 2;
75 mctCruiser = 3;
76
77 // mil research
78 BetterQuality: array[0..nModelCat - 1] of integer = (50, 50, 80, 80);
79 MaxBuildWorseThanBestModel = 20;
80 MaxExistWorseThanBestModel = 50;
81
82 maxCOD = 256;
83 PresenceUnknown = $10000;
84
85 nRequestedTechs = 48;
86
87 PlayerHash: array[0..nPl - 1] of integer =
88 (7, 6, 0, 2, 10, 8, 12, 14, 4, 1, 3, 5, 9, 11, 13);
89
90type
91 Suggestion = (suContact, suPeace, suFriendly);
92
93 TPersistentData = record
94 LastResearchTech, BehaviorFlags, TheologyPartner: integer;
95 RejectTurn: array[Suggestion, 0..15] of smallint;
96 RequestedTechs: array[0..nRequestedTechs - 1] of integer;
97 // ad + p shl 8 + Turn shl 16
98 end;
99
100 TAI = class(TBarbarina)
101 constructor Create(Nation: integer); override;
102
103 procedure SetDataDefaults; override;
104
105 protected
106 Data: ^TPersistentData;
107 WarNations, BombardingNations, mixSettlers, mixCaravan, mixTownGuard,
108 mixSlaves, mixMilitia, mixCruiser, OceanWithShip: integer;
109 NegoCause: (Routine, CheckBarbarina);
110 SettlerSurplus: array[0..maxCOD - 1] of integer;
111 uixPatrol: array[0..maxCOD - 1] of integer;
112
113 ContinentPresence: array[0..maxCOD - 1] of integer;
114 OceanPresence: array[0..maxCOD - 1] of integer;
115 UnitLack: array[0..maxCOD - 1, mctGroundDefender..mctGroundAttacker] of integer;
116
117 TotalPopulation: array[0..nPl - 1] of integer;
118 ContinentPopulation: array[0..nPl - 1, 0..maxCOD - 1] of integer;
119 // 1 means enemy territory spotted but no city
120 DistrictPopulation: array[0..maxCOD - 1] of integer;
121
122 ModelCat: array[0..nMmax - 1] of integer;
123 ModelQuality: array[0..nMmax - 1] of integer;
124 ModelBestQuality: array[0..nModelCat - 1] of integer;
125
126 AdvanceValue: array[0..nAdv - 1] of integer;
127 AdvanceValuesSet: boolean;
128
129 procedure DoTurn; override;
130 procedure DoNegotiation; override;
131 function ChooseResearchAdvance: integer; override;
132 function ChooseStealAdvance: integer; override;
133 function ChooseGovernment: integer; override;
134 function WantNegotiation(Nation: integer; NegoTime: TNegoTime): boolean; override;
135 function OnNegoRejected_CancelTreaty: boolean; override;
136
137 procedure FindBestTrade(Nation: integer; var adWanted, adGiveAway: integer);
138 procedure CheckGender;
139 procedure AnalyzeMap;
140 procedure CollectModelCatStat;
141 procedure AttackAndPatrol;
142 procedure MoveUnitsHome;
143 procedure CheckAttack(uix: integer);
144 procedure Patrol(uix: integer);
145 procedure SetCityProduction;
146 procedure SetAdvanceValues;
147 function HavePort: boolean;
148 {$IFDEF DEBUG}procedure TraceAdvanceValues(Nation: integer);{$ENDIF}
149
150 // research
151 procedure RateModel(const mi: TModelInfo; var Category, Quality: integer);
152 procedure RateMyModel(mix: integer; var Category, Quality: integer);
153 function IsBetterModel(const mi: TModelInfo): boolean;
154
155 //terraforming
156 procedure TileWorkPlan(Loc, cix: integer; var Value, NextJob, TotalWork: integer);
157 procedure ProcessSettlers;
158
159 // diplomacy
160 function MostWanted(Nation, adGiveAway: integer): integer;
161
162 end;
163
164
165implementation
166
167uses
168 Pile;
169
170const
171 // fine adjustment
172 Aggressive = 40; // 0 = never attacks, 100 = attacks even with heavy losses
173 DestroyBonus = 30; // percent of building cost
174
175var
176 LeaveOutValue: array[0..nAdv - 1] of integer;
177
178constructor TAI.Create(Nation: integer);
179begin
180 inherited;
181 Data := pointer(RO.Data);
182{$IFDEF DEBUG}
183 if Nation = 1 then
184 SetDebugMap(DebugMap);
185{$ENDIF}
186 AdvanceValuesSet := False;
187end;
188
189procedure TAI.SetDataDefaults;
190begin
191 with Data^ do
192 begin
193 LastResearchTech := -1;
194 if PlayerHash[me] > 7 then
195 BehaviorFlags := bFemale
196 else
197 BehaviorFlags := bMale;
198 DebugMessage(1, 'Gender:=' + char(48 + BehaviorFlags and bGender));
199 TheologyPartner := -1;
200 fillchar(RejectTurn, sizeof(RejectTurn), $FF);
201 Fillchar(RequestedTechs, sizeof(RequestedTechs), $FF);
202 end;
203end;
204
205function TAI.OnNegoRejected_CancelTreaty: boolean;
206begin
207 Data.RejectTurn[suContact, Opponent] := RO.Turn;
208 Result := Data.BehaviorFlags and bBarbarina <> 0;
209end;
210
211//-------------------------------
212// RESEARCH
213//-------------------------------
214
215procedure TAI.RateModel(const mi: TModelInfo; var Category, Quality: integer);
216var
217 EffectiveTransport: integer;
218begin
219 if mi.Kind >= mkScout then
220 begin
221 Category := mctNone;
222 exit;
223 end;
224 case mi.Domain of
225 dGround:
226 if mi.Speed >= 250 then
227 begin
228 Category := mctGroundAttacker;
229 if mi.Attack = 0 then
230 Quality := 0
231 else
232 begin
233 Quality := trunc(100 * (ln(mi.Attack) + ln(mi.Defense) +
234 ln(mi.Speed / 150) * 1.7 - ln(mi.Cost)));
235 if mi.Cap and (1 shl (mcFanatic - mcFirstNonCap)) <> 0 then
236 Inc(Quality, trunc(100 * ln(1.5)));
237 if mi.Cap and (1 shl (mcLongRange - mcFirstNonCap)) <> 0 then
238 Inc(Quality, trunc(100 * ln(1.5)));
239 end;
240 end
241 else
242 begin
243 Category := mctGroundDefender;
244 Quality := trunc(100 * (ln(mi.Defense) - ln(mi.Cost) * 0.6));
245 if mi.Cap and (1 shl (mcFanatic - mcFirstNonCap)) <> 0 then
246 Inc(Quality, trunc(100 * ln(1.5)));
247 end;
248 dSea:
249 if mi.Attack = 0 then
250 begin
251 Category := mctTransport;
252 if mi.TTrans = 0 then
253 Quality := 0
254 else
255 begin
256 EffectiveTransport := mi.TTrans;
257 if EffectiveTransport > 4 then
258 EffectiveTransport := 4; // rarely used more
259 Quality := 100 + trunc(100 * (ln(EffectiveTransport) +
260 ln(mi.Speed / 150) + ln(mi.Defense) - ln(mi.Cost)));
261 if mi.Cap and (1 shl (mcNav - mcFirstNonCap)) <> 0 then
262 Inc(Quality, trunc(100 * ln(1.5)));
263 if mi.Cap and (1 shl (mcAirDef - mcFirstNonCap)) <> 0 then
264 Inc(Quality, trunc(100 * ln(1.3)));
265 end;
266 end
267 else
268 begin
269 Category := mctCruiser;
270 if mi.Attack = 0 then
271 Quality := 0
272 else
273 begin
274 Quality := trunc(100 * (ln(mi.Attack) + ln(mi.Defense) * 0.6 - ln(mi.Cost)));
275 if mi.Cap and (1 shl (mcNav - mcFirstNonCap)) <> 0 then
276 Inc(Quality, trunc(100 * ln(1.4)));
277 if mi.Cap and (1 shl (mcAirDef - mcFirstNonCap)) <> 0 then
278 Inc(Quality, trunc(100 * ln(1.3)));
279 if mi.Cap and (1 shl (mcLongRange - mcFirstNonCap)) <> 0 then
280 Inc(Quality, trunc(100 * ln(2.0)));
281 if mi.Cap and (1 shl (mcRadar - mcFirstNonCap)) <> 0 then
282 Inc(Quality, trunc(100 * ln(1.5)));
283 end;
284 end;
285 dAir:
286 begin
287 Category := mctNone;
288 Quality := 0;
289 end;
290 end;
291 //!!!assert(Quality>0);
292end;
293
294procedure TAI.RateMyModel(mix: integer; var Category, Quality: integer);
295var
296 mi: TModelInfo;
297begin
298 MakeModelInfo(me, mix, MyModel[mix], mi);
299 RateModel(mi, Category, Quality);
300end;
301
302function TAI.IsBetterModel(const mi: TModelInfo): boolean;
303var
304 mix, Cat, Quality, Cat1, Quality1: integer;
305begin
306 RateModel(mi, Cat, Quality);
307 for mix := 0 to RO.nModel - 1 do
308 if mi.Domain = MyModel[mix].Domain then
309 begin
310 RateMyModel(mix, Cat1, Quality1);
311 if (Cat = Cat1) and (Quality < Quality1 + BetterQuality[Cat]) then
312 begin
313 Result := False;
314 exit;
315 end;
316 end;
317 Result := True;
318end;
319
320function TAI.ChooseResearchAdvance: integer;
321var
322 adNext, iad, i, ad, Count, EarliestNeeded, EarliestNeeded_NoLeaveOut,
323 NewResearch, StateOfArt, mix: integer;
324 mi: TModelInfo;
325 Entry: array[0..nAdv - 1] of boolean;
326 ok: boolean;
327
328 function MarkEntry(ad: integer): boolean;
329 begin
330 if RO.Tech[ad] >= tsApplicable then
331 Result := False // nothing more to research here
332 else if RO.Tech[ad] = tsSeen then
333 begin
334 Entry[ad] := True;
335 Result := True;
336 end
337 else
338 begin
339 Entry[ad] := True;
340 if ad = adScience then
341 begin
342 if MarkEntry(adTheology) then
343 Entry[ad] := False;
344 if MarkEntry(adPhilosophy) then
345 Entry[ad] := False;
346 end
347 else if ad = adMassProduction then
348 begin
349 if MarkEntry(adAutomobile) then
350 Entry[ad] := False;
351 if Data.BehaviorFlags and bGender = bMale then
352 begin
353 if MarkEntry(adElectronics) then
354 Entry[ad] := False;
355 end
356 else
357 begin
358 if MarkEntry(adTheCorporation) then
359 Entry[ad] := False;
360 end;
361 end
362 else
363 begin
364 if AdvPreq[ad, 0] >= 0 then
365 if MarkEntry(AdvPreq[ad, 0]) then
366 Entry[ad] := False;
367 if AdvPreq[ad, 1] >= 0 then
368 if MarkEntry(AdvPreq[ad, 1]) then
369 Entry[ad] := False;
370 end;
371 Result := True;
372 end;
373 end;
374
375 procedure OptimizeDevModel(OptimizeCaps: integer);
376 var
377 f, Cat, OriginalCat, Quality, BestQuality, Best: integer;
378 mi: TModelInfo;
379 begin
380 MakeModelInfo(me, 0, RO.DevModel, mi);
381 RateModel(mi, OriginalCat, BestQuality);
382 repeat
383 Best := -1;
384 for f := 0 to nFeature - 1 do
385 if (1 shl f and OptimizeCaps <> 0) and
386 ((Feature[f].Preq < 0) or IsResearched(Feature[f].Preq)) // check prerequisite
387 and (RO.DevModel.Weight + Feature[f].Weight <= RO.DevModel.MaxWeight) and
388 not ((f >= mcFirstNonCap) and (RO.DevModel.Cap[f] > 0)) then
389 begin
390 if SetNewModelFeature(f, RO.DevModel.Cap[f] + 1) >= rExecuted then
391 begin
392 MakeModelInfo(me, 0, RO.DevModel, mi);
393 RateModel(mi, Cat, Quality);
394 assert(Cat = OriginalCat);
395 if Quality > BestQuality then
396 begin
397 Best := f;
398 BestQuality := Quality;
399 end;
400 SetNewModelFeature(f, RO.DevModel.Cap[f] - 1);
401 end;
402 end;
403 if Best >= 0 then
404 SetNewModelFeature(Best, RO.DevModel.Cap[Best] + 1)
405 until Best < 0;
406 end;
407
408 function LeaveOutsMissing(ad: integer): boolean;
409 var
410 i: integer;
411 begin
412 Result := False;
413 if RO.Tech[ad] < tsSeen then
414 if ad in LeaveOutTechs then
415 Result := True
416 else if ad = adScience then
417 begin
418 Result := Result or LeaveOutsMissing(adTheology);
419 Result := Result or LeaveOutsMissing(adPhilosophy);
420 end
421 else if ad = adMassProduction then
422 Result := True
423 else
424 for i := 0 to 1 do
425 if AdvPreq[ad, i] >= 0 then
426 Result := Result or LeaveOutsMissing(AdvPreq[ad, i]);
427 end;
428
429begin
430 if Data.BehaviorFlags and bBarbarina <> 0 then
431 begin
432 Result := Barbarina_ChooseResearchAdvance;
433 if Result >= 0 then
434 exit;
435 end;
436
437 SetAdvanceValues;
438
439 // always complete traded techs first
440 Result := -1;
441 for ad := 0 to nAdv - 1 do
442 if (RO.Tech[ad] = tsSeen) and ((Result < 0) or
443 (AdvanceValue[ad] > AdvanceValue[Result])) then
444 Result := ad;
445 if Result >= 0 then
446 exit;
447
448 if Data.BehaviorFlags and bBarbarina = 0 then
449 begin
450 // develop new model?
451 if IsResearched(adWarriorCode) and IsResearched(adHorsebackRiding) and
452 not ((Data.BehaviorFlags and bGender = bMale) and
453 (RO.Tech[adIronWorking] >= tsApplicable) // wait for gunpowder
454 and (RO.Tech[adGunPowder] < tsApplicable)) then
455 begin // check new ground models
456 PrepareNewModel(dGround);
457 SetNewModelFeature(mcDefense, 1);
458 SetNewModelFeature(mcOffense, 2);
459 SetNewModelFeature(mcMob, 2);
460 OptimizeDevModel(1 shl mcOffense + 1 shl mcDefense + 1 shl
461 mcMob + 1 shl mcLongRange + 1 shl mcFanatic);
462 MakeModelInfo(me, 0, RO.DevModel, mi);
463 if IsBetterModel(mi) then
464 begin
465 Result := adMilitary;
466 exit;
467 end;
468
469 PrepareNewModel(dGround);
470 SetNewModelFeature(mcDefense, 2);
471 SetNewModelFeature(mcOffense, 1);
472 OptimizeDevModel(1 shl mcOffense + 1 shl mcDefense + 1 shl mcFanatic);
473 MakeModelInfo(me, 0, RO.DevModel, mi);
474 if IsBetterModel(mi) then
475 begin
476 Result := adMilitary;
477 exit;
478 end;
479 end;
480
481 if IsResearched(adMapMaking) and IsResearched(adSeafaring) and
482 IsResearched(adNavigation) and IsResearched(adSteamEngine) then
483 begin
484 Result := adMilitary;
485 for mix := 0 to RO.nModel - 1 do
486 if MyModel[mix].Cap[mcNav] > 0 then
487 Result := -1;
488 if Result = adMilitary then
489 begin
490 PrepareNewModel(dSea);
491 SetNewModelFeature(mcWeapons, 0);
492 SetNewModelFeature(mcDefense, 3);
493 exit;
494 end;
495 end;
496
497 (*
498 if IsResearched(adMapMaking) and IsResearched(adSeafaring) then
499 begin // check new naval models
500 PrepareNewModel(dSea);
501 if RO.DevModel.MTrans>1 then
502 begin // new transport?
503 SetNewModelFeature(mcDefense,2);
504 SetNewModelFeature(mcOffense,2);
505 SetNewModelFeature(mcSeaTrans,1);
506 OptimizeDevModel(1 shl mcDefense+1 shl mcSeaTrans+1 shl mcTurbines
507 +1 shl mcAirDef);
508 MakeModelInfo(me,0,RO.DevModel,mi);
509 if IsBetterModel(mi) then
510 begin result:=adMilitary; exit end;
511 end;
512
513 // new cruiser?
514 if IsResearched(adBallistics) or IsResearched(adGunPowder) then
515 begin
516 PrepareNewModel(dSea);
517 SetNewModelFeature(mcDefense,1);
518 SetNewModelFeature(mcOffense,2);
519 OptimizeDevModel(1 shl mcOffense+1 shl mcDefense
520 +1 shl mcLongRange+1 shl mcAirDef+1 shl mcRadar);
521 MakeModelInfo(me,0,RO.DevModel,mi);
522 if IsBetterModel(mi) then
523 begin result:=adMilitary; exit end;
524 end
525 end;
526 *)
527 end;
528
529 NewResearch := -1;
530
531 // check if cooperation with other gender doesn't work -- go for old needed techs then
532 StateOfArt := -1;
533 for ad := 0 to nAdv - 1 do
534 if (RO.Tech[ad] >= tsApplicable) and (Advancedness[ad] > StateOfArt) then
535 StateOfArt := Advancedness[ad];
536 EarliestNeeded := -1;
537 EarliestNeeded_NoLeaveOut := -1;
538 for ad := 0 to nAdv - 1 do
539 if (RO.Tech[ad] < tsSeen) and (AdvanceValue[ad] >= $100) and
540 ((EarliestNeeded < 0) or (Advancedness[ad] < Advancedness[EarliestNeeded])) then
541 begin
542 ok := False;
543 for iad := 0 to nResearchOrder - 1 do
544 if ResearchOrder[Data.BehaviorFlags and bGender, iad] = ad then
545 begin
546 ok := True;
547 break;
548 end;
549 if not ok then
550 begin
551 EarliestNeeded := ad;
552 if not LeaveOutsMissing(ad) then
553 EarliestNeeded_NoLeaveOut := ad;
554 end;
555 end;
556 if EarliestNeeded >= 0 then
557 begin
558 if (EarliestNeeded_NoLeaveOut >= 0) and
559 (Advancedness[EarliestNeeded_NoLeaveOut] + ForceNeeded_NoLeaveOut <
560 StateOfArt) then
561 begin
562 {$IFDEF DEBUG}
563 DebugMessage(2, 'No partner found, go for ' +
564 Name_Advance[EarliestNeeded_NoLeaveOut]);
565{$ENDIF}
566 NewResearch := EarliestNeeded_NoLeaveOut;
567 end
568 else if Advancedness[EarliestNeeded] + ForceNeeded_LeaveOut < StateOfArt then
569 begin
570 {$IFDEF DEBUG}
571 DebugMessage(2, 'No partner found, go for ' + Name_Advance[EarliestNeeded]);
572{$ENDIF}
573 NewResearch := EarliestNeeded;
574 end;
575 end;
576
577 // choose first directly researchable advance from own branch
578 adNext := -1;
579 if NewResearch < 0 then
580 for iad := 0 to nResearchOrder - 1 do
581 begin
582 ad := ResearchOrder[Data.BehaviorFlags and bGender, iad];
583 if RO.Tech[ad] < tsApplicable then
584 begin
585 if adNext < 0 then
586 adNext := ad;
587 if AdvPreq[ad, 2] <> preNone then
588 begin // 2 of 3 required
589 Count := 0;
590 for i := 0 to 2 do
591 if RO.Tech[AdvPreq[ad, i]] >= tsApplicable then
592 Inc(Count);
593 if Count >= 2 then
594 begin
595 Result := ad;
596 exit;
597 end;
598 end
599 else if ((AdvPreq[ad, 0] = preNone) or
600 (RO.Tech[AdvPreq[ad, 0]] >= tsApplicable)) and
601 ((AdvPreq[ad, 1] = preNone) or (RO.Tech[AdvPreq[ad, 1]] >= tsApplicable)) then
602 begin
603 Result := ad;
604 exit;
605 end;
606 end;
607 end;
608
609 if NewResearch < 0 then
610 if adNext >= 0 then
611 NewResearch := adNext // need tech from other gender
612 else if EarliestNeeded_NoLeaveOut >= 0 then
613 NewResearch := EarliestNeeded_NoLeaveOut
614 // own branch complete, pick tech from other gender
615 else if EarliestNeeded >= 0 then
616 NewResearch := EarliestNeeded // own branch complete, pick tech from other gender
617 else
618 begin // go for future techs
619 Result := -1;
620 i := 0;
621 for ad := nAdv - 4 to nAdv - 1 do
622 if (RO.Tech[ad] < MaxFutureTech) and (RO.Tech[AdvPreq[ad, 0]] >=
623 tsApplicable) then
624 begin
625 Inc(i);
626 if random(i) = 0 then
627 Result := ad;
628 end;
629 assert((Result < 0) or AdvanceResearchable(Result));
630 exit;
631 end;
632
633 assert(NewResearch >= 0);
634 fillchar(Entry, sizeof(Entry), False);
635 MarkEntry(NewResearch);
636 Result := -1;
637 for ad := 0 to nAdv - 1 do
638 if Entry[ad] and ((Result < 0) or (Advancedness[ad] > Advancedness[Result])) then
639 Result := ad;
640 assert(Result >= 0);
641end;
642
643function TAI.ChooseStealAdvance: integer;
644var
645 ad: integer;
646begin
647 Result := -1;
648 for ad := 0 to nAdv - 1 do
649 if AdvanceStealable(ad) and
650 ((Result < 0) or (Advancedness[ad] > Advancedness[Result])) then
651 Result := ad;
652end;
653
654//-------------------------------
655// TERRAFORMING
656//-------------------------------
657
658const
659 twpAllowFarmland = $0001;
660
661procedure TAI.TileWorkPlan(Loc, cix: integer; var Value, NextJob, TotalWork: integer);
662var
663 OldTile, TerrType: cardinal;
664 TileInfo: TTileInfo;
665begin
666 TotalWork := 0;
667 NextJob := jNone;
668 if Map[Loc] and (fRare1 or fRare2) <> 0 then
669 begin
670 Value := 3 * 8 - 1;
671 exit;
672 end; // better than any tile with 2 food
673
674 OldTile := Map[Loc];
675 TerrType := Map[Loc] and fTerrain;
676 if (TerrType >= fGrass) then
677 begin
678 if Map[Loc] and fPoll <> 0 then
679 begin // clean pollution
680 if NextJob = jNone then
681 NextJob := jPoll;
682 Inc(TotalWork, PollWork);
683 Map[Loc] := Map[Loc] and not fPoll;
684 end;
685 if Map[Loc] and (fTerrain or fSpecial) = fSwamp then
686 begin // drain swamp
687 if NextJob = jNone then
688 NextJob := jClear;
689 Inc(TotalWork, Terrain[TerrType].IrrClearWork);
690 Map[Loc] := Map[Loc] and not fTerrain or fGrass;
691 TerrType := fGrass;
692 Map[Loc] := Map[Loc] or cardinal(SpecialTile(Loc, TerrType, G.lx) shl 5);
693 end
694 else if IsResearched(adExplosives) and
695 (Map[Loc] and (fTerrain or fSpecial) in [fTundra, fHills]) and
696 (Map[Loc] and fTerImp <> tiMine) and (SpecialTile(Loc, fHills, G.lx) = 0) then
697 begin // transform
698 if NextJob = jNone then
699 NextJob := jTrans;
700 Inc(TotalWork, Terrain[TerrType].TransWork);
701 Map[Loc] := Map[Loc] and not fTerrain or fGrass;
702 TerrType := fGrass;
703 Map[Loc] := Map[Loc] or cardinal(SpecialTile(Loc, TerrType, G.lx) shl 5);
704 end;
705 if (Terrain[TerrType].MineEff > 0) and (RO.Government <> gDespotism) then
706 begin
707 if Map[Loc] and fTerImp <> tiMine then
708 begin // add mine
709 if NextJob = jNone then
710 NextJob := jMine;
711 Inc(TotalWork, Terrain[TerrType].MineAfforestWork);
712 Map[Loc] := Map[Loc] and not fTerImp or tiMine;
713 end;
714 end
715 else if Terrain[TerrType].IrrEff > 0 then
716 begin
717 if Map[Loc] and fTerImp = tiIrrigation then
718 begin // add farmland
719 if (MyCity[cix].Built[imSupermarket] > 0) and
720 IsResearched(adRefrigeration) and (RO.Government <> gDespotism) then
721 begin
722 if NextJob = jNone then
723 NextJob := jFarm;
724 Inc(TotalWork, Terrain[TerrType].IrrClearWork * FarmWork);
725 Map[Loc] := Map[Loc] and not fTerImp or tiFarm;
726 end;
727 end
728 else if Map[Loc] and fTerImp <> tiFarm then
729 begin // add irrigation
730 if (RO.Government <> gDespotism) or
731 (Map[Loc] and (fTerrain or fSpecial) <> fGrass) then
732 begin
733 if NextJob = jNone then
734 NextJob := jIrr;
735 Inc(TotalWork, Terrain[TerrType].IrrClearWork);
736 Map[Loc] := Map[Loc] and not fTerImp or tiIrrigation;
737 end;
738 end;
739 end;
740 if (Terrain[TerrType].MoveCost = 1) and (Map[Loc] and (fRoad or fRR) = 0) and
741 ((Map[Loc] and fRiver = 0) or IsResearched(adBridgeBuilding)) then
742 begin // add road
743 if NextJob = jNone then
744 NextJob := jRoad;
745 Inc(TotalWork, RoadWork);
746 Map[Loc] := Map[Loc] or fRoad;
747 end;
748 if ((Map[Loc] and fTerImp = tiMine) or
749 (Terrain[TerrType].ProdRes[Map[Loc] shr 5 and 3] >= 2)) and
750 IsResearched(adRailroad) and (Map[Loc] and fRR = 0) and
751 ((Map[Loc] and fRiver = 0) or IsResearched(adBridgeBuilding)) and
752 (RO.Government <> gDespotism) then
753 begin // add railroad
754 if Map[Loc] and fRoad = 0 then
755 begin
756 if NextJob = jNone then
757 NextJob := jRoad;
758 Inc(TotalWork, RoadWork * Terrain[TerrType].MoveCost);
759 end;
760 if NextJob = jNone then
761 NextJob := jRR;
762 Inc(TotalWork, RRWork * Terrain[TerrType].MoveCost);
763 Map[Loc] := Map[Loc] and not fRoad or fRR;
764 end;
765 end;
766 Server(sGetTileInfo, me, Loc, TileInfo);
767 Value := TileInfo.Food * 8 + TileInfo.Prod * 2 + TileInfo.Trade;
768 Map[Loc] := OldTile;
769end;
770
771// ProcessSettlers: move settlers, do terrain improvement, found cities
772procedure TAI.ProcessSettlers;
773var
774 i, uix, cix, ecix, dtr, Loc, RadiusLoc, Special, Food, Prod, Trade,
775 CityFood, Happy, TestScore, BestNearCityScore, BestUnusedValue,
776 BestUnusedLoc, Value, NextJob, TotalWork, V21, part, Loc1: integer;
777 Tile: cardinal;
778 FoodOk, Started: boolean;
779 Radius: TVicinity21Loc;
780 CityAreaInfo: TCityAreaInfo;
781 TileFood, ResourceScore, CityScore: array[0..lxmax * lymax - 1] of integer;
782
783 procedure AddJob(Loc, Job, Score: integer);
784 // set Score=1 for low-priority jobs
785 begin
786 JobAssignment_AddJob(Loc, Job, Score);
787 if (Score > 1) and (District[Loc] >= 0) and (District[Loc] < maxCOD) then
788 Dec(SettlerSurplus[District[Loc]]);
789 end;
790
791 procedure ReserveCityRadius(Loc: integer);
792 var
793 V21, RadiusLoc: integer;
794 Radius: TVicinity21Loc;
795 begin
796 V21_to_Loc(Loc, Radius);
797 for V21 := 1 to 26 do
798 begin
799 RadiusLoc := Radius[V21];
800 if (RadiusLoc >= 0) then
801 begin
802 ResourceScore[RadiusLoc] := 0;
803 TileFood[RadiusLoc] := 0;
804 end;
805 end;
806 end;
807
808 procedure ScoreRoadConnections;
809 var
810 V8, nFragments, Loc, Loc1, History, RoadScore, a, b, FullyDeveloped,
811 ConnectMask: integer;
812 BridgeOk: boolean;
813 Adjacent: TVicinity8Loc;
814 begin
815 BridgeOk := IsResearched(adBridgeBuilding);
816 if IsResearched(adRailroad) then
817 FullyDeveloped := fRR or fCity
818 else
819 FullyDeveloped := fRoad or fRR or fCity;
820 for Loc := G.lx to G.lx * (G.ly - 1) - 1 do
821 if ((1 shl (Map[Loc] and fTerrain)) and (1 shl fOcean or 1 shl
822 fShore or 1 shl fDesert or 1 shl fArctic or 1 shl fUNKNOWN) = 0) and
823 (RO.Territory[Loc] = me) and (Map[Loc] and FullyDeveloped = 0) and
824 (BridgeOk or (Map[Loc] and fRiver = 0)) then
825 begin
826 nFragments := 0;
827 History := 0;
828 if Map[Loc] and fRoad <> 0 then
829 ConnectMask := fRR or fCity // check for railroad
830 else
831 ConnectMask := fRoad or fRR or fCity; // check for road
832 V8_to_Loc(Loc, Adjacent);
833 for V8 := 0 to 9 do
834 begin
835 Loc1 := Adjacent[V8 and 7];
836 History := History shl 1;
837 if (Loc1 >= 0) and (RO.Territory[Loc1] = me) and
838 (Map[Loc1] and ConnectMask <> 0) then
839 begin
840 Inc(History);
841 if V8 >= 2 then
842 begin
843 Inc(nFragments);
844 case V8 and 1 of
845 0:
846 if History and 6 <> 0 then
847 Dec(nFragments);
848 1:
849 if History and 2 <> 0 then
850 Dec(nFragments)
851 else if History and 4 <> 0 then
852 begin
853 V8_to_ab((V8 - 1) and 7, a, b);
854 ab_to_Loc(Loc, a shl 1, b shl 1, Loc1);
855 if (Loc1 >= 0) and (Map[Loc1] and ConnectMask <> 0) then
856 Dec(nFragments);
857 end
858 end;
859 end;
860 end;
861 end;
862 if nFragments >= 2 then // road or railroad connection desirable
863 begin
864 if Map[Loc] and fRiver <> 0 then
865 RoadScore := 44 + (nFragments - 2) * 4
866 else
867 RoadScore := 56 - Terrain[Map[Loc] and fTerrain].MoveCost * 4 +
868 (nFragments - 2) * 4;
869 if Map[Loc] and fRoad <> 0 then
870 AddJob(Loc, jRR, RoadScore)
871 else
872 AddJob(Loc, jRoad, RoadScore);
873 end;
874 end;
875 end;
876
877begin
878 fillchar(SettlerSurplus, sizeof(SettlerSurplus), 0);
879 JobAssignment_Initialize;
880
881 if (Data.BehaviorFlags and bBarbarina = 0) or (RO.nCity < 3) then
882 begin
883 fillchar(TileFood, sizeof(TileFood), 0);
884 fillchar(ResourceScore, sizeof(ResourceScore), 0);
885 for Loc := 0 to MapSize - 1 do
886 if Map[Loc] and fTerrain <> fUNKNOWN then
887 if Map[Loc] and fDeadLands <> 0 then
888 begin
889 if not IsResearched(adMassProduction) or (Map[Loc] and fModern <> 0) then
890 ResourceScore[Loc] := 20;
891 end
892 else if Map[Loc] and fTerrain = fGrass then
893 TileFood[Loc] := Terrain[fGrass].FoodRes[Map[Loc] shr 5 and 3] - 1
894 else
895 begin
896 Special := SpecialTile(Loc, Map[Loc] and fTerrain, G.lx);
897 if Special <> 0 then
898 with Terrain[Map[Loc] and fTerrain] do
899 begin
900 Food := FoodRes[Special];
901 if MineEff = 0 then
902 Inc(Food, IrrEff);
903 Prod := ProdRes[Special] + MineEff;
904 Trade := TradeRes[Special];
905 if MoveCost = 1 then
906 Inc(Trade);
907 ResourceScore[Loc] := Food + 2 * Prod + Trade - 7;
908 if Food > 2 then
909 TileFood[Loc] := Food - 2;
910 end;
911 end;
912
913 for cix := 0 to RO.nCity - 1 do
914 if MyCity[cix].Loc >= 0 then
915 ReserveCityRadius(MyCity[cix].Loc); // these resources already have a city
916 for uix := 0 to RO.nUn - 1 do
917 if (MyUnit[uix].Loc >= 0) and (MyUnit[uix].Job = jCity) then
918 ReserveCityRadius(MyUnit[uix].Loc); // these resources almost already have a city
919 for ecix := 0 to RO.nEnemyCity - 1 do
920 if RO.EnemyCity[ecix].Loc >= 0 then
921 ReserveCityRadius(RO.EnemyCity[ecix].Loc);
922 // these resources already have an enemy city
923
924 // rate possible new cities
925 fillchar(CityScore, MapSize * sizeof(integer), 0);
926 for Loc := 0 to MapSize - 1 do
927 begin
928 FoodOk := (TileFood[Loc] > 0) and
929 ((Map[Loc] and fTerrain = fGrass) and
930 ((RO.Government <> gDespotism) or (Map[Loc] and fSpecial = fSpecial1)) or
931 (Map[Loc] and (fTerrain or fSpecial) = fPrairie or fSpecial1));
932 if FoodOk and ((RO.Territory[Loc] < 0) or (RO.Territory[Loc] = me)) then
933 begin
934 TestScore := 0;
935 CityFood := 0;
936 BestNearCityScore := 0;
937 V21_to_Loc(Loc, Radius);
938 for V21 := 1 to 26 do
939 begin // sum resource scores in potential city radius
940 RadiusLoc := Radius[V21];
941 if (RadiusLoc >= 0) then
942 begin
943 Inc(CityFood, TileFood[RadiusLoc]);
944 if ResourceScore[RadiusLoc] > 0 then
945 Inc(TestScore, ResourceScore[RadiusLoc]);
946 if CityScore[RadiusLoc] > BestNearCityScore then
947 BestNearCityScore := CityScore[RadiusLoc];
948 end;
949 end;
950 if CityFood >= MinCityFood then // city is worth founding
951 begin
952 TestScore := (72 + 2 * TestScore) shl 8 + ((loc xor me) * 4567) mod 251;
953 // some unexactness, random but always the same for this tile
954 if TestScore > BestNearCityScore then
955 begin // better than all other sites in radius
956 if BestNearCityScore > 0 then // found no other cities in radius
957 begin
958 for V21 := 1 to 26 do
959 begin
960 RadiusLoc := Radius[V21];
961 if (RadiusLoc >= 0) then
962 CityScore[RadiusLoc] := 0;
963 end;
964 end;
965 CityScore[Loc] := TestScore;
966 end;
967 end;
968 end;
969 end;
970 for Loc := 0 to MapSize - 1 do
971 if CityScore[Loc] > 0 then
972 AddJob(Loc, jCity, CityScore[Loc] shr 8);
973 end;
974
975 // improve terrain
976 for cix := 0 to RO.nCity - 1 do
977 with MyCity[cix] do
978 if Loc >= 0 then
979 begin // order terrain improvements
980 BestUnusedValue := 0;
981 City_GetAreaInfo(cix, CityAreaInfo);
982 V21_to_Loc(Loc, Radius);
983 for V21 := 1 to 26 do
984 if V21 <> CityOwnTile then
985 if 1 shl V21 and Tiles <> 0 then
986 begin // tile is being exploited!
987 RadiusLoc := Radius[V21];
988 if not (Map[RadiusLoc] and fTerrain in [fDesert, fArctic]) then
989 begin
990 assert(RadiusLoc >= 0);
991 TileWorkPlan(RadiusLoc, cix, Value, NextJob, TotalWork);
992 if (NextJob = jRoad) and (Built[imPalace] +
993 Built[imCourt] + Built[imTownHall] = 0) then
994 AddJob(RadiusLoc, NextJob, 44)
995 else if NextJob <> jNone then
996 AddJob(RadiusLoc, NextJob, 84);
997 end;
998 end
999 else if CityAreaInfo.Available[V21] = faAvailable then
1000 begin // tile could be exploited
1001 RadiusLoc := Radius[V21];
1002 assert(RadiusLoc >= 0);
1003 if not (Map[RadiusLoc] and fTerrain in [fDesert, fArctic]) then
1004 begin
1005 TileWorkPlan(RadiusLoc, cix, Value, NextJob, TotalWork);
1006 Value := Value shl 16 + $FFFF - TotalWork;
1007 if Value > BestUnusedValue then
1008 begin
1009 BestUnusedValue := Value;
1010 BestUnusedLoc := RadiusLoc;
1011 end;
1012 end;
1013 end;
1014 if BestUnusedValue > 0 then
1015 begin
1016 TileWorkPlan(BestUnusedLoc, cix, Value, NextJob, TotalWork);
1017 if NextJob <> jNone then
1018 AddJob(BestUnusedLoc, NextJob, 44);
1019 end;
1020 end;
1021
1022 ScoreRoadConnections;
1023
1024 if Data.BehaviorFlags and bBarbarina = 0 then // low priority jobs
1025 for Loc := 0 to MapSize - 1 do
1026 if RO.Territory[Loc] = me then
1027 begin
1028 Tile := Map[Loc];
1029 if Tile and fPoll <> 0 then
1030 AddJob(Loc, jPoll, 1)
1031 else
1032 case Tile and (fTerrain or fSpecial or fCity) of
1033 fGrass, fGrass + fSpecial1:
1034 if IsResearched(adExplosives) and (SpecialTile(Loc, fHills, G.lx) > 0) then
1035 AddJob(Loc, jTrans, 1);
1036 fSwamp:
1037 if SpecialTile(Loc, fSwamp, G.lx) = 0 then
1038 AddJob(Loc, jClear, 1);
1039 fTundra, fHills:
1040 if IsResearched(adExplosives) and (Tile and fTerImp <> tiMine) and
1041 (SpecialTile(Loc, fHills, G.lx) = 0) then
1042 AddJob(Loc, jTrans, 1);
1043 end;
1044 end;
1045
1046 // cities for colony ship production
1047 if Data.BehaviorFlags and bBarbarina = bBarbarina then
1048 begin
1049 for part := 0 to nShipPart - 1 do
1050 for i := 0 to ColonyShipPlan[part].nLocFoundCity - 1 do
1051 begin
1052 Loc := ColonyShipPlan[part].LocFoundCity[i];
1053 Started := False;
1054 for uix := 0 to RO.nUn - 1 do
1055 if (MyUnit[uix].Loc = Loc) and (MyUnit[uix].Job = jCity) then
1056 begin
1057 Started := True;
1058 break;
1059 end;
1060 if not Started then
1061 begin
1062 Tile := RO.Map[Loc];
1063 if (Tile and fTerrain = fForest) or (Tile and fTerrain = fSwamp) then
1064 AddJob(Loc, jClear, 235)
1065 else if Tile and fTerrain = fHills then
1066 begin
1067 if IsResearched(adExplosives) then
1068 AddJob(Loc, jTrans, 235);
1069 end
1070 else
1071 AddJob(Loc, jCity, 235);
1072 end;
1073 V21_to_Loc(Loc, Radius);
1074 for V21 := 1 to 26 do
1075 begin
1076 Loc1 := Radius[V21];
1077 if (Loc1 >= 0) and (RO.Map[Loc1] and (fTerrain or fSpecial) = fSwamp) then
1078 AddJob(Loc1, jClear, 255);
1079 end;
1080 end;
1081 end;
1082
1083 // choose all settlers to work
1084 for uix := 0 to RO.nUn - 1 do
1085 with MyUnit[uix] do
1086 if (Loc >= 0) and ((mix = mixSettlers) or (mix = mixSlaves) or
1087 (Data.BehaviorFlags and bBarbarina <> 0) and
1088 (MyModel[mix].Kind = mkSettler)) then
1089 begin
1090 JobAssignment_AddUnit(uix);
1091 if (District[Loc] >= 0) and (District[Loc] < maxCOD) then
1092 Inc(SettlerSurplus[District[Loc]]);
1093 end;
1094
1095 JobAssignment_Go;
1096
1097 for uix := 0 to RO.nUn - 1 do
1098 with MyUnit[uix] do
1099 if (Loc >= 0) and (Map[Loc] and fCity = 0) and (Job = jNone) and
1100 ((mix = mixSettlers) or (mix = mixSlaves)) and not JobAssignment_GotJob(uix) then
1101 Unit_MoveEx(uix, maNextCity);
1102
1103 //{$IFDEF DEBUG}DebugMessage(2, Format('Settler surplus in district 0: %d',[SettlerSurplus[0]]));{$ENDIF}
1104
1105 // add settlers to city
1106 for uix := 0 to RO.nUn - 1 do
1107 with MyUnit[uix] do
1108 if (Loc >= 0) and (Map[Loc] and fCity <> 0) and
1109 (MyModel[MyUnit[uix].mix].Kind = mkSettler) then
1110 begin
1111 dtr := District[Loc];
1112 if (mix <> mixSettlers) or (dtr >= 0) and (dtr < maxCOD) and
1113 (SettlerSurplus[dtr] > DistrictPopulation[dtr] div 8) then
1114 begin
1115 City_FindMyCity(Loc, cix);
1116 with MyCity[cix] do
1117 if (Built[imSewer] > 0) or (Built[imAqueduct] > 0) and
1118 (Size <= NeedSewerSize - 2) or (Size <= NeedAqueductSize - 2) then
1119 begin // settlers could be added to this city
1120 Happy := BasicHappy;
1121 for i := 0 to nWonder - 1 do
1122 if Built[i] > 0 then
1123 Inc(Happy);
1124 if Built[imTemple] > 0 then
1125 Inc(Happy);
1126 if Built[imCathedral] > 0 then
1127 begin
1128 Inc(Happy, 2);
1129 if RO.Wonder[woBach].EffectiveOwner = me then
1130 Inc(Happy, 1);
1131 end;
1132 if Built[imTheater] > 0 then
1133 Inc(Happy, 2);
1134 if (Built[imColosseum] > 0) or (Happy shl 1 >= Size + 2) then
1135 begin // bigger city would be happy
1136 // {$IFDEF DEBUG}DebugMessage(2, Format('Adding settlers to city at %d',[Loc]));{$ENDIF}
1137 Unit_AddToCity(uix);
1138 if (dtr >= 0) and (dtr < maxCOD) then
1139 Dec(SettlerSurplus[dtr]);
1140 end;
1141 end;
1142 end;
1143 end;
1144end;
1145
1146//-------------------------------
1147// MY TURN
1148//-------------------------------
1149
1150procedure TAI.DoTurn;
1151var
1152 emix, i, p1, TaxSum, ScienceSum, NewTaxRate: integer;
1153 AllHateMe: boolean;
1154{$IFDEF PERF}
1155 PF, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9: int64;
1156{$ENDIF}
1157begin
1158{$IFDEF DEBUG}
1159 fillchar(DebugMap, sizeof(DebugMap), 0);
1160{$ENDIF}
1161
1162{$IFDEF PERF}
1163 QueryPerformanceFrequency(PF);
1164{$ENDIF}
1165{$IFDEF PERF}
1166 QueryPerformanceCounter(t0);
1167{$ENDIF}
1168
1169 WarNations := PresenceUnknown;
1170 for p1 := 0 to nPl - 1 do
1171 if (p1 <> me) and (1 shl p1 and RO.Alive <> 0) and (RO.Treaty[p1] < trPeace) then
1172 Inc(WarNations, 1 shl p1);
1173 BombardingNations := 0;
1174 for emix := 0 to RO.nEnemyModel - 1 do
1175 with RO.EnemyModel[emix] do
1176 if (Domain = dSea) and (1 shl (mcLongRange - mcFirstNonCap) and Cap <> 0) then
1177 BombardingNations := BombardingNations or (1 shl Owner);
1178 BombardingNations := BombardingNations and WarNations;
1179
1180 AnalyzeMap;
1181 //for i:=0 to MapSize-1 do DebugMap[i]:=Formation[i];
1182
1183 if (Data.BehaviorFlags and bBarbarina = 0) and
1184 (RO.Tech[ResearchOrder[Data.BehaviorFlags and bGender, 8]] < tsApplicable) then
1185 CheckGender;
1186
1187 if G.Difficulty[me] < MaxDiff then // not on beginner level
1188 begin
1189 if (Data.LastResearchTech = adHorsebackRiding) and (RO.ResearchTech < 0) and
1190 (random(6) = 0) and (HavePort or (ContinentPresence[0] and not
1191 (1 shl me or PresenceUnknown) <> 0)) then
1192 begin
1193 Data.BehaviorFlags := Data.BehaviorFlags or bBarbarina_Hide;
1194 DebugMessage(1, 'Early Barbarina!');
1195 end;
1196 if Data.BehaviorFlags and bBarbarina = 0 then
1197 begin
1198 AllHateMe := False;
1199 for p1 := 0 to nPl - 1 do
1200 if (1 shl p1 and RO.Alive <> 0) and (RO.Treaty[p1] >= trNone) then
1201 if (RO.Treaty[p1] < trPeace) and
1202 ((Data.RejectTurn[suContact, p1] >= 0) or
1203 (Data.RejectTurn[suPeace, p1] >= 0)) then
1204 AllHateMe := True
1205 else
1206 begin
1207 AllHateMe := False;
1208 break;
1209 end;
1210 if AllHateMe then
1211 begin
1212 Data.BehaviorFlags := Data.BehaviorFlags or bBarbarina_Hide;
1213 DebugMessage(1, 'All hate me!');
1214 end;
1215 end;
1216
1217 if Data.BehaviorFlags and bBarbarina = 0 then
1218 if Barbarina_GoHidden then
1219 begin
1220 Data.BehaviorFlags := Data.BehaviorFlags or bBarbarina_Hide;
1221 DebugMessage(1, 'Barbarina!');
1222 end;
1223 if Data.BehaviorFlags and bBarbarina = bBarbarina_Hide then
1224 if Barbarina_Go then
1225 begin
1226 Data.BehaviorFlags := Data.BehaviorFlags or bBarbarina;
1227 DebugMessage(1, 'Barbarina - no mercy!');
1228 end;
1229 end;
1230
1231{$IFDEF PERF}
1232 QueryPerformanceCounter(t1);
1233{$ENDIF}
1234
1235 // better government form available?
1236 if (Data.BehaviorFlags and bBarbarina = 0) and (RO.Turn >= LeaveDespotism) and
1237 (RO.Government <> gAnarchy) then
1238 if IsResearched(adDemocracy) then
1239 begin
1240 if RO.Government <> gDemocracy then
1241 Revolution; //!!!
1242 end
1243 else if IsResearched(adTheRepublic) then
1244 begin
1245 if RO.Government <> gRepublic then
1246 Revolution;
1247 end
1248 else if IsResearched(adMonarchy) then
1249 begin
1250 if RO.Government <> gMonarchy then
1251 Revolution;
1252 end;
1253
1254 CollectModelCatStat;
1255
1256 if Data.BehaviorFlags and bBarbarina = bBarbarina then
1257 begin
1258 MakeColonyShipPlan;
1259 Barbarina_DoTurn;
1260 end
1261 else
1262 begin
1263 {$IFDEF PERF}
1264 QueryPerformanceCounter(t2);
1265{$ENDIF}
1266
1267 {$IFDEF PERF}
1268 QueryPerformanceCounter(t3);
1269{$ENDIF}
1270
1271 AttackAndPatrol;
1272
1273 {$IFDEF PERF}
1274 QueryPerformanceCounter(t4);
1275{$ENDIF}
1276
1277 MoveUnitsHome;
1278
1279 {$IFDEF PERF}
1280 QueryPerformanceCounter(t5);
1281{$ENDIF}
1282 end;
1283
1284 ProcessSettlers;
1285
1286{$IFDEF PERF}
1287 QueryPerformanceCounter(t6);
1288{$ENDIF}
1289
1290 if Data.BehaviorFlags and bBarbarina <> 0 then
1291 Barbarina_SetCityProduction
1292 else
1293 SetCityProduction;
1294
1295{$IFDEF PERF}
1296 QueryPerformanceCounter(t7);
1297{$ENDIF}
1298
1299 // correct tax rate if necessary
1300 if not IsResearched(adWheel) then
1301 ChangeRates(0, 0)
1302 else
1303 begin
1304 if (RO.TaxRate = 0) or (RO.Money < (TotalPopulation[me] - 4) * 2) then
1305 NewTaxRate := RO.TaxRate // don't check decreasing tax
1306 else
1307 NewTaxRate := RO.TaxRate - 10;
1308 while NewTaxRate < 100 do
1309 begin
1310 SumCities(NewTaxRate, TaxSum, ScienceSum);
1311 if RO.Money + TaxSum >= (TotalPopulation[me] - 4) then
1312 break; // enough
1313 Inc(NewTaxRate, 10);
1314 end;
1315 if NewTaxRate <> RO.TaxRate then
1316 begin
1317 // {$IFDEF DEBUG}DebugMessage(3,Format('New tax rate: %d',[NewTaxRate]));{$ENDIF}
1318 ChangeRates(NewTaxRate, 0);
1319 end;
1320 end;
1321
1322 // clean up RequestedTechs
1323 if (Data.LastResearchTech >= 0) and (Data.LastResearchTech <> RO.ResearchTech) then
1324 // research completed
1325 for p1 := 0 to nPl - 1 do
1326 if (p1 <> me) and (1 shl p1 and RO.Alive <> 0) and
1327 (RO.EnemyReport[p1].TurnOfCivilReport + TechReportOutdated > RO.Turn) and
1328 (RO.EnemyReport[p1].Tech[Data.LastResearchTech] < tsSeen) then
1329 begin // latest researched advance might be of interest to this nation
1330 for i := 0 to nRequestedTechs - 1 do
1331 if (Data.RequestedTechs[i] >= 0) and
1332 (Data.RequestedTechs[i] shr 8 and $F = p1) then
1333 Data.RequestedTechs[i] := -1;
1334 end;
1335 if RO.ResearchTech = adMilitary then
1336 Data.LastResearchTech := -1
1337 else
1338 Data.LastResearchTech := RO.ResearchTech;
1339 for i := 0 to nRequestedTechs - 1 do
1340 if (Data.RequestedTechs[i] >= 0) and
1341 (RO.Tech[Data.RequestedTechs[i] and $FF] >= tsSeen) then
1342 Data.RequestedTechs[i] := -1;
1343
1344 // prepare negotiation
1345 AdvanceValuesSet := False;
1346 SetAdvanceValues;
1347
1348{$IFDEF DEBUG}
1349(*for p1:=0 to nPl-1 do
1350 if (p1<>me) and (1 shl p1 and RO.Alive<>0) and (RO.Treaty[p1]>=trPeace)
1351 and (RO.EnemyReport[p1].TurnOfCivilReport>=0) then
1352 TraceAdvanceValues(p1);*)
1353{$ENDIF}
1354
1355{$IFDEF PERF}
1356 DebugMessage(2, Format('t1=%d t2=%d t3=%d t4=%d t5=%d t6=%d t7=%d t8=%d t9=%d (ns)',
1357 [(t1 - t0) * 1000000 div PF, (t2 - t1) * 1000000 div PF, (t3 - t2) *
1358 1000000 div PF, (t4 - t3) * 1000000 div PF, (t5 - t4) * 1000000 div PF,
1359 (t6 - t5) * 1000000 div PF, (t7 - t6) * 1000000 div PF, (t8 - t7) *
1360 1000000 div PF, (t9 - t8) * 1000000 div PF]));
1361{$ENDIF}
1362end;
1363
1364{$IFDEF DEBUG}
1365procedure TAI.TraceAdvanceValues(Nation: integer);
1366var
1367 ad: integer;
1368begin
1369 for ad := 0 to nAdv - 1 do
1370 if (RO.Tech[ad] < tsSeen) and (RO.EnemyReport[Nation].Tech[ad] >= tsApplicable) and
1371 (AdvanceValue[ad] > 0) then
1372 begin
1373 DebugMessage(2, Format('%s (%d): +%x', [Name_Advance[ad],
1374 Advancedness[ad], AdvanceValue[ad]]));
1375 end;
1376end;
1377{$ENDIF}
1378
1379procedure TAI.CheckGender;
1380var
1381 p1, NewGender: integer;
1382begin
1383 NewGender := -1;
1384 for p1 := 0 to nPl - 1 do
1385 if (p1 <> me) and (1 shl p1 and RO.Alive <> 0) and
1386 (RO.Treaty[p1] >= trFriendlyContact) then
1387 if PlayerHash[me] > PlayerHash[p1] then
1388 begin
1389 if NewGender = bMale then
1390 begin
1391 NewGender := -2;
1392 break;
1393 end; // ambiguous, don't change gender
1394 NewGender := bFemale;
1395 end
1396 else
1397 begin
1398 if NewGender = bFemale then
1399 begin
1400 NewGender := -2;
1401 break;
1402 end; // ambiguous, don't change gender
1403 NewGender := bMale;
1404 end;
1405 if (NewGender >= 0) and (NewGender <> Data.BehaviorFlags and bGender) then
1406 begin
1407 Data.BehaviorFlags := Data.BehaviorFlags and not bGender or NewGender;
1408 DebugMessage(1, 'Gender:=' + char(48 + NewGender));
1409 end;
1410end;
1411
1412procedure TAI.SetAdvanceValues;
1413
1414 procedure RateResearchAdv(ad, Time: integer);
1415 var
1416 Value: integer;
1417 begin
1418 if Time = 0 then
1419 Value := TechValue_ForResearch_Next
1420 else
1421 Value := TechValue_ForResearch - Time;
1422 if AdvanceValue[ad] < Value then
1423 AdvanceValue[ad] := Value;
1424 end;
1425
1426 procedure SetPreqValues(ad, Value: integer);
1427 begin
1428 if (RO.Tech[ad] < tsSeen) and (ad <> RO.ResearchTech) then
1429 begin
1430 if AdvanceValue[ad] < Value then
1431 AdvanceValue[ad] := Value;
1432 if ad = adScience then
1433 begin
1434 SetPreqValues(adTheology, Value - 1);
1435 SetPreqValues(adPhilosophy, Value - 1);
1436 end
1437 else if ad = adMassProduction then
1438 // preqs should be researched now
1439 else
1440 begin
1441 if AdvPreq[ad, 0] >= 0 then
1442 SetPreqValues(AdvPreq[ad, 0], Value - 1);
1443 if AdvPreq[ad, 1] >= 0 then
1444 SetPreqValues(AdvPreq[ad, 1], Value - 1);
1445 end;
1446 end;
1447 end;
1448
1449 procedure RateImpPreq(iix, Value: integer);
1450 begin
1451 if (Value > 0) and (Imp[iix].Preq >= 0) then
1452 Inc(AdvanceValue[Imp[iix].Preq], Value);
1453 end;
1454
1455var
1456 emix, cix, adMissing, iad, ad, Count, i, Time, d, CurrentCost,
1457 CurrentStrength, MaxSize, MaxTrade: integer;
1458 PreView, Emergency, Bombarded: boolean;
1459begin
1460 if AdvanceValuesSet then
1461 exit;
1462 AdvanceValuesSet := True;
1463
1464 fillchar(AdvanceValue, sizeof(AdvanceValue), 0);
1465
1466 // rate techs to ensure research progress
1467 Time := 0;
1468 for ad := 0 to nAdv - 1 do
1469 if RO.Tech[ad] = tsSeen then
1470 Inc(Time);
1471 adMissing := -1;
1472 Emergency := True;
1473 for iad := 0 to nResearchOrder - 1 do
1474 begin
1475 ad := ResearchOrder[Data.BehaviorFlags and bGender, iad];
1476 if (ad <> RO.ResearchTech) and (RO.Tech[ad] < tsSeen) then
1477 begin
1478 if adMissing < 0 then
1479 adMissing := ad;
1480 RateResearchAdv(ad, Time); // unseen tech of own gender
1481 if AdvPreq[ad, 2] <> preNone then
1482 begin // 2 of 3 required
1483 Count := 0;
1484 for i := 0 to 2 do
1485 if (AdvPreq[ad, i] = RO.ResearchTech) or
1486 (RO.Tech[AdvPreq[ad, i]] >= tsSeen) then
1487 Inc(Count);
1488 if Count >= 2 then
1489 Emergency := False
1490 else
1491 begin
1492 if ad <> adMassProduction then // don't score third preq for MP
1493 begin
1494 for i := 0 to 2 do
1495 if (AdvPreq[ad, i] <> RO.ResearchTech) and
1496 (RO.Tech[AdvPreq[ad, i]] < tsSeen) then
1497 RateResearchAdv(AdvPreq[ad, i], Time);
1498 end;
1499 Inc(Time, 2 - Count);
1500 end;
1501 end
1502 else
1503 begin
1504 Count := 0;
1505 for i := 0 to 1 do
1506 if (AdvPreq[ad, i] <> preNone) and (AdvPreq[ad, i] <> RO.ResearchTech) and
1507 (RO.Tech[AdvPreq[ad, i]] < tsSeen) then
1508 begin
1509 RateResearchAdv(AdvPreq[ad, i], Time);
1510 Inc(Count);
1511 end;
1512 if Count = 0 then
1513 Emergency := False;
1514 Inc(Time, Count);
1515 end;
1516 Inc(Time, 2);
1517 end;
1518 end;
1519 if Emergency and (adMissing >= 0) then
1520 begin
1521 {$IFDEF DEBUG}
1522 DebugMessage(2, 'Research emergency: Go for' + Name_Advance[adMissing] + ' now!');
1523{$ENDIF}
1524 SetPreqValues(adMissing, TechValue_ForResearch_Urgent);
1525 end;
1526 for iad := 0 to nResearchOrder - 1 do
1527 begin
1528 ad := ResearchOrder[Data.BehaviorFlags and bGender xor 1, iad];
1529 if ad = adScience then
1530 Inc(AdvanceValue[ad], 5 * TechValue_ForResearch_LeaveOut)
1531 else if LeaveOutValue[ad] > 0 then
1532 if AdvanceValue[ad] > 0 then
1533 Inc(AdvanceValue[ad], LeaveOutValue[ad] * TechValue_ForResearch_LeaveOut);
1534 // else AdvanceValue[ad]:=1;
1535 end;
1536
1537 // rate military techs
1538 for d := 0 to nDomains - 1 do
1539 begin
1540 CurrentCost := 0;
1541 CurrentStrength := 0;
1542 for PreView := True downto False do
1543 for i := 0 to nUpgrade - 1 do
1544 with Upgrade[d, i] do
1545 if (Preq >= 0) and not (Preq in FutureTech) then
1546 if ((Ro.ResearchTech = Preq) or (RO.Tech[Preq] >= tsSeen)) = PreView then
1547 if PreView then
1548 begin
1549 if Cost > CurrentCost then
1550 CurrentCost := Cost;
1551 Inc(CurrentStrength, Strength);
1552 end
1553 else
1554 begin // rate
1555 if (i > 0) and (Trans > 0) then
1556 Inc(AdvanceValue[Preq], $400);
1557 if Cost <= CurrentCost then
1558 Inc(AdvanceValue[Preq], (4 - d) * Strength * $400 div
1559 (CurrentStrength + Upgrade[d, 0].Strength))
1560 else
1561 Inc(AdvanceValue[Preq], (4 - d) * Strength * $200 div
1562 (CurrentStrength + Upgrade[d, 0].Strength));
1563 end;
1564 end;
1565 // speed
1566 Inc(AdvanceValue[adSteamEngine], $400);
1567 Inc(AdvanceValue[adNuclearPower], $400);
1568 Inc(AdvanceValue[adRocketry], $400);
1569 // features
1570 Inc(AdvanceValue[adBallistics], $800);
1571 Inc(AdvanceValue[adCommunism], $800);
1572 // weight
1573 Inc(AdvanceValue[adAutomobile], $800);
1574 Inc(AdvanceValue[adSteel], $800);
1575 Inc(AdvanceValue[adAdvancedFlight], $400);
1576
1577 // civil non-improvement
1578 if RO.Turn >= LeaveDespotism then
1579 begin
1580 Inc(AdvanceValue[adDemocracy], $80 * RO.nCity);
1581 Inc(AdvanceValue[adTheRepublic], $800);
1582 end;
1583 Inc(AdvanceValue[adRailroad], $800);
1584 // inc(AdvanceValue[adExplosives],$800); // no, has enough
1585 Inc(AdvanceValue[adBridgeBuilding], $200);
1586 Inc(AdvanceValue[adSpaceFlight], $200);
1587 Inc(AdvanceValue[adSelfContainedEnvironment], $200);
1588 Inc(AdvanceValue[adImpulseDrive], $200);
1589 Inc(AdvanceValue[adTransstellarColonization], $200);
1590
1591 // city improvements
1592 MaxSize := 0;
1593 for cix := 0 to RO.nCity - 1 do
1594 if MyCity[cix].Size > MaxSize then
1595 MaxSize := MyCity[cix].Size;
1596 if RO.Government in [gRepublic, gDemocracy, gLybertarianism] then
1597 MaxTrade := (MaxSize - 1) * 3
1598 else
1599 MaxTrade := (MaxSize - 1) * 2;
1600
1601 RateImpPreq(imCourt, (RO.nCity - 1) * $100);
1602 RateImpPreq(imLibrary, (MaxTrade - 10) * $180);
1603 RateImpPreq(imMarket, (MaxTrade - 10) * $140);
1604 RateImpPreq(imUniversity, (MaxTrade - 10) * $140);
1605 RateImpPreq(imBank, (MaxTrade - 10) * $100);
1606 RateImpPreq(imObservatory, (MaxTrade - 10) * $100);
1607 RateImpPreq(imResLab, (MaxTrade - 14) * $140);
1608 RateImpPreq(imStockEx, (MaxTrade - 10) * $10 * (RO.nCity - 1));
1609 RateImpPreq(imHighways, (MaxSize - 5) * $200);
1610 RateImpPreq(imFactory, (MaxSize - 8) * $200);
1611 RateImpPreq(imMfgPlant, (MaxSize - 8) * $1C0);
1612 RateImpPreq(imRecycling, (MaxSize - 8) * $180);
1613 RateImpPreq(imHarbor, (MaxSize - 7) * $200);
1614 RateImpPreq(imSuperMarket, $300);
1615 if RO.Turn >= 40 then
1616 RateImpPreq(imTemple, $400);
1617 if RO.Government <> gDespotism then
1618 begin
1619 RateImpPreq(imCathedral, $400);
1620 RateImpPreq(imTheater, $400);
1621 end;
1622 if MaxSize >= NeedAqueductSize - 1 then
1623 begin
1624 RateImpPreq(imAqueduct, $600);
1625 RateImpPreq(imGrWall, $300);
1626 end;
1627 if cixStateImp[imPalace] >= 0 then
1628 with MyCity[cixStateImp[imPalace]] do
1629 if (Built[imColosseum] + Built[imObservatory] > 0) and
1630 (Size >= NeedSewerSize - 1) then
1631 RateImpPreq(imSewer, $400);
1632 Bombarded := False;
1633 for emix := 0 to RO.nEnemyModel - 1 do
1634 if 1 shl (mcLongRange - mcFirstNonCap) and RO.EnemyModel[emix].Cap <> 0 then
1635 Bombarded := True;
1636 if Bombarded then
1637 RateImpPreq(imCoastalFort, $400);
1638end;
1639
1640procedure TAI.AnalyzeMap;
1641var
1642 cix, Loc, Loc1, V8, f1, p1: integer;
1643 Adjacent: TVicinity8Loc;
1644begin
1645 inherited;
1646
1647 // collect nation presence information for continents and oceans
1648 fillchar(ContinentPresence, sizeof(ContinentPresence), 0);
1649 fillchar(OceanPresence, sizeof(OceanPresence), 0);
1650 for Loc := 0 to MapSize - 1 do
1651 begin
1652 f1 := Formation[Loc];
1653 case f1 of
1654 0..maxCOD - 1:
1655 begin
1656 p1 := RO.Territory[Loc];
1657 if p1 >= 0 then
1658 if Map[Loc] and fTerrain >= fGrass then
1659 ContinentPresence[f1] := ContinentPresence[f1] or (1 shl p1)
1660 else
1661 OceanPresence[f1] := OceanPresence[f1] or (1 shl p1);
1662 end;
1663 nfUndiscovered:
1664 begin // adjacent formations are not completely discovered
1665 V8_to_Loc(Loc, Adjacent);
1666 for V8 := 0 to 7 do
1667 begin
1668 Loc1 := Adjacent[V8];
1669 if Loc1 >= 0 then
1670 begin
1671 f1 := Formation[Loc1];
1672 if (f1 >= 0) and (f1 < maxCOD) then
1673 if Map[Loc1] and fTerrain >= fGrass then
1674 ContinentPresence[f1] := ContinentPresence[f1] or PresenceUnknown
1675 else
1676 OceanPresence[f1] := OceanPresence[f1] or PresenceUnknown;
1677 end;
1678 end;
1679 end;
1680 nfPeace:
1681 begin // nation present in adjacent formations
1682 V8_to_Loc(Loc, Adjacent);
1683 for V8 := 0 to 7 do
1684 begin
1685 Loc1 := Adjacent[V8];
1686 if Loc1 >= 0 then
1687 begin
1688 f1 := Formation[Loc1];
1689 if (f1 >= 0) and (f1 < maxCOD) then
1690 if Map[Loc1] and fTerrain >= fGrass then
1691 ContinentPresence[f1] :=
1692 ContinentPresence[f1] or (1 shl RO.Territory[Loc])
1693 else
1694 OceanPresence[f1] := OceanPresence[f1] or (1 shl RO.Territory[Loc]);
1695 end;
1696 end;
1697 end;
1698 end;
1699 end;
1700
1701 fillchar(TotalPopulation, sizeof(TotalPopulation), 0);
1702 fillchar(ContinentPopulation, sizeof(ContinentPopulation), 0);
1703 fillchar(DistrictPopulation, 4 * nDistrict, 0);
1704
1705 // count population
1706 for cix := 0 to RO.nEnemyCity - 1 do
1707 with RO.EnemyCity[cix] do
1708 if Loc >= 0 then
1709 begin
1710 Inc(TotalPopulation[Owner], Size);
1711 if (Formation[Loc] >= 0) and (Formation[Loc] < maxCOD) then
1712 Inc(ContinentPopulation[Owner, Formation[Loc]], Size);
1713 end;
1714 for cix := 0 to RO.nCity - 1 do
1715 with RO.City[cix] do
1716 if Loc >= 0 then
1717 begin
1718 Inc(TotalPopulation[me], Size);
1719 assert(District[Loc] >= 0);
1720 if District[Loc] < maxCOD then
1721 Inc(DistrictPopulation[District[Loc]], Size);
1722 end;
1723end;
1724
1725procedure TAI.CollectModelCatStat;
1726var
1727 i, uix, Cat, mix, Quality: integer;
1728begin
1729 // categorize models
1730 for Cat := 0 to nModelCat - 1 do
1731 ModelBestQuality[Cat] := 0;
1732 mixCaravan := -1;
1733 mixSlaves := -1;
1734 mixCruiser := -1;
1735 for mix := 0 to RO.nModel - 1 do
1736 begin
1737 ModelCat[mix] := mctNone;
1738 if mix = 1 then
1739 mixMilitia := mix
1740 else
1741 case MyModel[mix].Kind of
1742 $00..$0F: // common units
1743 if MyModel[mix].Cap[mcNav] > 0 then
1744 mixCruiser := mix // temporary!!!
1745 else
1746 begin
1747 RateMyModel(mix, Cat, Quality);
1748 ModelCat[mix] := Cat;
1749 ModelQuality[mix] := Quality;
1750 if (Cat >= 0) and (Quality > ModelBestQuality[Cat]) then
1751 ModelBestQuality[Cat] := Quality;
1752 end;
1753 mkSpecial_TownGuard: mixTownGuard := mix;
1754 mkSettler: mixSettlers := mix; // engineers always have higher mix
1755 mkCaravan: mixCaravan := mix;
1756 mkSlaves: mixSlaves := mix
1757 end;
1758 end;
1759
1760 // mark obsolete models with quality=0
1761 for mix := 0 to RO.nModel - 1 do
1762 if (MyModel[mix].Kind < $10) and (ModelCat[mix] >= 0) and
1763 (ModelQuality[mix] + MaxExistWorseThanBestModel <
1764 ModelBestQuality[ModelCat[mix]]) then
1765 ModelQuality[mix] := ModelQuality[mix] - $40000000;
1766
1767 OceanWithShip := 0;
1768 if mixCruiser >= 0 then
1769 for uix := 0 to RO.nUn - 1 do
1770 with MyUnit[uix] do
1771 if (Loc >= 0) and (mix = mixCruiser) and (Map[Loc] and fTerrain < fGrass) then
1772 begin
1773 i := Formation[Loc];
1774 if (i >= 0) and (i < maxCOD) then
1775 OceanWithShip := OceanWithShip or (1 shl i);
1776 end;
1777end;
1778
1779procedure TAI.MoveUnitsHome;
1780const
1781 PatrolDestination = lxmax * lymax;
1782 FirstSurplusLoop: array[mctGroundDefender..mctGroundAttacker] of integer = (2, 1);
1783var
1784 Cat, i, mix, cix, uix, Loop, nModelOrder: integer;
1785 Adjacent: TVicinity8Loc;
1786 LocNeed: array[0..lxmax * lymax - 1] of shortint;
1787 Destination: array[0..nUmax - 1] of integer;
1788 DistrictNeed, DistrictNeed0: array[0..maxCOD - 1] of integer;
1789 ModelOrder: array[0..nMmax - 1] of integer;
1790 complete, Fortified: boolean;
1791
1792 function IsBombarded(cix: integer): boolean;
1793 var
1794 Loc1, V8: integer;
1795 Adjacent: TVicinity8Loc;
1796 begin
1797 Result := False;
1798 if BombardingNations <> 0 then
1799 with MyCity[cix] do
1800 begin
1801 V8_to_Loc(Loc, Adjacent);
1802 for V8 := 0 to 7 do
1803 begin
1804 Loc1 := Adjacent[V8];
1805 if (Loc1 >= 0) and (Map[Loc1] and fTerrain < fGrass) and
1806 (Formation[Loc1] >= 0) and (Formation[Loc1] < maxCOD) and
1807 (OceanPresence[Formation[Loc1]] and (BombardingNations or
1808 PresenceUnknown) <> 0) then
1809 begin
1810 Result := True;
1811 exit;
1812 end;
1813 end;
1814 end;
1815 end;
1816
1817 procedure TryUtilize(uix: integer);
1818 var
1819 cix, ProdCost, UtilizeCost: integer;
1820 begin
1821 if (MyUnit[uix].Health = 100) and (Map[MyUnit[uix].Loc] and
1822 (fCity or fOwned) = fCity or fOwned) then
1823 begin
1824 City_FindMyCity(MyUnit[uix].Loc, cix);
1825 with MyCity[cix] do
1826 if Project and cpImp = 0 then
1827 begin
1828 ProdCost := MyModel[Project and cpIndex].Cost;
1829 UtilizeCost := MyModel[MyUnit[uix].mix].Cost;
1830 if Prod < (ProdCost - UtilizeCost * 2 div 3) *
1831 BuildCostMod[G.Difficulty[me]] div 12 then
1832 Unit_Disband(uix);
1833 end;
1834 end;
1835 end;
1836
1837 procedure FindDestination(uix: integer);
1838 var
1839 MoveStyle, V8, Loc1, Time, NextLoc, NextTime, RecoverTurns: integer;
1840 Reached: array[0..lxmax * lymax - 1] of boolean;
1841 begin
1842 fillchar(Reached, MapSize, False);
1843 Pile.Create(MapSize);
1844 with MyUnit[uix] do
1845 begin
1846 Pile.Put(Loc, $800 - Movement);
1847 MoveStyle := GetMyMoveStyle(mix, 100);
1848 end;
1849 while Pile.Get(Loc1, Time) do
1850 begin
1851 if LocNeed[Loc1] > 0 then
1852 begin
1853 LocNeed[Loc1] := 0;
1854 if (District[Loc1] >= 0) and (District[Loc1] < maxCOD) then
1855 begin
1856 assert(DistrictNeed[District[Loc1]] > 0);
1857 Dec(DistrictNeed[District[Loc1]]);
1858 end;
1859 Destination[uix] := Loc1;
1860 break;
1861 end;
1862 Reached[Loc1] := True;
1863 V8_to_Loc(Loc1, Adjacent);
1864 for V8 := 0 to 7 do
1865 begin
1866 NextLoc := Adjacent[V8];
1867 if (NextLoc >= 0) and not Reached[NextLoc] and (RO.Territory[NextLoc] = me) then
1868 case CheckStep(MoveStyle, Time, V8 and 1, NextTime, RecoverTurns,
1869 Map[Loc1], Map[NextLoc], False) of
1870 csOk:
1871 Pile.Put(NextLoc, NextTime);
1872 csForbiddenTile:
1873 Reached[NextLoc] := True; // don't check moving there again
1874 csCheckTerritory:
1875 assert(False);
1876 end;
1877 end;
1878 end;
1879 Pile.Free;
1880 end;
1881
1882begin
1883 if not (RO.Government in [gAnarchy, gDespotism]) then // utilize townguards
1884 for uix := 0 to RO.nUn - 1 do
1885 with MyUnit[uix] do
1886 if (Loc >= 0) and (Master < 0) and (mix = mixTownGuard) then
1887 Unit_Disband(uix);
1888
1889 fillchar(UnitLack, sizeof(UnitLack), 0);
1890 fillchar(Destination, 4 * RO.nUn, $FF);
1891 for i := 0 to maxCOD - 1 do
1892 if uixPatrol[i] >= 0 then
1893 Destination[uixPatrol[i]] := PatrolDestination;
1894 for uix := 0 to RO.nUn - 1 do
1895 if (MyUnit[uix].mix = mixMilitia) or (MyUnit[uix].mix = mixCruiser) then
1896 Destination[uix] := PatrolDestination;
1897
1898 // distribute attackers and defenders
1899 for Cat := mctGroundDefender to mctGroundAttacker do
1900 begin
1901 nModelOrder := 0;
1902 for mix := 0 to Ro.nModel - 1 do
1903 if ModelCat[mix] = Cat then
1904 begin
1905 i := nModelOrder;
1906 while (i > 0) and (ModelQuality[mix] < ModelQuality[ModelOrder[i - 1]]) do
1907 begin
1908 ModelOrder[i] := ModelOrder[i - 1];
1909 Dec(i);
1910 end;
1911 ModelOrder[i] := mix;
1912 Inc(nModelOrder);
1913 end;
1914
1915 Loop := 0;
1916 repeat
1917 if Loop = FirstSurplusLoop[Cat] then
1918 for uix := 0 to RO.nUn - 1 do
1919 with MyUnit[uix] do
1920 if (Loc >= 0) and (Destination[uix] < 0) and (Master < 0) and
1921 (ModelCat[mix] = Cat) and (ModelQuality[mix] < 0) then
1922 TryUtilize(uix);
1923
1924 fillchar(LocNeed, MapSize, 0);
1925 fillchar(DistrictNeed, sizeof(DistrictNeed), 0);
1926
1927 for cix := 0 to RO.nCity - 1 do
1928 with MyCity[cix] do
1929 if Loc >= 0 then
1930 if ((Cat <> mctGroundDefender) or (Loop <> 0) or IsBombarded(cix)) and
1931 ((Loop <> FirstSurplusLoop[Cat]) or
1932 (Built[imBarracks] + Built[imMilAcademy] > 0)) and
1933 ((Loop <> FirstSurplusLoop[Cat] + 1) or
1934 (Built[imBarracks] + Built[imMilAcademy] = 0)) then
1935 begin
1936 LocNeed[Loc] := 1;
1937 if (District[Loc] >= 0) and (District[Loc] < maxCOD) then
1938 begin
1939 Inc(DistrictNeed[District[Loc]]);
1940 if Loop < FirstSurplusLoop[Cat] then
1941 Inc(UnitLack[District[Loc], Cat]);
1942 end;
1943 end;
1944
1945 if Loop = 0 then // protect city building sites
1946 for uix := 0 to RO.nUn - 1 do
1947 with MyUnit[uix] do
1948 if (Loc >= 0) and (Job = jCity) and (RO.Territory[Loc] = me) then
1949 begin
1950 LocNeed[Loc] := 1;
1951 if (District[Loc] >= 0) and (District[Loc] < maxCOD) then
1952 Inc(DistrictNeed[District[Loc]]);
1953 end;
1954
1955 complete := Loop >= FirstSurplusLoop[Cat];
1956 for i := nModelOrder - 1 downto 0 do
1957 begin
1958 for Fortified := True downto False do
1959 for uix := 0 to RO.nUn - 1 do
1960 with MyUnit[uix] do
1961 if (mix = ModelOrder[i]) and (Loc >= 0) and
1962 (Destination[uix] < 0) and (Master < 0) and
1963 ((Flags and unFortified <> 0) = Fortified) and (LocNeed[Loc] > 0) then
1964 begin
1965 LocNeed[Loc] := 0;
1966 if (District[Loc] >= 0) and (District[Loc] < maxCOD) then
1967 Dec(DistrictNeed[District[Loc]]);
1968 Destination[uix] := Loc;
1969 complete := False;
1970 end;
1971
1972 for uix := 0 to RO.nUn - 1 do
1973 with MyUnit[uix] do
1974 if (mix = ModelOrder[i]) and (Loc >= 0) and (Destination[uix] < 0) and
1975 (Master < 0) then
1976 if (District[Loc] >= 0) and (District[Loc] < maxCOD) and
1977 (DistrictNeed[District[Loc]] = 0) then
1978 else
1979 begin // unassigned unit
1980 FindDestination(uix);
1981 if Destination[uix] >= 0 then
1982 complete := False;
1983 end;
1984 end;
1985 Inc(Loop)
1986 until complete;
1987 end;
1988
1989 // distribute obsolete settlers
1990 repeat
1991 fillchar(LocNeed, MapSize, 0);
1992 fillchar(DistrictNeed, sizeof(DistrictNeed), 0);
1993
1994 for cix := 0 to RO.nCity - 1 do
1995 with MyCity[cix] do
1996 if Loc >= 0 then
1997 if (Built[imSewer] > 0) or (Built[imAqueduct] > 0) and
1998 (Size <= NeedSewerSize - 2) or (Size <= NeedAqueductSize - 2) or
1999 (Project = mixSettlers) then
2000 begin
2001 LocNeed[Loc] := 1;
2002 if (District[Loc] >= 0) and (District[Loc] < maxCOD) then
2003 Inc(DistrictNeed[District[Loc]]);
2004 end;
2005 DistrictNeed0 := DistrictNeed;
2006
2007 complete := True;
2008 for uix := 0 to RO.nUn - 1 do
2009 with MyUnit[uix] do
2010 if (Loc >= 0) and (Destination[uix] < 0) and (Master < 0) then
2011 if (MyModel[mix].Kind = mkSettler) and (mix <> mixSettlers) and
2012 (Job = jNone) then
2013 if (District[Loc] >= 0) and (District[Loc] < maxCOD) and
2014 (DistrictNeed[District[Loc]] = 0) then
2015 begin
2016 if DistrictNeed0[District[Loc]] > 0 then
2017 complete := False;
2018 end
2019 else
2020 begin // unassigned unit
2021 FindDestination(uix);
2022 // if (Destination[uix]<0) and (RO.Territory[Loc]=me) then
2023 // complete:=false; // causes hangup when unit can't move due to zoc
2024 end;
2025 until complete;
2026
2027 for uix := 0 to RO.nUn - 1 do
2028 with MyUnit[uix] do
2029 if Loc >= 0 then
2030 if Destination[uix] < 0 then
2031 begin
2032 if (MyModel[mix].Kind <> mkSettler) and (MyModel[mix].Kind <> mkSlaves) and
2033 (Master < 0) and (Map[Loc] and fCity = 0) then
2034 Unit_MoveEx(uix, maNextCity);
2035 end
2036 else if (Destination[uix] <> PatrolDestination) and
2037 (Loc <> Destination[uix]) then
2038 Unit_MoveEx(uix, Destination[uix]);
2039
2040 for uix := 0 to RO.nUn - 1 do
2041 with MyUnit[uix] do
2042 if (Loc >= 0) and (RO.Territory[Loc] = me) and (District[Loc] >= 0) and
2043 (District[Loc] < maxCOD) and (ModelQuality[mix] > 0) then
2044 case ModelCat[mix] of
2045 mctGroundDefender, mctGroundAttacker:
2046 Dec(UnitLack[District[Loc], ModelCat[mix]])
2047 end;
2048end;
2049
2050procedure TAI.CheckAttack(uix: integer);
2051var
2052 AttackScore, BestCount, AttackLoc, TestLoc, NextLoc, TestTime, V8,
2053 TestScore, euix, MyDamage, EnemyDamage, OldLoc, AttackForecast,
2054 MoveResult, AttackResult, MoveStyle, NextTime, RecoverTurns: integer;
2055 Tile: cardinal;
2056 Exhausted: boolean;
2057 Adjacent: TVicinity8Loc;
2058 Reached: array[0..lxmax * lymax - 1] of boolean;
2059
2060begin
2061 with MyUnit[uix] do
2062 begin
2063 MoveStyle := GetMyMoveStyle(mix, Health);
2064 repeat
2065 AttackScore := -999999;
2066 AttackLoc := -1;
2067 fillchar(Reached, MapSize, False);
2068 Pile.Create(MapSize);
2069 Pile.Put(Loc, $800 - Movement);
2070 // start search for something to do at current location
2071 while Pile.Get(TestLoc, TestTime) do
2072 begin
2073 TestScore := 0;
2074 Tile := Map[TestLoc];
2075 Reached[TestLoc] := True;
2076
2077 if ((Tile and fUnit) <> 0) and ((Tile and fOwned) = 0) then
2078 begin // enemy unit
2079 assert(TestTime < $1000);
2080 Unit_FindEnemyDefender(TestLoc, euix);
2081 if RO.Treaty[RO.EnemyUn[euix].Owner] < trPeace then
2082 if Unit_AttackForecast(uix, TestLoc, $800 - TestTime, AttackForecast) then
2083 begin // attack possible, but advantageous?
2084 if AttackForecast = 0 then
2085 begin // enemy unit would be destroyed
2086 MyDamage := Health + DestroyBonus;
2087 EnemyDamage := RO.EnemyUn[euix].Health + DestroyBonus;
2088 end
2089 else if AttackForecast > 0 then
2090 begin // enemy unit would be destroyed
2091 MyDamage := Health - AttackForecast;
2092 EnemyDamage := RO.EnemyUn[euix].Health + DestroyBonus;
2093 end
2094 else // own unit would be destroyed
2095 begin
2096 MyDamage := Health + DestroyBonus;
2097 EnemyDamage := RO.EnemyUn[euix].Health + AttackForecast;
2098 end;
2099 TestScore := Aggressive * 2 *
2100 (EnemyDamage * RO.EnemyModel[RO.EnemyUn[euix].emix].Cost) div
2101 (MyDamage * MyModel[mix].Cost);
2102 if TestScore <= 100 then
2103 TestScore := 0 // own losses exceed enemy losses, no good
2104 else
2105 begin
2106 if TestScore > AttackScore then
2107 BestCount := 0;
2108 if TestScore >= AttackScore then
2109 begin
2110 Inc(BestCount);
2111 if random(BestCount) = 0 then
2112 begin
2113 AttackScore := TestScore;
2114 AttackLoc := TestLoc;
2115 end;
2116 end;
2117 end;
2118 end;
2119 end // enemy unit
2120
2121 else if ((Tile and fCity) <> 0) and ((Tile and fOwned) = 0) then
2122 // enemy city
2123
2124 else
2125 begin // no enemy city or unit here
2126 V8_to_Loc(TestLoc, Adjacent);
2127 for V8 := 0 to 7 do
2128 begin
2129 NextLoc := Adjacent[V8];
2130 if (NextLoc >= 0) and not Reached[NextLoc] and
2131 (Map[NextLoc] and fTerrain <> fUNKNOWN) then
2132 if Map[NextLoc] and (fUnit or fOwned) = fUnit then
2133 Pile.Put(NextLoc, TestTime) // foreign unit!
2134 else
2135 case CheckStep(MoveStyle, TestTime, V8 and 1, NextTime,
2136 RecoverTurns, Map[Loc], Map[NextLoc], True) of
2137 csOk, csCheckTerritory:
2138 if NextTime < $1000 then
2139 Pile.Put(NextLoc, NextTime);
2140 csForbiddenTile:
2141 Reached[NextLoc] := True; // don't check moving there again
2142 end;
2143 end;
2144 end; // no enemy city or unit here
2145 end; // while Pile.Get
2146 Pile.Free;
2147
2148 if AttackLoc >= 0 then
2149 begin
2150 OldLoc := Loc;
2151 MoveResult := Unit_Move(uix, AttackLoc);
2152 Exhausted := (Loc = OldLoc) or
2153 ((MoveResult and (rMoreTurns or rUnitRemoved)) <> 0);
2154 if MoveResult and rLocationReached <> 0 then
2155 if Movement < 100 then
2156 Exhausted := True
2157 else
2158 begin
2159 AttackResult := Unit_Attack(uix, AttackLoc);
2160 Exhausted := ((AttackResult and rExecuted) = 0) or
2161 ((AttackResult and rUnitRemoved) <> 0);
2162 end;
2163 end
2164 else
2165 Exhausted := True;
2166 until Exhausted;
2167 end;
2168end;
2169
2170procedure TAI.Patrol(uix: integer);
2171const
2172 DistanceScore = 4;
2173var
2174 PatrolScore, BestCount, PatrolLoc, TestLoc, NextLoc, TestTime, V8,
2175 TestScore, OldLoc, MoveResult, MoveStyle, NextTime, RecoverTurns: integer;
2176 Tile: cardinal;
2177 Exhausted, CaptureOnly: boolean;
2178 Adjacent: TVicinity8Loc;
2179 AdjacentUnknown: array[0..lxmax * lymax - 1] of shortint;
2180
2181begin
2182 with MyUnit[uix] do
2183 begin
2184 CaptureOnly := ((100 - Health) * Terrain[Map[Loc] and fTerrain].Defense > 60) and
2185 not (Map[Loc] and fTerrain in [fOcean, fShore, fArctic, fDesert]);
2186 MoveStyle := GetMyMoveStyle(mix, Health);
2187 repeat
2188 PatrolScore := -999999;
2189 PatrolLoc := -1;
2190 FillChar(AdjacentUnknown, MapSize, $FF); // -1, indicates tiles not checked yet
2191 Pile.Create(MapSize);
2192 Pile.Put(Loc, $800 - Movement);
2193 while Pile.Get(TestLoc, TestTime) do
2194 begin
2195 if (50 * $1000 - DistanceScore * TestTime <= PatrolScore)
2196 // assume a score of 50 is the best achievable
2197 or CaptureOnly and (TestTime >= $1000) then
2198 break;
2199
2200 TestScore := 0;
2201 Tile := Map[TestLoc];
2202 AdjacentUnknown[TestLoc] := 0;
2203
2204 if ((Tile and fUnit) <> 0) and ((Tile and fOwned) = 0) then
2205 // enemy unit
2206
2207 else if ((Tile and fCity) <> 0) and ((Tile and fOwned) = 0) then
2208 begin
2209 if ((Tile and fObserved) <> 0) and (MyModel[mix].Domain = dGround) and
2210 (MyModel[mix].Attack > 0) and ((RO.Territory[TestLoc] < 0)
2211 // happens only for unobserved cities of extinct tribes, new owner unknown
2212 or (RO.Treaty[RO.Territory[TestLoc]] < trPeace)) then
2213 TestScore := 40; // unfriendly undefended city -- capture!
2214 end
2215
2216 else
2217 begin // no enemy city or unit here
2218 V8_to_Loc(TestLoc, Adjacent);
2219 for V8 := 0 to 7 do
2220 begin
2221 NextLoc := Adjacent[V8];
2222 if (NextLoc >= 0) and (AdjacentUnknown[NextLoc] < 0) then
2223 if Map[NextLoc] and fTerrain = fUNKNOWN then
2224 Inc(AdjacentUnknown[TestLoc])
2225 else if Formation[NextLoc] = Formation[TestLoc] then
2226 case CheckStep(MoveStyle, TestTime, V8 and 1, NextTime,
2227 RecoverTurns, Map[TestLoc], Map[NextLoc], True) of
2228 csOk:
2229 Pile.Put(NextLoc, NextTime);
2230 csForbiddenTile:
2231 AdjacentUnknown[NextLoc] := 0; // don't check moving there again
2232 csCheckTerritory:
2233 if RO.Territory[NextLoc] = RO.Territory[TestLoc] then
2234 Pile.Put(NextLoc, NextTime);
2235 end;
2236 end;
2237 if not CaptureOnly then
2238 if AdjacentUnknown[TestLoc] > 0 then
2239 TestScore := 20 + AdjacentUnknown[TestLoc]
2240 else
2241 TestScore := (RO.Turn - RO.MapObservedLast[TestLoc]) div 16;
2242 end; // no enemy city or unit here
2243
2244 if TestScore > 0 then
2245 begin
2246 TestScore := TestScore * $1000 - DistanceScore * TestTime;
2247 if TestScore > PatrolScore then
2248 BestCount := 0;
2249 if TestScore >= PatrolScore then
2250 begin
2251 Inc(BestCount);
2252 if random(BestCount) = 0 then
2253 begin
2254 PatrolScore := TestScore;
2255 PatrolLoc := TestLoc;
2256 end;
2257 end;
2258 end;
2259 end; // while Pile.Get
2260 Pile.Free;
2261
2262 if PatrolLoc >= 0 then
2263 begin // attack/capture/discover/patrol task found, execute it
2264 OldLoc := Loc;
2265 MoveResult := Unit_Move(uix, PatrolLoc);
2266 Exhausted := (Loc = OldLoc) or
2267 ((MoveResult and (rMoreTurns or rUnitRemoved)) <> 0);
2268 end
2269 else
2270 Exhausted := True;
2271 until Exhausted;
2272 end;
2273end;
2274
2275procedure TAI.AttackAndPatrol;
2276const
2277 nAttackCatOrder = 3;
2278 AttackCatOrder: array[0..nAttackCatOrder - 1] of integer =
2279 (mctGroundAttacker, mctCruiser, mctGroundDefender);
2280var
2281 iCat, uix, uix1: integer;
2282 IsPatrolUnit, Fortified: boolean;
2283begin
2284 for uix := 0 to RO.nUn - 1 do
2285 with MyUnit[uix] do // utilize militia
2286 if (Loc >= 0) and (mix = mixMilitia) and
2287 ((Formation[Loc] < 0) or (Formation[Loc] >= maxCOD) or
2288 (ContinentPresence[Formation[Loc]] and PresenceUnknown = 0)) then
2289 Unit_Disband(uix);
2290
2291 if RO.nEnemyUn > 0 then
2292 for iCat := 0 to nAttackCatOrder - 1 do
2293 for Fortified := False to True do
2294 for uix := RO.nUn - 1 downto 0 do
2295 with MyUnit[uix] do
2296 if (Loc >= 0) and (ModelCat[mix] = AttackCatOrder[iCat]) and
2297 (MyModel[mix].Attack > 0) and ((Flags and unFortified <> 0) =
2298 Fortified) then
2299 CheckAttack(uix);
2300
2301 fillchar(uixPatrol, sizeof(uixPatrol), $FF);
2302 for uix := 0 to RO.nUn - 1 do
2303 with MyUnit[uix], MyModel[mix] do
2304 if (Loc >= 0) and (Domain = dGround) and (Attack > 0) and
2305 (Speed >= 250) and (Map[Loc] and fTerrain >= fGrass) and
2306 (Formation[Loc] >= 0) and (Formation[Loc] < maxCOD) and
2307 ((uixPatrol[Formation[Loc]] < 0) or (MyUnit[uix].ID <
2308 MyUnit[uixPatrol[Formation[Loc]]].ID)) then
2309 uixPatrol[Formation[Loc]] := uix;
2310
2311 for uix := 0 to RO.nUn - 1 do
2312 with MyUnit[uix] do
2313 if Loc >= 0 then
2314 begin
2315 if mix = mixMilitia then
2316 if (RO.nUn < 3) and (RO.nCity = 1) or (Map[Loc] and fCity = 0) then
2317 IsPatrolUnit := True
2318 else
2319 begin // militia
2320 IsPatrolUnit := False;
2321 for uix1 := 0 to RO.nUn - 1 do
2322 if (uix1 <> uix) and (MyUnit[uix1].Loc = Loc) and
2323 (MyUnit[uix1].mix <> mixSettlers) then
2324 IsPatrolUnit := True;
2325 end
2326 else
2327 IsPatrolUnit := (mix = mixCruiser) or (Map[Loc] and fTerrain >= fGrass) and
2328 (Formation[Loc] >= 0) and (Formation[Loc] < maxCOD) and
2329 (uix = uixPatrol[Formation[Loc]]);
2330 if IsPatrolUnit then
2331 Patrol(uix);
2332 end;
2333end;
2334
2335function TAI.HavePort: boolean;
2336var
2337 V8, cix, AdjacentLoc, f: integer;
2338 Adjacent: TVicinity8Loc;
2339begin
2340 Result := False;
2341 for cix := 0 to RO.nCity - 1 do
2342 with MyCity[cix] do
2343 if Loc >= 0 then
2344 begin
2345 V8_to_Loc(Loc, Adjacent);
2346 for V8 := 0 to 7 do
2347 begin
2348 AdjacentLoc := Adjacent[V8];
2349 if (AdjacentLoc >= 0) and ((Map[AdjacentLoc] and fTerrain) < fGrass) then
2350 begin
2351 f := Formation[AdjacentLoc];
2352 if (f >= 0) and (f < maxCOD) and (OceanPresence[f] and
2353 not (1 shl me) <> 0) then
2354 Result := True;
2355 end;
2356 end;
2357 end;
2358end;
2359
2360procedure TAI.SetCityProduction;
2361var
2362 uix, cix, iix, dtr, V8, V21, NewImprovement, AdjacentLoc, MaxSettlers,
2363 maxcount, cixMilAcademy: integer;
2364 TerrType: cardinal;
2365 IsPort, IsNavalBase, NeedCruiser, CheckProd, Destructed, ProduceSettlers,
2366 ProduceMil: boolean;
2367 Adjacent: TVicinity8Loc;
2368 Radius: TVicinity21Loc;
2369 Report: TCityReport;
2370 HomeCount, CityProdRep: array[0..nCmax - 1] of integer;
2371 MilProdCity: array[0..nCmax - 1] of boolean;
2372
2373 procedure TryBuild(Improvement: integer);
2374 begin
2375 if (NewImprovement = imTrGoods) // not already improvement of higher priority found
2376 and (MyCity[cix].Built[Improvement] = 0) // not built yet
2377 and ((Imp[Improvement].Preq = preNone) or
2378 (RO.Tech[Imp[Improvement].Preq] >= tsApplicable)) and
2379 City_Improvable(cix, Improvement) then
2380 NewImprovement := Improvement;
2381 end;
2382
2383 procedure TryDestruct(Improvement: integer);
2384 begin
2385 if Destructed or (MyCity[cix].Built[Improvement] = 0) then
2386 exit;
2387 if City_CurrentImprovementProject(cix) >= 0 then
2388 City_RebuildImprovement(cix, Improvement)
2389 else
2390 City_SellImprovement(cix, Improvement);
2391{ if (CurrentImprovementProject>=0)
2392 and (Imp[CurrentImprovementProject].Kind in [ikCommon,ikNatGlobal,ikNatLocal])
2393 and ((Imp[CurrentImprovementProject].Cost*3-Imp[Improvement].Cost*2)
2394 *BuildCostMod[G.Difficulty[me]]>MyCity[cix].Prod*(12*3)) then}
2395 Destructed := True;
2396 end;
2397
2398 function ChooseBuildModel(Cat: integer): integer;
2399 var
2400 Count, mix: integer;
2401 begin
2402 Count := 0;
2403 for mix := 0 to RO.nModel - 1 do
2404 if (ModelCat[mix] = Cat) and (ModelQuality[mix] >=
2405 ModelBestQuality[Cat] - MaxBuildWorseThanBestModel) then
2406 begin
2407 Inc(Count);
2408 if random(Count) = 0 then
2409 Result := mix;
2410 end;
2411 assert(Count > 0);
2412 end;
2413
2414 procedure NominateMilProdCities;
2415 // find military production cities
2416 var
2417 cix, Total, d, Threshold, NewThreshold, Share, SharePlus, cixWorst: integer;
2418 begin
2419 fillchar(MilProdCity, RO.nCity, 0);
2420 GetCityProdPotential;
2421 for d := 0 to maxCOD - 1 do
2422 begin
2423 Total := 0;
2424 for cix := 0 to RO.nCity - 1 do
2425 with MyCity[cix] do
2426 if (Loc >= 0) and (District[Loc] = d) then
2427 Total := Total + CityResult[cix];
2428 if Total = 0 then
2429 continue; // district does not exist
2430
2431 Share := 0;
2432 cixWorst := -1;
2433 for cix := 0 to RO.nCity - 1 do
2434 with MyCity[cix] do
2435 if (Loc >= 0) and (District[Loc] = d) and
2436 (Built[imBarracks] + Built[imMilAcademy] > 0) then
2437 begin
2438 MilProdCity[cix] := True;
2439 Inc(Share, CityResult[cix]);
2440 if (cixWorst < 0) or (CityResult[cix] < CityResult[cixWorst]) then
2441 cixWorst := cix;
2442 end;
2443
2444 Threshold := $FFFF;
2445 while (Threshold > 0) and (Share < Total * MilProdShare div 100) do
2446 begin
2447 NewThreshold := -1;
2448 for cix := 0 to RO.nCity - 1 do
2449 with MyCity[cix] do
2450 if (Loc >= 0) and (District[Loc] = d) and
2451 (Built[imBarracks] + Built[imMilAcademy] = 0) and
2452 (Built[imObservatory] = 0) and (CityResult[cix] < Threshold) and
2453 (CityResult[cix] >= NewThreshold) then
2454 if CityResult[cix] > NewThreshold then
2455 begin
2456 NewThreshold := CityResult[cix];
2457 SharePlus := CityResult[cix];
2458 end
2459 else
2460 Inc(SharePlus, CityResult[cix]);
2461 Threshold := NewThreshold;
2462 Inc(Share, SharePlus);
2463 end;
2464
2465 for cix := 0 to RO.nCity - 1 do
2466 with MyCity[cix] do
2467 if (Loc >= 0) and (District[Loc] = d) and
2468 (Built[imBarracks] + Built[imMilAcademy] = 0) and
2469 (CityResult[cix] >= Threshold) then
2470 MilProdCity[cix] := True;
2471{ if (cixWorst>=0)
2472 and (Share-CityResult[cixWorst]*2>=Total*MilProdShare div 100) then
2473 MilProdCity[cixWorst]:=false;}
2474 end;
2475
2476 // check best city for military academy
2477 cixMilAcademy := cixStateImp[imMilAcademy];
2478 if cixStateImp[imPalace] >= 0 then
2479 begin
2480 d := District[MyCity[cixStateImp[imPalace]].Loc];
2481 if (d >= 0) and (d < maxCOD) then
2482 begin
2483 cixMilAcademy := -1;
2484 for cix := 0 to RO.nCity - 1 do
2485 with MyCity[cix] do
2486 if (Loc >= 0) and (District[Loc] = d) and
2487 (Built[imObservatory] + Built[imPalace] = 0) and
2488 ((cixMilAcademy < 0) or (CityResult[cix] > CityResult[cixMilAcademy])) then
2489 cixMilAcademy := cix;
2490 end;
2491 if (cixMilAcademy >= 0) and (cixStateImp[imMilAcademy] >= 0) and
2492 (cixMilAcademy <> cixStateImp[imMilAcademy]) and
2493 (MyCity[cixStateImp[imMilAcademy]].Built[imObservatory] = 0) and
2494 (CityResult[cixMilAcademy] <= CityResult[cixStateImp[imMilAcademy]] *
2495 3 div 2) then
2496 cixMilAcademy := cixStateImp[imMilAcademy]; // because not so much better
2497 end;
2498 end;
2499
2500 procedure ChangeHomeCities;
2501 var
2502 uix, NewHome, HomeSupport, NewHomeSupport, SingleSupport: integer;
2503 begin
2504 if RO.Government in [gAnarchy, gFundamentalism] then
2505 exit;
2506 for uix := 0 to RO.nUn - 1 do
2507 with MyUnit[uix] do
2508 if (Loc >= 0) and (Home >= 0) and (Map[Loc] and fCity <> 0) and
2509 (MyCity[Home].Loc <> Loc) and (MyModel[mix].Kind <> mkSettler) then
2510 begin
2511 City_FindMyCity(Loc, NewHome);
2512 case RO.Government of
2513 gDespotism:
2514 begin
2515 HomeSupport := HomeCount[Home] - MyCity[Home].Size;
2516 NewHomeSupport := HomeCount[NewHome] - MyCity[NewHome].Size;
2517 end;
2518 gMonarchy, gCommunism:
2519 begin
2520 HomeSupport := HomeCount[Home] - MyCity[Home].Size div 2;
2521 NewHomeSupport := HomeCount[NewHome] - MyCity[NewHome].Size div 2;
2522 end;
2523 else
2524 begin
2525 HomeSupport := HomeCount[Home];
2526 NewHomeSupport := HomeCount[NewHome];
2527 end;
2528 end;
2529 if HomeSupport > 0 then
2530 begin
2531 if MyModel[mix].Flags and mdDoubleSupport = 0 then
2532 SingleSupport := 1
2533 else
2534 SingleSupport := 2;
2535 HomeSupport := HomeSupport - SingleSupport;
2536 NewHomeSupport := NewHomeSupport + SingleSupport;
2537 if HomeSupport < 0 then
2538 HomeSupport := 0;
2539 if NewHomeSupport < 0 then
2540 NewHomeSupport := 0;
2541 if (NewHomeSupport <= 0) or (CityProdRep[Home] -
2542 HomeSupport <= CityProdRep[NewHome] - NewHomeSupport) then
2543 begin
2544 Dec(HomeCount[Home], SingleSupport);
2545 Inc(HomeCount[NewHome], SingleSupport);
2546 Unit_SetHomeHere(uix);
2547 end;
2548 end;
2549 end;
2550 end;
2551
2552begin
2553 fillchar(HomeCount, 4 * RO.nCity, 0);
2554 for uix := 0 to RO.nUn - 1 do
2555 with MyUnit[uix] do
2556 if (Loc >= 0) and (Home >= 0) then
2557 if MyModel[mix].Flags and mdDoubleSupport = 0 then
2558 Inc(HomeCount[Home])
2559 else
2560 Inc(HomeCount[Home], 2);
2561
2562 NominateMilProdCities;
2563
2564 for cix := 0 to RO.nCity - 1 do
2565 with MyCity[cix] do
2566 if (Loc >= 0) and (Flags and chCaptured = 0) and (District[Loc] >= 0) then
2567 begin
2568 if size < 4 then
2569 City_OptimizeTiles(cix, rwMaxGrowth)
2570 else
2571 City_OptimizeTiles(cix, rwForceProd);
2572
2573 City_GetReport(cix, Report);
2574 CityProdRep[cix] := Report.ProdRep;
2575
2576 Destructed := False;
2577 CheckProd := (RO.Turn = 0) or ((Flags and chProduction) <>
2578 0) // city production complete
2579 or not City_HasProject(cix);
2580 if not CheckProd then
2581 begin // check whether producing double state improvement or wonder
2582 iix := City_CurrentImprovementProject(cix);
2583 if (iix >= 0) and (((Imp[iix].Kind in [ikNatLocal, ikNatGlobal]) and
2584 (RO.NatBuilt[iix] > 0)) or ((Imp[iix].Kind = ikWonder) and
2585 (RO.Wonder[iix].CityID <> WonderNotBuiltYet))) then
2586 CheckProd := True;
2587 end;
2588 if CheckProd then
2589 begin // check production
2590 IsPort := False;
2591 IsNavalBase := False;
2592 NeedCruiser := False;
2593 V8_to_Loc(Loc, Adjacent);
2594 for V8 := 0 to 7 do
2595 begin
2596 AdjacentLoc := Adjacent[V8];
2597 if (AdjacentLoc >= 0) and ((Map[AdjacentLoc] and fTerrain) < fGrass) then
2598 begin
2599 IsPort := True; // shore tile at adjacent location -- city is port!
2600 if (Formation[AdjacentLoc] >= 0) and
2601 (Formation[AdjacentLoc] < maxCOD) and
2602 (OceanPresence[Formation[AdjacentLoc]] and WarNations <> 0) then
2603 begin
2604 IsNavalBase := True;
2605 if (1 shl Formation[AdjacentLoc]) and OceanWithShip = 0 then
2606 NeedCruiser := True;
2607 end;
2608 end;
2609 end;
2610
2611 if RO.Turn = 0 then
2612 begin
2613 NewImprovement := -1;
2614 City_StartUnitProduction(cix, mixMilitia); // militia
2615 end
2616 else
2617 NewImprovement := imTrGoods;
2618
2619 dtr := District[Loc]; // formation of city
2620
2621 if NewImprovement = imTrGoods then
2622 begin
2623 if (Built[imPalace] + Built[imCourt] + Built[imTownHall] = 0) then
2624 TryBuild(imTownHall);
2625 end;
2626
2627 if (NewImprovement = imTrGoods) and (RO.Government = gDespotism) and
2628 (Report.Support = 0) then
2629 begin // produce town guard
2630 NewImprovement := -1;
2631 City_StartUnitProduction(cix, mixTownGuard);
2632 end;
2633
2634 if NewImprovement = imTrGoods then
2635 begin
2636 if RO.Government = gDespotism then
2637 maxcount := Size
2638 else
2639 maxcount := Size div 2;
2640
2641 if IsResearched(adRailroad) and (mixSettlers =
2642 0) // better wait for engineers
2643 or (Built[imColosseum] + Built[imObservatory] > 0) then
2644 MaxSettlers := 1
2645 else
2646 MaxSettlers := (Size + 2) div 6;
2647 ProduceSettlers :=
2648 (HomeCount[cix] < maxcount + Size div 2) and
2649 ((Report.Eaten - Size * 2) div SettlerFood[RO.Government] <
2650 MaxSettlers) and ((dtr < 0) or (dtr >= maxCOD) or
2651 (SettlerSurplus[dtr] <= 0));
2652
2653 ProduceMil := (HomeCount[cix] < maxcount + Size div 2) and
2654 (Built[imBarracks] + Built[imMilAcademy] > 0) and
2655 ((ModelBestQuality[mctGroundDefender] > 0) or
2656 (ModelBestQuality[mctGroundAttacker] > 0)) and
2657 ((dtr < maxCOD) and ((UnitLack[dtr, mctGroundAttacker] > 0) or
2658 (UnitLack[dtr, mctGroundDefender] > 0)) or (HomeCount[cix] < maxcount));
2659
2660 if ProduceMil or not ProduceSettlers and (HomeCount[cix] < maxcount) then
2661 begin
2662 NewImprovement := -1;
2663 if (dtr >= maxCOD) or
2664 (ModelBestQuality[mctGroundDefender] = 0) or
2665 (UnitLack[dtr, mctGroundAttacker] >=
2666 UnitLack[dtr, mctGroundDefender]) then
2667 City_StartUnitProduction(cix, ChooseBuildModel(mctGroundAttacker))
2668 else
2669 City_StartUnitProduction(cix, ChooseBuildModel(mctGroundDefender));
2670 end
2671 else if ProduceSettlers then
2672 begin
2673 NewImprovement := -1;
2674 City_StartUnitProduction(cix, mixSettlers);
2675 end;
2676 end;
2677
2678 if NewImprovement >= 0 then
2679 begin // produce improvement
2680 if (RO.Turn >= 40) and (Report.Happy * 2 <= Size) and
2681 (Built[imColosseum] = 0) then
2682 TryBuild(imTemple);
2683 if cix = cixMilAcademy then
2684 TryBuild(imMilAcademy)
2685 else if ((Built[imPalace] > 0) or MilProdCity[cix] and
2686 (Built[imTemple] > 0)) and (Built[imObservatory] = 0) then
2687 TryBuild(imBarracks);
2688 if Report.Trade - Report.Corruption >= 11 then
2689 TryBuild(imLibrary);
2690 if Report.Trade - Report.Corruption >= 11 then
2691 TryBuild(imMarket);
2692 if (Report.Trade - Report.Corruption >= 11) and (Report.Happy >= 4) then
2693 TryBuild(imUniversity);
2694 if (Built[imPalace] > 0) and (Report.Trade - Report.Corruption >= 11) and
2695 (Report.Happy >= 4) and (RO.NatBuilt[imObservatory] = 0) then
2696 TryBuild(imObservatory); // always build observatory in capital
2697 if (Report.Trade - Report.Corruption >= 15) and (Report.Happy >= 4) then
2698 TryBuild(imResLab);
2699 if (Size >= 9) and (Built[imPalace] + Built[imCourt] > 0) then
2700 TryBuild(imHighways);
2701 if (RO.Government <> gDespotism) and (Report.Happy * 2 <= Size) and
2702 (Built[imCathedral] + Built[imTheater] + Built[imColosseum] = 0) then
2703 begin
2704 TryBuild(imCathedral);
2705 TryBuild(imTheater);
2706 end;
2707 if (RO.Government <> gDespotism) and (Size >= NeedAqueductSize) then
2708 TryBuild(imAqueduct);
2709 if (Built[imColosseum] + Built[imObservatory] > 0) and
2710 (Size >= NeedSewerSize) then
2711 TryBuild(imSewer);
2712 if (RO.NatBuilt[imGrWall] = 0) and
2713 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2714 (RO.nCity >= 6) and (cixStateImp[imPalace] >= 0) and
2715 (Formation[Loc] = Formation[MyCity[cixStateImp[imPalace]].Loc]) and
2716 (Report.ProdRep - Report.Support >= 6) then
2717 TryBuild(imGrWall);
2718 // if Map[Loc] and fGrWall=0 then
2719 // TryBuild(imWalls);
2720 // if IsNavalBase then
2721 // TryBuild(imCoastalFort);
2722 if (RO.NatBuilt[imSpacePort] = 0) and
2723 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2724 (Report.ProdRep - Report.Support >= 10) then
2725 TryBuild(imSpacePort);
2726 if Report.ProdRep >= 8 then
2727 TryBuild(imFactory);
2728 if Report.ProdRep >= 12 then
2729 TryBuild(imMfgPlant);
2730 if IsPort then
2731 if Size > 8 then
2732 TryBuild(imHarbor)
2733 else if (Built[imHarbor] = 0) and (Size > 4) and
2734 ((Size and 1 <> 0) and (Report.Happy * 2 > Size) or
2735 (Built[imColosseum] > 0)) then
2736 begin // check building harbor
2737 V21_to_Loc(Loc, Radius);
2738 for V21 := 1 to 26 do // city is in growth mode - using any 1-food tile?
2739 if Tiles and (1 shl V21) <> 0 then
2740 begin
2741 TerrType := Map[Radius[V21]] and (fTerrain or fSpecial);
2742 if TerrType in [fDesert, fTundra, fSwamp, fForest,
2743 fHills, fMountains] then
2744 begin
2745 TryBuild(imHarbor);
2746 break;
2747 end;
2748 end;
2749 end;
2750 if (Size <= 10) and (Report.FoodRep - Report.Eaten < 2) and
2751 (Report.Happy * 2 >= Size + 2) then
2752 TryBuild(imSuperMarket);
2753
2754 // less important
2755 if (Built[imPalace] > 0) and (RO.NatBuilt[imColosseum] = 0) and
2756 (Size >= 10) then
2757 TryBuild(imColosseum); // always build colosseum in capital
2758 if (Built[imPalace] + Built[imCourt] = 0) and
2759 ((Report.Corruption > 2) or IsResearched(Imp[imHighways].Preq)) then
2760 TryBuild(imCourt); // replace courthouse
2761 if Report.PollRep >= 15 then
2762 TryBuild(imRecycling);
2763 if (Report.Trade - Report.Corruption >= 11) and
2764 (RO.Money < TotalPopulation[me] * 2) then
2765 TryBuild(imBank);
2766 if (RO.NatBuilt[imStockEx] = 0) and
2767 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2768 (Report.ProdRep - Report.Support >= 8) then
2769 TryBuild(imStockEx);
2770
2771 // every improvement checked -- start production now
2772 if NewImprovement <> imTrGoods then
2773 begin
2774 if City_StartImprovement(cix, NewImprovement) < rExecuted then
2775 NewImprovement := imTrGoods;
2776 end;
2777 if (NewImprovement = imTrGoods) and (RO.Turn and $F = 0) then
2778 begin // try colony ship parts
2779 NewImprovement := imShipComp;
2780 while (NewImprovement <= imShipHab) and
2781 ((RO.Tech[Imp[NewImprovement].Preq] < 0) or
2782 (City_StartImprovement(cix, NewImprovement) < rExecuted)) do
2783 Inc(NewImprovement);
2784 if NewImprovement > imShipHab then
2785 NewImprovement := imTrGoods;
2786 end;
2787 end;
2788
2789 if (NewImprovement = imTrGoods) and NeedCruiser and
2790 (mixCruiser >= 0) and (Project and (cpImp or cpIndex) <> mixCruiser) and
2791 (Report.ProdRep - Report.Support >= 6) then
2792 begin
2793 NewImprovement := -1;
2794 City_StartUnitProduction(cix, mixCruiser);
2795 end;
2796
2797 if (NewImprovement = imTrGoods) and City_HasProject(cix) then
2798 City_StopProduction(cix);
2799
2800 // rebuild imps no longer needed
2801 if (RO.TaxRate = 0) and (RO.Money >= TotalPopulation[me] * 4) then
2802 TryDestruct(imBank)
2803 else if Report.Happy * 2 >= Size + 6 then
2804 TryDestruct(imTheater)
2805 else if Report.Happy * 2 >= Size + 4 then
2806 TryDestruct(imTemple);
2807 end;
2808
2809 // rebuild imps no longer needed, no report needed
2810 if (Built[imObservatory] > 0) or (Project and (cpImp or cpIndex) =
2811 cpImp or imObservatory)
2812 {or not MilProdCity[cix]} then
2813 TryDestruct(imBarracks);
2814 if Map[Loc] and fGrWall <> 0 then
2815 TryDestruct(imWalls);
2816 if Built[imColosseum] > 0 then
2817 begin
2818 TryDestruct(imTheater);
2819 TryDestruct(imCathedral);
2820 TryDestruct(imTemple);
2821 end;
2822 end;
2823
2824 ChangeHomeCities;
2825end;
2826
2827function TAI.ChooseGovernment: integer;
2828begin
2829 if Data.BehaviorFlags and bBarbarina <> 0 then
2830 if IsResearched(adTheology) then
2831 Result := gFundamentalism
2832 else
2833 Result := gDespotism
2834 else if IsResearched(adDemocracy) then
2835 Result := gDemocracy //!!!
2836 else if IsResearched(adTheRepublic) then
2837 Result := gRepublic
2838 else if IsResearched(adMonarchy) then
2839 Result := gMonarchy
2840 else
2841 Result := gDespotism;
2842end;
2843
2844//-------------------------------
2845// DIPLOMACY
2846//-------------------------------
2847
2848function TAI.MostWanted(Nation, adGiveAway: integer): integer;
2849var
2850 ad: integer;
2851begin
2852 Result := -1;
2853 if RO.Tech[adGiveAway] >= tsApplicable then
2854 if (adGiveAway = adTheRepublic) and (Data.BehaviorFlags and bGender = bFemale) and
2855 (RO.Tech[adTheology] < tsSeen) then
2856 begin
2857 if RO.EnemyReport[Nation].Tech[adTheology] >= tsApplicable then
2858 Result := adTheology;
2859 end
2860 else
2861 for ad := 0 to nAdv - 5 do // no future techs
2862 if (AdvanceValue[ad] > 0) and (RO.Tech[ad] < tsSeen) and
2863 (ad <> RO.ResearchTech) and (RO.EnemyReport[Nation].Tech[ad] >=
2864 tsApplicable) and ((Advancedness[adGiveAway] <= Advancedness[ad] +
2865 AdvanceValue[ad] shr 8 + Compromise) or (adGiveAway = adScience) and
2866 (Nation = Data.TheologyPartner)) and
2867 ((Result < 0) or ((Advancedness[adGiveAway] + Compromise >=
2868 Advancedness[ad]) // acceptable for opponent
2869 or (ad = adScience)) and (AdvanceValue[ad] > AdvanceValue[Result]) or
2870 (Result <> adScience) and (Advancedness[adGiveAway] +
2871 Compromise < Advancedness[Result]) and (Advancedness[ad] <
2872 Advancedness[Result])) and ((ad <> adTheRepublic) or
2873 (Data.BehaviorFlags and bGender = bFemale) or
2874 (RO.EnemyReport[Nation].Tech[adTheology] >= tsSeen)) then
2875 Result := ad;
2876end;
2877
2878procedure TAI.FindBestTrade(Nation: integer; var adWanted, adGiveAway: integer);
2879var
2880 i, ad, ead, adTestGiveAway: integer;
2881begin
2882 adWanted := -1;
2883 adGiveAway := -1;
2884 for ead := 0 to nAdv - 5 do // no future techs
2885 if (AdvanceValue[ead] >= $100) and (RO.Tech[ead] < tsSeen) and
2886 (ead <> RO.ResearchTech) and (RO.EnemyReport[Nation].Tech[ead] >= tsApplicable) and
2887 ((adWanted < 0) or (AdvanceValue[ead] > AdvanceValue[adWanted])) then
2888 begin
2889 adTestGiveAway := -1;
2890 for i := 0 to nRequestedTechs - 1 do
2891 if (Data.RequestedTechs[i] >= 0) and
2892 (Data.RequestedTechs[i] and $FFFF = Nation shl 8 + ead) then
2893 adTestGiveAway := -2; // already requested before
2894 if adTestGiveAway = -1 then
2895 begin
2896 for ad := 0 to nAdv - 5 do // no future techs
2897 if (RO.Tech[ad] >= tsApplicable) and
2898 (ad <> RO.EnemyReport[Nation].ResearchTech) and
2899 (RO.EnemyReport[Nation].Tech[ad] < tsSeen) and
2900 ((Advancedness[ad] + Compromise >= Advancedness[ead]) or
2901 (ead = adScience)) and (Advancedness[ad] <= Advancedness[ead] +
2902 AdvanceValue[ead] shr 8 + Compromise) and
2903 ((adTestGiveAway < 0) or (Advancedness[ad] <
2904 Advancedness[adTestGiveAway])) then
2905 adTestGiveAway := ad;
2906 if adTestGiveAway >= 0 then
2907 begin
2908 adWanted := ead;
2909 adGiveAway := adTestGiveAway;
2910 end;
2911 end;
2912 end;
2913end;
2914
2915function TAI.WantNegotiation(Nation: integer; NegoTime: TNegoTime): boolean;
2916var
2917 p1, Count, adWanted, adGiveAway: integer;
2918begin
2919 if Data.BehaviorFlags and bBarbarina = bBarbarina then
2920 begin
2921 Result := Barbarina_WantNegotiation(Nation, NegoTime);
2922 exit;
2923 end;
2924
2925 if RO.Treaty[Nation] < trPeace then
2926 begin
2927 if Data.BehaviorFlags and bBarbarina <> 0 then
2928 begin
2929 Result := False;
2930 exit;
2931 end;
2932 Count := 0;
2933 for p1 := 0 to nPl - 1 do
2934 if (p1 <> me) and (1 shl p1 and RO.Alive <> 0) and (RO.Treaty[p1] >= trPeace) then
2935 Inc(Count);
2936 if Count >= 3 then // enough peace made
2937 begin
2938 Result := False;
2939 exit;
2940 end;
2941 end;
2942
2943 NegoCause := Routine;
2944 case NegoTime of
2945 EnemyCalled:
2946 Result := True;
2947 EndOfTurn:
2948 if (Data.RejectTurn[suContact, Nation] >= 0) and
2949 (Data.RejectTurn[suContact, Nation] + WaitAfterReject >= RO.Turn) then
2950 Result := False
2951 else if RO.Treaty[Nation] < trPeace then
2952 Result := (Data.RejectTurn[suPeace, Nation] < 0) or
2953 (Data.RejectTurn[suPeace, Nation] + WaitAfterReject < RO.Turn)
2954 else if RO.Treaty[Nation] = trPeace then
2955 Result := (Data.BehaviorFlags and bBarbarina = 0) and
2956 ((Data.RejectTurn[suFriendly, Nation] < 0) or
2957 (Data.RejectTurn[suFriendly, Nation] + WaitAfterReject < RO.Turn))
2958 else
2959 begin
2960 FindBestTrade(Nation, adWanted, adGiveAway);
2961 Result := adWanted >= 0;
2962 end;
2963 BeginOfTurn:
2964 if (Data.RejectTurn[suContact, Nation] >= 0) and
2965 (Data.RejectTurn[suContact, Nation] + WaitAfterReject >= RO.Turn) then
2966 Result := False
2967 else if (Data.BehaviorFlags and bGender = bMale) and
2968 Barbarina_WantCheckNegotiation(Nation) then
2969 begin
2970 NegoCause := CheckBarbarina;
2971 Result := True;
2972 end
2973 else
2974 Result := False;
2975 end;
2976end;
2977
2978procedure TAI.DoNegotiation;
2979var
2980 i, adWanted, adGiveAway, adToGet, Slot: integer;
2981 BuildFreeOffer: boolean;
2982begin
2983 if MyLastAction = scDipOffer then
2984 if OppoAction = scDipAccept then
2985 begin // evaluate accepted offers
2986 AdvanceValuesSet := False;
2987 if (MyLastOffer.nDeliver = 1) and (MyLastOffer.nCost > 0) and
2988 (MyLastOffer.Price[1] = opTech + adTheology) then
2989 Data.TheologyPartner := Opponent;
2990 end
2991 else
2992 begin // evaluate rejected offers
2993 if MyLastOffer.nDeliver + MyLastOffer.nCost = 1 then
2994 if MyLastOffer.Price[0] = opTreaty + trPeace then
2995 Data.RejectTurn[suPeace, Opponent] := RO.Turn
2996 else if MyLastOffer.Price[0] = opTreaty + trFriendlyContact then
2997 Data.RejectTurn[suFriendly, Opponent] := RO.Turn;
2998 end;
2999 if OppoAction = scDipBreak then
3000 Data.RejectTurn[suContact, Opponent] := RO.Turn
3001 else if OppoAction = scDipCancelTreaty then
3002 begin
3003 case RO.Treaty[Opponent] of
3004 trNone: Data.RejectTurn[suPeace, Opponent] := RO.Turn;
3005 trPeace: Data.RejectTurn[suFriendly, Opponent] := RO.Turn;
3006 end;
3007 end;
3008
3009 if Data.BehaviorFlags and bBarbarina = bBarbarina then
3010 begin
3011 Barbarina_DoNegotiation;
3012 exit;
3013 end;
3014
3015 if NegoCause = CheckBarbarina then
3016 begin
3017 Barbarina_DoCheckNegotiation;
3018 exit;
3019 end;
3020
3021 SetAdvanceValues; // in case no turn played after loading this game
3022
3023 BuildFreeOffer := False;
3024 if (OppoAction = scDipStart) or (OppoAction = scDipAccept) then
3025 BuildFreeOffer := True
3026 else if (OppoAction = scDipOffer) and (OppoOffer.nDeliver + OppoOffer.nCost = 0) then
3027 BuildFreeOffer := True
3028 else if OppoAction = scDipOffer then
3029 begin
3030 if (Data.BehaviorFlags and bBarbarina = 0) and
3031 (OppoOffer.nDeliver + OppoOffer.nCost = 1) and
3032 (OppoOffer.Price[0] and opMask = opTreaty) and
3033 (integer(OppoOffer.Price[0] - opTreaty) > RO.Treaty[Opponent]) and
3034 ((OppoOffer.Price[0] - opTreaty < trAlliance) or
3035 (RO.Tech[adScience] >= tsSeen)) then
3036 MyAction := scDipAccept // accept all treaties
3037 else if (RO.Treaty[Opponent] >= trPeace) and (OppoOffer.nDeliver = 1) and
3038 (OppoOffer.Price[0] and $FFFF0000 = opCivilReport + cardinal(Opponent) shl 16) and
3039 (OppoOffer.nCost = 1) and (OppoOffer.Price[1] and $FFFF0000 =
3040 opCivilReport + cardinal(me) shl 16) then
3041 MyAction := scDipAccept // accept exchange of civil reports
3042 else if (OppoOffer.nDeliver = 1) and (OppoOffer.nCost = 1) and
3043 (OppoOffer.Price[1] and opMask = opTech) then
3044 begin // opponent wants tech
3045 BuildFreeOffer := True;
3046 adGiveAway := OppoOffer.Price[1] - opTech;
3047 if (OppoOffer.Price[0] and opMask = opTech) and
3048 (MyLastAction = scDipOffer) and (MyLastOffer.nDeliver = 1) and
3049 (MyLastOffer.nCost = 1) and (OppoOffer.Price[0] = MyLastOffer.Price[1]) then
3050 begin // opponent makes counter offer, check whether to accept
3051 adToGet := OppoOffer.Price[0] - opTech;
3052 if (adGiveAway = adTheRepublic) and (Data.BehaviorFlags and
3053 bGender = bFemale) and (RO.Tech[adTheology] < tsSeen) then
3054 begin
3055 if adToGet = adTheology then
3056 MyAction := scDipAccept;
3057 end
3058 else if (RO.Tech[adGiveAway] >= tsApplicable) and
3059 (RO.Tech[adToGet] < tsSeen) and (AdvanceValue[adToGet] > 0) and
3060 ((Advancedness[adGiveAway] <= Advancedness[adToGet] +
3061 AdvanceValue[adToGet] shr 8 + Compromise) or (adGiveAway = adScience) and
3062 (Opponent = Data.TheologyPartner)) then
3063 MyAction := scDipAccept;
3064 end
3065 else if (OppoOffer.Price[0] and opMask = opChoose) or
3066 (OppoOffer.Price[0] and opMask = opTech) then
3067 begin // choose price
3068 adWanted := MostWanted(Opponent, OppoOffer.Price[1] - opTech);
3069 if (OppoOffer.Price[0] and opMask = opTech) and
3070 (cardinal(adWanted) = OppoOffer.Price[0] - opTech) then
3071 MyAction := scDipAccept // opponent's offer is already perfect
3072 else if adWanted >= 0 then
3073 begin // make improved counter offer
3074 MyOffer.nDeliver := 1;
3075 MyOffer.nCost := 1;
3076 MyOffer.Price[0] := OppoOffer.Price[1];
3077 MyOffer.Price[1] := opTech + adWanted;
3078 MyAction := scDipOffer;
3079 BuildFreeOffer := False;
3080 end;
3081 end;
3082 if MyAction = scDipAccept then
3083 BuildFreeOffer := False;
3084 end
3085 else
3086 BuildFreeOffer := True;
3087 end;
3088 if (MyAction = scDipAccept) and (OppoAction = scDipOffer) then
3089 begin
3090 AdvanceValuesSet := False;
3091 if (OppoOffer.nDeliver > 0) and (OppoOffer.Price[0] = opTech + adTheology) then
3092 Data.TheologyPartner := Opponent;
3093 end;
3094
3095 if BuildFreeOffer then
3096 begin
3097 if (Data.BehaviorFlags and bBarbarina = 0) and (RO.Treaty[Opponent] < trPeace) and
3098 ((Data.RejectTurn[suPeace, Opponent] < 0) or
3099 (Data.RejectTurn[suPeace, Opponent] + WaitAfterReject < RO.Turn)) then
3100 begin
3101 MyOffer.nDeliver := 1;
3102 MyOffer.nCost := 0;
3103 MyOffer.Price[0] := opTreaty + trPeace;
3104 MyAction := scDipOffer;
3105 end
3106 else if (Data.BehaviorFlags and bBarbarina = 0) and
3107 (RO.Treaty[Opponent] = trPeace) and
3108 ((Data.RejectTurn[suFriendly, Opponent] < 0) or
3109 (Data.RejectTurn[suFriendly, Opponent] + WaitAfterReject < RO.Turn)) then
3110 begin
3111 MyOffer.nDeliver := 1;
3112 MyOffer.nCost := 0;
3113 MyOffer.Price[0] := opTreaty + trFriendlyContact;
3114 MyAction := scDipOffer;
3115 end
3116 else
3117 begin
3118 FindBestTrade(Opponent, adWanted, adGiveAway);
3119 if adWanted >= 0 then
3120 begin
3121 MyOffer.nDeliver := 1;
3122 MyOffer.nCost := 1;
3123 MyOffer.Price[0] := opTech + adGiveAway;
3124 MyOffer.Price[1] := opTech + adWanted;
3125 MyAction := scDipOffer;
3126 for i := 0 to nRequestedTechs - 1 do
3127 if Data.RequestedTechs[i] < 0 then
3128 begin
3129 Slot := i;
3130 break;
3131 end
3132 else if (i = 0) or (Data.RequestedTechs[i] shr 16 <
3133 Data.RequestedTechs[Slot] shr 16) then // find most outdated entry
3134 Slot := i;
3135 Data.RequestedTechs[Slot] := RO.Turn shl 16 + Opponent shl 8 + adWanted;
3136 end;
3137 end;
3138 end;
3139end;
3140
3141procedure SetLeaveOutValue;
3142
3143 procedure Process(ad: integer);
3144 var
3145 i: integer;
3146 begin
3147 if LeaveOutValue[ad] < 0 then
3148 begin
3149 LeaveOutValue[ad] := 0;
3150 for i := 0 to 1 do
3151 if AdvPreq[ad, i] >= 0 then
3152 begin
3153 Process(AdvPreq[ad, i]);
3154 if AdvPreq[ad, i] in LeaveOutTechs then
3155 Inc(LeaveOutValue[ad], LeaveOutValue[AdvPreq[ad, i]] + 1);
3156 end;
3157 end;
3158 end;
3159
3160var
3161 ad: integer;
3162begin
3163 FillChar(LeaveOutValue, SizeOf(LeaveOutValue), $FF);
3164 for ad := 0 to nAdv - 5 do
3165 Process(ad);
3166end;
3167
3168
3169initialization
3170 RWDataSize := sizeof(TPersistentData);
3171 SetLeaveOutValue;
3172
3173end.
Note: See TracBrowser for help on using the repository browser.