source: trunk/AI/StdAI/AI.pas

Last change on this file was 549, checked in by chronos, 2 days ago
  • Modified: Optimize code with earlier break from for cycle evaluating boolean result.
  • 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 begin
2354 Result := True;
2355 Exit;
2356 end;
2357 end;
2358 end;
2359 end;
2360end;
2361
2362procedure TAI.SetCityProduction;
2363var
2364 uix, cix, iix, dtr, V8, V21, NewImprovement, AdjacentLoc, MaxSettlers,
2365 maxcount, cixMilAcademy: Integer;
2366 TerrType: Cardinal;
2367 IsPort, IsNavalBase, NeedCruiser, CheckProd, Destructed, ProduceSettlers,
2368 ProduceMil: Boolean;
2369 Adjacent: TVicinity8Loc;
2370 Radius: TVicinity21Loc;
2371 Report: TCityReport;
2372 HomeCount, CityProdRep: array[0..nCmax - 1] of Integer;
2373 MilProdCity: array[0..nCmax - 1] of Boolean;
2374
2375 procedure TryBuild(Improvement: Integer);
2376 begin
2377 if (NewImprovement = imTrGoods) // not already improvement of higher priority found
2378 and (MyCity[cix].Built[Improvement] = 0) // not built yet
2379 and ((Imp[Improvement].Preq = preNone) or
2380 (RO.Tech[Imp[Improvement].Preq] >= tsApplicable)) and
2381 City_Improvable(cix, Improvement) then
2382 NewImprovement := Improvement;
2383 end;
2384
2385 procedure TryDestruct(Improvement: Integer);
2386 begin
2387 if Destructed or (MyCity[cix].Built[Improvement] = 0) then
2388 Exit;
2389 if City_CurrentImprovementProject(cix) >= 0 then
2390 City_RebuildImprovement(cix, Improvement)
2391 else
2392 City_SellImprovement(cix, Improvement);
2393{ if (CurrentImprovementProject>=0)
2394 and (Imp[CurrentImprovementProject].Kind in [ikCommon,ikNatGlobal,ikNatLocal])
2395 and ((Imp[CurrentImprovementProject].Cost*3-Imp[Improvement].Cost*2)
2396 *BuildCostMod[G.Difficulty[Me]]>MyCity[cix].Prod*(12*3)) then}
2397 Destructed := True;
2398 end;
2399
2400 function ChooseBuildModel(Cat: Integer): Integer;
2401 var
2402 Count, mix: Integer;
2403 begin
2404 Count := 0;
2405 for mix := 0 to RO.nModel - 1 do
2406 if (ModelCat[mix] = Cat) and (ModelQuality[mix] >=
2407 ModelBestQuality[Cat] - MaxBuildWorseThanBestModel) then
2408 begin
2409 Inc(Count);
2410 if Random(Count) = 0 then
2411 Result := mix;
2412 end;
2413 Assert(Count > 0);
2414 end;
2415
2416 procedure NominateMilProdCities;
2417 // find military production cities
2418 var
2419 cix, Total, D, Threshold, NewThreshold, Share, SharePlus, cixWorst: Integer;
2420 begin
2421 FillChar(MilProdCity, RO.nCity, 0);
2422 GetCityProdPotential;
2423 for D := 0 to maxCOD - 1 do
2424 begin
2425 Total := 0;
2426 for cix := 0 to RO.nCity - 1 do
2427 with MyCity[cix] do
2428 if (Loc >= 0) and (District[Loc] = D) then
2429 Total := Total + CityResult[cix];
2430 if Total = 0 then
2431 Continue; // district does not exist
2432
2433 Share := 0;
2434 cixWorst := -1;
2435 for cix := 0 to RO.nCity - 1 do
2436 with MyCity[cix] do
2437 if (Loc >= 0) and (District[Loc] = D) and
2438 (Built[imBarracks] + Built[imMilAcademy] > 0) then
2439 begin
2440 MilProdCity[cix] := True;
2441 Inc(Share, CityResult[cix]);
2442 if (cixWorst < 0) or (CityResult[cix] < CityResult[cixWorst]) then
2443 cixWorst := cix;
2444 end;
2445
2446 Threshold := $FFFF;
2447 while (Threshold > 0) and (Share < Total * MilProdShare div 100) do
2448 begin
2449 NewThreshold := -1;
2450 for cix := 0 to RO.nCity - 1 do
2451 with MyCity[cix] do
2452 if (Loc >= 0) and (District[Loc] = D) and
2453 (Built[imBarracks] + Built[imMilAcademy] = 0) and
2454 (Built[imObservatory] = 0) and (CityResult[cix] < Threshold) and
2455 (CityResult[cix] >= NewThreshold) then
2456 if CityResult[cix] > NewThreshold then
2457 begin
2458 NewThreshold := CityResult[cix];
2459 SharePlus := CityResult[cix];
2460 end
2461 else
2462 Inc(SharePlus, CityResult[cix]);
2463 Threshold := NewThreshold;
2464 Inc(Share, SharePlus);
2465 end;
2466
2467 for cix := 0 to RO.nCity - 1 do
2468 with MyCity[cix] do
2469 if (Loc >= 0) and (District[Loc] = D) and
2470 (Built[imBarracks] + Built[imMilAcademy] = 0) and
2471 (CityResult[cix] >= Threshold) then
2472 MilProdCity[cix] := True;
2473{ if (cixWorst>=0)
2474 and (Share-CityResult[cixWorst]*2>=Total*MilProdShare div 100) then
2475 MilProdCity[cixWorst]:=False;}
2476 end;
2477
2478 // check best city for military academy
2479 cixMilAcademy := cixStateImp[imMilAcademy];
2480 if cixStateImp[imPalace] >= 0 then
2481 begin
2482 D := District[MyCity[cixStateImp[imPalace]].Loc];
2483 if (D >= 0) and (D < maxCOD) then
2484 begin
2485 cixMilAcademy := -1;
2486 for cix := 0 to RO.nCity - 1 do
2487 with MyCity[cix] do
2488 if (Loc >= 0) and (District[Loc] = D) and
2489 (Built[imObservatory] + Built[imPalace] = 0) and
2490 ((cixMilAcademy < 0) or (CityResult[cix] > CityResult[cixMilAcademy])) then
2491 cixMilAcademy := cix;
2492 end;
2493 if (cixMilAcademy >= 0) and (cixStateImp[imMilAcademy] >= 0) and
2494 (cixMilAcademy <> cixStateImp[imMilAcademy]) and
2495 (MyCity[cixStateImp[imMilAcademy]].Built[imObservatory] = 0) and
2496 (CityResult[cixMilAcademy] <= CityResult[cixStateImp[imMilAcademy]] *
2497 3 div 2) then
2498 cixMilAcademy := cixStateImp[imMilAcademy]; // because not so much better
2499 end;
2500 end;
2501
2502 procedure ChangeHomeCities;
2503 var
2504 uix, NewHome, HomeSupport, NewHomeSupport, SingleSupport: Integer;
2505 begin
2506 if RO.Government in [gAnarchy, gFundamentalism] then
2507 Exit;
2508 for uix := 0 to RO.nUn - 1 do
2509 with MyUnit[uix] do
2510 if (Loc >= 0) and (Home >= 0) and (Map[Loc] and fCity <> 0) and
2511 (MyCity[Home].Loc <> Loc) and (MyModel[mix].Kind <> mkSettler) then
2512 begin
2513 City_FindMyCity(Loc, NewHome);
2514 case RO.Government of
2515 gDespotism:
2516 begin
2517 HomeSupport := HomeCount[Home] - MyCity[Home].Size;
2518 NewHomeSupport := HomeCount[NewHome] - MyCity[NewHome].Size;
2519 end;
2520 gMonarchy, gCommunism:
2521 begin
2522 HomeSupport := HomeCount[Home] - MyCity[Home].Size div 2;
2523 NewHomeSupport := HomeCount[NewHome] - MyCity[NewHome].Size div 2;
2524 end;
2525 else
2526 begin
2527 HomeSupport := HomeCount[Home];
2528 NewHomeSupport := HomeCount[NewHome];
2529 end;
2530 end;
2531 if HomeSupport > 0 then
2532 begin
2533 if MyModel[mix].Flags and mdDoubleSupport = 0 then
2534 SingleSupport := 1
2535 else
2536 SingleSupport := 2;
2537 HomeSupport := HomeSupport - SingleSupport;
2538 NewHomeSupport := NewHomeSupport + SingleSupport;
2539 if HomeSupport < 0 then
2540 HomeSupport := 0;
2541 if NewHomeSupport < 0 then
2542 NewHomeSupport := 0;
2543 if (NewHomeSupport <= 0) or (CityProdRep[Home] -
2544 HomeSupport <= CityProdRep[NewHome] - NewHomeSupport) then
2545 begin
2546 Dec(HomeCount[Home], SingleSupport);
2547 Inc(HomeCount[NewHome], SingleSupport);
2548 Unit_SetHomeHere(uix);
2549 end;
2550 end;
2551 end;
2552 end;
2553
2554begin
2555 FillChar(HomeCount, 4 * RO.nCity, 0);
2556 for uix := 0 to RO.nUn - 1 do
2557 with MyUnit[uix] do
2558 if (Loc >= 0) and (Home >= 0) then
2559 if MyModel[mix].Flags and mdDoubleSupport = 0 then
2560 Inc(HomeCount[Home])
2561 else
2562 Inc(HomeCount[Home], 2);
2563
2564 NominateMilProdCities;
2565
2566 for cix := 0 to RO.nCity - 1 do
2567 with MyCity[cix] do
2568 if (Loc >= 0) and (Flags and chCaptured = 0) and (District[Loc] >= 0) then
2569 begin
2570 if Size < 4 then
2571 City_OptimizeTiles(cix, rwMaxGrowth)
2572 else
2573 City_OptimizeTiles(cix, rwForceProd);
2574
2575 City_GetReport(cix, Report);
2576 CityProdRep[cix] := Report.ProdRep;
2577
2578 Destructed := False;
2579 CheckProd := (RO.Turn = 0) or ((Flags and chProduction) <>
2580 0) // city production complete
2581 or not City_HasProject(cix);
2582 if not CheckProd then
2583 begin // check whether producing double state improvement or wonder
2584 iix := City_CurrentImprovementProject(cix);
2585 if (iix >= 0) and (((Imp[iix].Kind in [ikNatLocal, ikNatGlobal]) and
2586 (RO.NatBuilt[iix] > 0)) or ((Imp[iix].Kind = ikWonder) and
2587 (RO.Wonder[iix].CityID <> WonderNotBuiltYet))) then
2588 CheckProd := True;
2589 end;
2590 if CheckProd then
2591 begin // check production
2592 IsPort := False;
2593 IsNavalBase := False;
2594 NeedCruiser := False;
2595 V8_to_Loc(Loc, Adjacent);
2596 for V8 := 0 to 7 do
2597 begin
2598 AdjacentLoc := Adjacent[V8];
2599 if (AdjacentLoc >= 0) and ((Map[AdjacentLoc] and fTerrain) < fGrass) then
2600 begin
2601 IsPort := True; // shore tile at adjacent location -- city is port!
2602 if (Formation[AdjacentLoc] >= 0) and
2603 (Formation[AdjacentLoc] < maxCOD) and
2604 (OceanPresence[Formation[AdjacentLoc]] and WarNations <> 0) then
2605 begin
2606 IsNavalBase := True;
2607 if (1 shl Formation[AdjacentLoc]) and OceanWithShip = 0 then
2608 NeedCruiser := True;
2609 end;
2610 end;
2611 end;
2612
2613 if RO.Turn = 0 then
2614 begin
2615 NewImprovement := -1;
2616 City_StartUnitProduction(cix, mixMilitia); // militia
2617 end
2618 else
2619 NewImprovement := imTrGoods;
2620
2621 dtr := District[Loc]; // formation of city
2622
2623 if NewImprovement = imTrGoods then
2624 begin
2625 if (Built[imPalace] + Built[imCourt] + Built[imTownHall] = 0) then
2626 TryBuild(imTownHall);
2627 end;
2628
2629 if (NewImprovement = imTrGoods) and (RO.Government = gDespotism) and
2630 (Report.Support = 0) then
2631 begin // produce town guard
2632 NewImprovement := -1;
2633 City_StartUnitProduction(cix, mixTownGuard);
2634 end;
2635
2636 if NewImprovement = imTrGoods then
2637 begin
2638 if RO.Government = gDespotism then
2639 maxcount := Size
2640 else
2641 maxcount := Size div 2;
2642
2643 if IsResearched(adRailroad) and (mixSettlers =
2644 0) // better wait for engineers
2645 or (Built[imColosseum] + Built[imObservatory] > 0) then
2646 MaxSettlers := 1
2647 else
2648 MaxSettlers := (Size + 2) div 6;
2649 ProduceSettlers :=
2650 (HomeCount[cix] < maxcount + Size div 2) and
2651 ((Report.Eaten - Size * 2) div SettlerFood[RO.Government] <
2652 MaxSettlers) and ((dtr < 0) or (dtr >= maxCOD) or
2653 (SettlerSurplus[dtr] <= 0));
2654
2655 ProduceMil := (HomeCount[cix] < maxcount + Size div 2) and
2656 (Built[imBarracks] + Built[imMilAcademy] > 0) and
2657 ((ModelBestQuality[mctGroundDefender] > 0) or
2658 (ModelBestQuality[mctGroundAttacker] > 0)) and
2659 ((dtr < maxCOD) and ((UnitLack[dtr, mctGroundAttacker] > 0) or
2660 (UnitLack[dtr, mctGroundDefender] > 0)) or (HomeCount[cix] < maxcount));
2661
2662 if ProduceMil or not ProduceSettlers and (HomeCount[cix] < maxcount) then
2663 begin
2664 NewImprovement := -1;
2665 if (dtr >= maxCOD) or
2666 (ModelBestQuality[mctGroundDefender] = 0) or
2667 (UnitLack[dtr, mctGroundAttacker] >=
2668 UnitLack[dtr, mctGroundDefender]) then
2669 City_StartUnitProduction(cix, ChooseBuildModel(mctGroundAttacker))
2670 else
2671 City_StartUnitProduction(cix, ChooseBuildModel(mctGroundDefender));
2672 end
2673 else if ProduceSettlers then
2674 begin
2675 NewImprovement := -1;
2676 City_StartUnitProduction(cix, mixSettlers);
2677 end;
2678 end;
2679
2680 if NewImprovement >= 0 then
2681 begin // produce improvement
2682 if (RO.Turn >= 40) and (Report.Happy * 2 <= Size) and
2683 (Built[imColosseum] = 0) then
2684 TryBuild(imTemple);
2685 if cix = cixMilAcademy then
2686 TryBuild(imMilAcademy)
2687 else if ((Built[imPalace] > 0) or MilProdCity[cix] and
2688 (Built[imTemple] > 0)) and (Built[imObservatory] = 0) then
2689 TryBuild(imBarracks);
2690 if Report.Trade - Report.Corruption >= 11 then
2691 TryBuild(imLibrary);
2692 if Report.Trade - Report.Corruption >= 11 then
2693 TryBuild(imMarket);
2694 if (Report.Trade - Report.Corruption >= 11) and (Report.Happy >= 4) then
2695 TryBuild(imUniversity);
2696 if (Built[imPalace] > 0) and (Report.Trade - Report.Corruption >= 11) and
2697 (Report.Happy >= 4) and (RO.NatBuilt[imObservatory] = 0) then
2698 TryBuild(imObservatory); // always build observatory in capital
2699 if (Report.Trade - Report.Corruption >= 15) and (Report.Happy >= 4) then
2700 TryBuild(imResLab);
2701 if (Size >= 9) and (Built[imPalace] + Built[imCourt] > 0) then
2702 TryBuild(imHighways);
2703 if (RO.Government <> gDespotism) and (Report.Happy * 2 <= Size) and
2704 (Built[imCathedral] + Built[imTheater] + Built[imColosseum] = 0) then
2705 begin
2706 TryBuild(imCathedral);
2707 TryBuild(imTheater);
2708 end;
2709 if (RO.Government <> gDespotism) and (Size >= NeedAqueductSize) then
2710 TryBuild(imAqueduct);
2711 if (Built[imColosseum] + Built[imObservatory] > 0) and
2712 (Size >= NeedSewerSize) then
2713 TryBuild(imSewer);
2714 if (RO.NatBuilt[imGrWall] = 0) and
2715 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2716 (RO.nCity >= 6) and (cixStateImp[imPalace] >= 0) and
2717 (Formation[Loc] = Formation[MyCity[cixStateImp[imPalace]].Loc]) and
2718 (Report.ProdRep - Report.Support >= 6) then
2719 TryBuild(imGrWall);
2720 // if Map[Loc] and fGrWall=0 then
2721 // TryBuild(imWalls);
2722 // if IsNavalBase then
2723 // TryBuild(imCoastalFort);
2724 if (RO.NatBuilt[imSpacePort] = 0) and
2725 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2726 (Report.ProdRep - Report.Support >= 10) then
2727 TryBuild(imSpacePort);
2728 if Report.ProdRep >= 8 then
2729 TryBuild(imFactory);
2730 if Report.ProdRep >= 12 then
2731 TryBuild(imMfgPlant);
2732 if IsPort then
2733 if Size > 8 then
2734 TryBuild(imHarbor)
2735 else if (Built[imHarbor] = 0) and (Size > 4) and
2736 ((Size and 1 <> 0) and (Report.Happy * 2 > Size) or
2737 (Built[imColosseum] > 0)) then
2738 begin // check building harbor
2739 V21_to_Loc(Loc, Radius);
2740 for V21 := 1 to 26 do // city is in growth mode - using any 1-food tile?
2741 if Tiles and (1 shl V21) <> 0 then
2742 begin
2743 TerrType := Map[Radius[V21]] and (fTerrain or fSpecial);
2744 if TerrType in [fDesert, fTundra, fSwamp, fForest,
2745 fHills, fMountains] then
2746 begin
2747 TryBuild(imHarbor);
2748 Break;
2749 end;
2750 end;
2751 end;
2752 if (Size <= 10) and (Report.FoodRep - Report.Eaten < 2) and
2753 (Report.Happy * 2 >= Size + 2) then
2754 TryBuild(imSuperMarket);
2755
2756 // less important
2757 if (Built[imPalace] > 0) and (RO.NatBuilt[imColosseum] = 0) and
2758 (Size >= 10) then
2759 TryBuild(imColosseum); // always build colosseum in capital
2760 if (Built[imPalace] + Built[imCourt] = 0) and
2761 ((Report.Corruption > 2) or IsResearched(Imp[imHighways].Preq)) then
2762 TryBuild(imCourt); // replace courthouse
2763 if Report.PollRep >= 15 then
2764 TryBuild(imRecycling);
2765 if (Report.Trade - Report.Corruption >= 11) and
2766 (RO.Money < TotalPopulation[Me] * 2) then
2767 TryBuild(imBank);
2768 if (RO.NatBuilt[imStockEx] = 0) and
2769 (Built[imObservatory] + Built[imMilAcademy] = 0) and
2770 (Report.ProdRep - Report.Support >= 8) then
2771 TryBuild(imStockEx);
2772
2773 // every improvement checked -- start production now
2774 if NewImprovement <> imTrGoods then
2775 begin
2776 if City_StartImprovement(cix, NewImprovement) < rExecuted then
2777 NewImprovement := imTrGoods;
2778 end;
2779 if (NewImprovement = imTrGoods) and (RO.Turn and $F = 0) then
2780 begin // try colony ship parts
2781 NewImprovement := imShipComp;
2782 while (NewImprovement <= imShipHab) and
2783 ((RO.Tech[Imp[NewImprovement].Preq] < 0) or
2784 (City_StartImprovement(cix, NewImprovement) < rExecuted)) do
2785 Inc(NewImprovement);
2786 if NewImprovement > imShipHab then
2787 NewImprovement := imTrGoods;
2788 end;
2789 end;
2790
2791 if (NewImprovement = imTrGoods) and NeedCruiser and
2792 (mixCruiser >= 0) and (Project and (cpImp or cpIndex) <> mixCruiser) and
2793 (Report.ProdRep - Report.Support >= 6) then
2794 begin
2795 NewImprovement := -1;
2796 City_StartUnitProduction(cix, mixCruiser);
2797 end;
2798
2799 if (NewImprovement = imTrGoods) and City_HasProject(cix) then
2800 City_StopProduction(cix);
2801
2802 // rebuild imps no longer needed
2803 if (RO.TaxRate = 0) and (RO.Money >= TotalPopulation[Me] * 4) then
2804 TryDestruct(imBank)
2805 else if Report.Happy * 2 >= Size + 6 then
2806 TryDestruct(imTheater)
2807 else if Report.Happy * 2 >= Size + 4 then
2808 TryDestruct(imTemple);
2809 end;
2810
2811 // rebuild imps no longer needed, no report needed
2812 if (Built[imObservatory] > 0) or (Project and (cpImp or cpIndex) =
2813 cpImp or imObservatory)
2814 {or not MilProdCity[cix]} then
2815 TryDestruct(imBarracks);
2816 if Map[Loc] and fGrWall <> 0 then
2817 TryDestruct(imWalls);
2818 if Built[imColosseum] > 0 then
2819 begin
2820 TryDestruct(imTheater);
2821 TryDestruct(imCathedral);
2822 TryDestruct(imTemple);
2823 end;
2824 end;
2825
2826 ChangeHomeCities;
2827end;
2828
2829function TAI.ChooseGovernment: Integer;
2830begin
2831 if Data.BehaviorFlags and bBarbarina <> 0 then
2832 if IsResearched(adTheology) then
2833 Result := gFundamentalism
2834 else
2835 Result := gDespotism
2836 else if IsResearched(adDemocracy) then
2837 Result := gDemocracy //!!!
2838 else if IsResearched(adTheRepublic) then
2839 Result := gRepublic
2840 else if IsResearched(adMonarchy) then
2841 Result := gMonarchy
2842 else
2843 Result := gDespotism;
2844end;
2845
2846//-------------------------------
2847// DIPLOMACY
2848//-------------------------------
2849
2850function TAI.MostWanted(Nation, adGiveAway: Integer): Integer;
2851var
2852 ad: Integer;
2853begin
2854 Result := -1;
2855 if RO.Tech[adGiveAway] >= tsApplicable then
2856 if (adGiveAway = adTheRepublic) and (Data.BehaviorFlags and bGender = bFemale) and
2857 (RO.Tech[adTheology] < tsSeen) then
2858 begin
2859 if RO.EnemyReport[Nation].Tech[adTheology] >= tsApplicable then
2860 Result := adTheology;
2861 end
2862 else
2863 for ad := 0 to nAdv - 5 do // no future techs
2864 if (AdvanceValue[ad] > 0) and (RO.Tech[ad] < tsSeen) and
2865 (ad <> RO.ResearchTech) and (RO.EnemyReport[Nation].Tech[ad] >=
2866 tsApplicable) and ((Advancedness[adGiveAway] <= Advancedness[ad] +
2867 AdvanceValue[ad] shr 8 + Compromise) or (adGiveAway = adScience) and
2868 (Nation = Data.TheologyPartner)) and
2869 ((Result < 0) or ((Advancedness[adGiveAway] + Compromise >=
2870 Advancedness[ad]) // acceptable for opponent
2871 or (ad = adScience)) and (AdvanceValue[ad] > AdvanceValue[Result]) or
2872 (Result <> adScience) and (Advancedness[adGiveAway] +
2873 Compromise < Advancedness[Result]) and (Advancedness[ad] <
2874 Advancedness[Result])) and ((ad <> adTheRepublic) or
2875 (Data.BehaviorFlags and bGender = bFemale) or
2876 (RO.EnemyReport[Nation].Tech[adTheology] >= tsSeen)) then
2877 Result := ad;
2878end;
2879
2880procedure TAI.FindBestTrade(Nation: Integer; var adWanted, adGiveAway: Integer);
2881var
2882 I, ad, ead, adTestGiveAway: Integer;
2883begin
2884 adWanted := -1;
2885 adGiveAway := -1;
2886 for ead := 0 to nAdv - 5 do // no future techs
2887 if (AdvanceValue[ead] >= $100) and (RO.Tech[ead] < tsSeen) and
2888 (ead <> RO.ResearchTech) and (RO.EnemyReport[Nation].Tech[ead] >= tsApplicable) and
2889 ((adWanted < 0) or (AdvanceValue[ead] > AdvanceValue[adWanted])) then
2890 begin
2891 adTestGiveAway := -1;
2892 for I := 0 to nRequestedTechs - 1 do
2893 if (Data.RequestedTechs[I] >= 0) and
2894 (Data.RequestedTechs[I] and $FFFF = Nation shl 8 + ead) then
2895 adTestGiveAway := -2; // already requested before
2896 if adTestGiveAway = -1 then
2897 begin
2898 for ad := 0 to nAdv - 5 do // no future techs
2899 if (RO.Tech[ad] >= tsApplicable) and
2900 (ad <> RO.EnemyReport[Nation].ResearchTech) and
2901 (RO.EnemyReport[Nation].Tech[ad] < tsSeen) and
2902 ((Advancedness[ad] + Compromise >= Advancedness[ead]) or
2903 (ead = adScience)) and (Advancedness[ad] <= Advancedness[ead] +
2904 AdvanceValue[ead] shr 8 + Compromise) and
2905 ((adTestGiveAway < 0) or (Advancedness[ad] <
2906 Advancedness[adTestGiveAway])) then
2907 adTestGiveAway := ad;
2908 if adTestGiveAway >= 0 then
2909 begin
2910 adWanted := ead;
2911 adGiveAway := adTestGiveAway;
2912 end;
2913 end;
2914 end;
2915end;
2916
2917function TAI.WantNegotiation(Nation: Integer; NegoTime: TNegoTime): Boolean;
2918var
2919 p1, Count, adWanted, adGiveAway: Integer;
2920begin
2921 if Data.BehaviorFlags and bBarbarina = bBarbarina then
2922 begin
2923 Result := Barbarina_WantNegotiation(Nation, NegoTime);
2924 Exit;
2925 end;
2926
2927 if RO.Treaty[Nation] < trPeace then
2928 begin
2929 if Data.BehaviorFlags and bBarbarina <> 0 then
2930 begin
2931 Result := False;
2932 Exit;
2933 end;
2934 Count := 0;
2935 for p1 := 0 to nPl - 1 do
2936 if (p1 <> Me) and (1 shl p1 and RO.Alive <> 0) and (RO.Treaty[p1] >= trPeace) then
2937 Inc(Count);
2938 if Count >= 3 then // enough peace made
2939 begin
2940 Result := False;
2941 Exit;
2942 end;
2943 end;
2944
2945 NegoCause := Routine;
2946 case NegoTime of
2947 EnemyCalled:
2948 Result := True;
2949 EndOfTurn:
2950 if (Data.RejectTurn[suContact, Nation] >= 0) and
2951 (Data.RejectTurn[suContact, Nation] + WaitAfterReject >= RO.Turn) then
2952 Result := False
2953 else if RO.Treaty[Nation] < trPeace then
2954 Result := (Data.RejectTurn[suPeace, Nation] < 0) or
2955 (Data.RejectTurn[suPeace, Nation] + WaitAfterReject < RO.Turn)
2956 else if RO.Treaty[Nation] = trPeace then
2957 Result := (Data.BehaviorFlags and bBarbarina = 0) and
2958 ((Data.RejectTurn[suFriendly, Nation] < 0) or
2959 (Data.RejectTurn[suFriendly, Nation] + WaitAfterReject < RO.Turn))
2960 else
2961 begin
2962 FindBestTrade(Nation, adWanted, adGiveAway);
2963 Result := adWanted >= 0;
2964 end;
2965 BeginOfTurn:
2966 if (Data.RejectTurn[suContact, Nation] >= 0) and
2967 (Data.RejectTurn[suContact, Nation] + WaitAfterReject >= RO.Turn) then
2968 Result := False
2969 else if (Data.BehaviorFlags and bGender = bMale) and
2970 Barbarina_WantCheckNegotiation(Nation) then
2971 begin
2972 NegoCause := CheckBarbarina;
2973 Result := True;
2974 end
2975 else
2976 Result := False;
2977 end;
2978end;
2979
2980procedure TAI.DoNegotiation;
2981var
2982 I, adWanted, adGiveAway, adToGet, Slot: Integer;
2983 BuildFreeOffer: Boolean;
2984begin
2985 if MyLastAction = scDipOffer then
2986 if OppoAction = scDipAccept then
2987 begin // evaluate accepted offers
2988 AdvanceValuesSet := False;
2989 if (MyLastOffer.nDeliver = 1) and (MyLastOffer.nCost > 0) and
2990 (MyLastOffer.Price[1] = opTech + adTheology) then
2991 Data.TheologyPartner := Opponent;
2992 end
2993 else
2994 begin // evaluate rejected offers
2995 if MyLastOffer.nDeliver + MyLastOffer.nCost = 1 then
2996 if MyLastOffer.Price[0] = opTreaty + trPeace then
2997 Data.RejectTurn[suPeace, Opponent] := RO.Turn
2998 else if MyLastOffer.Price[0] = opTreaty + trFriendlyContact then
2999 Data.RejectTurn[suFriendly, Opponent] := RO.Turn;
3000 end;
3001 if OppoAction = scDipBreak then
3002 Data.RejectTurn[suContact, Opponent] := RO.Turn
3003 else if OppoAction = scDipCancelTreaty then
3004 begin
3005 case RO.Treaty[Opponent] of
3006 trNone: Data.RejectTurn[suPeace, Opponent] := RO.Turn;
3007 trPeace: Data.RejectTurn[suFriendly, Opponent] := RO.Turn;
3008 end;
3009 end;
3010
3011 if Data.BehaviorFlags and bBarbarina = bBarbarina then
3012 begin
3013 Barbarina_DoNegotiation;
3014 Exit;
3015 end;
3016
3017 if NegoCause = CheckBarbarina then
3018 begin
3019 Barbarina_DoCheckNegotiation;
3020 Exit;
3021 end;
3022
3023 SetAdvanceValues; // in case no turn played after loading this game
3024
3025 BuildFreeOffer := False;
3026 if (OppoAction = scDipStart) or (OppoAction = scDipAccept) then
3027 BuildFreeOffer := True
3028 else if (OppoAction = scDipOffer) and (OppoOffer.nDeliver + OppoOffer.nCost = 0) then
3029 BuildFreeOffer := True
3030 else if OppoAction = scDipOffer then
3031 begin
3032 if (Data.BehaviorFlags and bBarbarina = 0) and
3033 (OppoOffer.nDeliver + OppoOffer.nCost = 1) and
3034 (OppoOffer.Price[0] and opMask = opTreaty) and
3035 (Integer(OppoOffer.Price[0] - opTreaty) > RO.Treaty[Opponent]) and
3036 ((OppoOffer.Price[0] - opTreaty < trAlliance) or
3037 (RO.Tech[adScience] >= tsSeen)) then
3038 MyAction := scDipAccept // accept all treaties
3039 else if (RO.Treaty[Opponent] >= trPeace) and (OppoOffer.nDeliver = 1) and
3040 (OppoOffer.Price[0] and $FFFF0000 = opCivilReport + Cardinal(Opponent) shl 16) and
3041 (OppoOffer.nCost = 1) and (OppoOffer.Price[1] and $FFFF0000 =
3042 opCivilReport + Cardinal(Me) shl 16) then
3043 MyAction := scDipAccept // accept exchange of civil reports
3044 else if (OppoOffer.nDeliver = 1) and (OppoOffer.nCost = 1) and
3045 (OppoOffer.Price[1] and opMask = opTech) then
3046 begin // opponent wants tech
3047 BuildFreeOffer := True;
3048 adGiveAway := OppoOffer.Price[1] - opTech;
3049 if (OppoOffer.Price[0] and opMask = opTech) and
3050 (MyLastAction = scDipOffer) and (MyLastOffer.nDeliver = 1) and
3051 (MyLastOffer.nCost = 1) and (OppoOffer.Price[0] = MyLastOffer.Price[1]) then
3052 begin // opponent makes counter offer, check whether to accept
3053 adToGet := OppoOffer.Price[0] - opTech;
3054 if (adGiveAway = adTheRepublic) and (Data.BehaviorFlags and
3055 bGender = bFemale) and (RO.Tech[adTheology] < tsSeen) then
3056 begin
3057 if adToGet = adTheology then
3058 MyAction := scDipAccept;
3059 end
3060 else if (RO.Tech[adGiveAway] >= tsApplicable) and
3061 (RO.Tech[adToGet] < tsSeen) and (AdvanceValue[adToGet] > 0) and
3062 ((Advancedness[adGiveAway] <= Advancedness[adToGet] +
3063 AdvanceValue[adToGet] shr 8 + Compromise) or (adGiveAway = adScience) and
3064 (Opponent = Data.TheologyPartner)) then
3065 MyAction := scDipAccept;
3066 end
3067 else if (OppoOffer.Price[0] and opMask = opChoose) or
3068 (OppoOffer.Price[0] and opMask = opTech) then
3069 begin // choose price
3070 adWanted := MostWanted(Opponent, OppoOffer.Price[1] - opTech);
3071 if (OppoOffer.Price[0] and opMask = opTech) and
3072 (Cardinal(adWanted) = OppoOffer.Price[0] - opTech) then
3073 MyAction := scDipAccept // opponent's offer is already perfect
3074 else if adWanted >= 0 then
3075 begin // make improved counter offer
3076 MyOffer.nDeliver := 1;
3077 MyOffer.nCost := 1;
3078 MyOffer.Price[0] := OppoOffer.Price[1];
3079 MyOffer.Price[1] := opTech + adWanted;
3080 MyAction := scDipOffer;
3081 BuildFreeOffer := False;
3082 end;
3083 end;
3084 if MyAction = scDipAccept then
3085 BuildFreeOffer := False;
3086 end
3087 else
3088 BuildFreeOffer := True;
3089 end;
3090 if (MyAction = scDipAccept) and (OppoAction = scDipOffer) then
3091 begin
3092 AdvanceValuesSet := False;
3093 if (OppoOffer.nDeliver > 0) and (OppoOffer.Price[0] = opTech + adTheology) then
3094 Data.TheologyPartner := Opponent;
3095 end;
3096
3097 if BuildFreeOffer then
3098 begin
3099 if (Data.BehaviorFlags and bBarbarina = 0) and (RO.Treaty[Opponent] < trPeace) and
3100 ((Data.RejectTurn[suPeace, Opponent] < 0) or
3101 (Data.RejectTurn[suPeace, Opponent] + WaitAfterReject < RO.Turn)) then
3102 begin
3103 MyOffer.nDeliver := 1;
3104 MyOffer.nCost := 0;
3105 MyOffer.Price[0] := opTreaty + trPeace;
3106 MyAction := scDipOffer;
3107 end
3108 else if (Data.BehaviorFlags and bBarbarina = 0) and
3109 (RO.Treaty[Opponent] = trPeace) and
3110 ((Data.RejectTurn[suFriendly, Opponent] < 0) or
3111 (Data.RejectTurn[suFriendly, Opponent] + WaitAfterReject < RO.Turn)) then
3112 begin
3113 MyOffer.nDeliver := 1;
3114 MyOffer.nCost := 0;
3115 MyOffer.Price[0] := opTreaty + trFriendlyContact;
3116 MyAction := scDipOffer;
3117 end
3118 else
3119 begin
3120 FindBestTrade(Opponent, adWanted, adGiveAway);
3121 if adWanted >= 0 then
3122 begin
3123 MyOffer.nDeliver := 1;
3124 MyOffer.nCost := 1;
3125 MyOffer.Price[0] := opTech + adGiveAway;
3126 MyOffer.Price[1] := opTech + adWanted;
3127 MyAction := scDipOffer;
3128 for I := 0 to nRequestedTechs - 1 do
3129 if Data.RequestedTechs[I] < 0 then
3130 begin
3131 Slot := I;
3132 Break;
3133 end
3134 else if (I = 0) or (Data.RequestedTechs[I] shr 16 <
3135 Data.RequestedTechs[Slot] shr 16) then // find most outdated entry
3136 Slot := I;
3137 Data.RequestedTechs[Slot] := RO.Turn shl 16 + Opponent shl 8 + adWanted;
3138 end;
3139 end;
3140 end;
3141end;
3142
3143procedure SetLeaveOutValue;
3144
3145 procedure Process(ad: Integer);
3146 var
3147 I: Integer;
3148 begin
3149 if LeaveOutValue[ad] < 0 then
3150 begin
3151 LeaveOutValue[ad] := 0;
3152 for I := 0 to 1 do
3153 if AdvPreq[ad, I] >= 0 then
3154 begin
3155 Process(AdvPreq[ad, I]);
3156 if AdvPreq[ad, I] in LeaveOutTechs then
3157 Inc(LeaveOutValue[ad], LeaveOutValue[AdvPreq[ad, I]] + 1);
3158 end;
3159 end;
3160 end;
3161
3162var
3163 ad: Integer;
3164begin
3165 FillChar(LeaveOutValue, SizeOf(LeaveOutValue), $FF);
3166 for ad := 0 to nAdv - 5 do
3167 Process(ad);
3168end;
3169
3170
3171initialization
3172 RWDataSize := SizeOf(TPersistentData);
3173 SetLeaveOutValue;
3174
3175end.
Note: See TracBrowser for help on using the repository browser.