source: trunk/AI/StdAI/AI.pas@ 328

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