2587 lines
112 KiB
C++
2587 lines
112 KiB
C++
// This file is part of c-evo-evo.
|
|
//
|
|
// This software is governed by the CeCILL license under French law and
|
|
// abiding by the rules of distribution of free software. You can use,
|
|
// modify and/or redistribute the software under the terms of the CeCILL
|
|
// license as circulated by CEA, CNRS and INRIA at the following URL
|
|
// "http://www.cecill.info".
|
|
//
|
|
// As a counterpart to the access to the source code and rights to copy,
|
|
// modify and redistribute granted by the license, users are provided only
|
|
// with a limited warranty and the software's author, the holder of the
|
|
// economic rights, and the successive licensors have only limited
|
|
// liability.
|
|
//
|
|
// In this respect, the user's attention is drawn to the risks associated
|
|
// with loading, using, modifying and/or developing or reproducing the
|
|
// software by the user in light of its specific status of free software,
|
|
// that may mean that it is complicated to manipulate, and that also
|
|
// therefore means that it is reserved for developers and experienced
|
|
// professionals having in-depth computer knowledge. Users are therefore
|
|
// encouraged to load and test the software's suitability as regards their
|
|
// requirements in conditions enabling the security of their systems and/or
|
|
// data to be ensured and, more generally, to use and operate it in the
|
|
// same conditions as regards security.
|
|
//
|
|
// The fact that you are presently reading this means that you have had
|
|
// knowledge of the CeCILL license and that you accept its terms.
|
|
|
|
#include "Cevo/AI.h"
|
|
#include "Cevo/Geometry.h"
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cmath>
|
|
#include <cstdlib>
|
|
#include <functional>
|
|
|
|
namespace Cevo {
|
|
|
|
namespace {
|
|
|
|
int randomInt(int n) // Pascal's RTL Random(n); not ABI/determinism-relevant
|
|
{
|
|
return n > 0 ? std::rand() % n : 0;
|
|
}
|
|
|
|
double randomFloat() // Pascal's RTL Random (no args): float in [0, 1)
|
|
{
|
|
return static_cast<double>(std::rand()) / (static_cast<double>(RAND_MAX) + 1.0);
|
|
}
|
|
|
|
constexpr int WaitAfterReject = 20; // don't try to contact for this many turns after a reject
|
|
constexpr int MinCityFood = 3;
|
|
constexpr int LeaveDespotism = 80; // stay in despotism until this turn
|
|
constexpr int TechReportOutdated = 30;
|
|
constexpr int MilProdShare = 50; // min. share of total production to specialize in military
|
|
|
|
constexpr int nResearchOrder = 46;
|
|
constexpr int ResearchOrder[2][nResearchOrder] = {
|
|
{ adWheel, adWarriorCode, adHorsebackRiding, adCeremonialBurial, adPolytheism, adMonarchy, adMysticism, adPoetry,
|
|
adAstronomy, adMonotheism, adTheology, adChivalry, adPottery, adMedicine, adGunpowder, adChemistry,
|
|
adExplosives, adUniversity, adTactics, adSeafaring, adNavigation, adRefining, adCombustionEngine,
|
|
adAutomobile, adPhysics, adMagnetism, adElectricity, adRefrigeration, adRadioCommunication, adTheoryOfGravity,
|
|
adAtomicTheory, adElectronics, adMassProduction, adPlastics, adFlight, adEnvironmentalism, adSanitation, adMin,
|
|
adComputers, adRecycling, adSyntheticFood, adSelfContainedEnvironment, adNuclearFission, adNuclearPower,
|
|
adTheLaser, adIntelligenArms },
|
|
{ adWheel, adWarriorCode, adHorsebackRiding, adAlphabet, adMapMaking, adBronzeWorking, adWriting, adCodeOfLaws,
|
|
adCurrency, adTrade, adLiterature, adTheRepublic, adMathematics, adPhilosophy, adScience, adMasonry,
|
|
adConstruction, adEngineering, adInvention, adIronWorking, adBridgeBuilding, adSteamEngine, adRailroad,
|
|
adSteel, adBanking, adIndustrialization, adConscription, adDemocracy, adEconomics, adTheCorporation,
|
|
adMassProduction, adRobotics, adCommunism, adMetallurgy, adBallistics, adMobileWarfare, adAmphibiousWarfare,
|
|
adMin, adComputers, adRocketry, adAdvancedRocketry, adAdvancedFlight, adSpaceFlight, adComposites,
|
|
adIntelligence, adCombinedArms },
|
|
};
|
|
|
|
bool isLeaveOutTech(int ad)
|
|
{
|
|
static constexpr int kLeaveOutTechs[] = { adPolytheism, adMysticism, adInvention, adEconomics, adPottery,
|
|
adMedicine, adEnvironmentalism, adRefining, adTrade, adLiterature,
|
|
adMathematics, adPhilosophy, adChemistry, adConscription,
|
|
adCombustionEngine, adPhysics, adTheoryOfGravity, adAtomicTheory,
|
|
adSyntheticFood, adNuclearFission };
|
|
for (int v : kLeaveOutTechs)
|
|
if (v == ad)
|
|
return true;
|
|
return false;
|
|
}
|
|
|
|
bool isAiFutureTech(int ad) // AI.pas's own local `FutureTech` set (distinct from Protocol's IsFutureTech)
|
|
{
|
|
return ad == futResearchTechnology || ad == futProductionTechnology || ad == futArmorTechnology ||
|
|
ad == futMissileTechnology;
|
|
}
|
|
|
|
constexpr int TechValue_ForResearch_LeaveOut = 0x700;
|
|
constexpr int TechValue_ForResearch_Urgent = 0x600;
|
|
constexpr int TechValue_ForResearch_Next = 0x400;
|
|
constexpr int TechValue_ForResearch = 0xFF;
|
|
constexpr int ForceNeeded_NoLeaveOut = 20; // advancedness behind state-of-art
|
|
constexpr int ForceNeeded_LeaveOut = 30; // advancedness behind state-of-art
|
|
constexpr int Compromise = 6;
|
|
|
|
constexpr int bGender = 0x0001;
|
|
constexpr int bMale = 0x0000;
|
|
constexpr int bFemale = 0x0001;
|
|
constexpr int bBarbarina = 0x0006;
|
|
constexpr int bBarbarina_Hide = 0x0002;
|
|
|
|
constexpr int BetterQuality[nAIModelCat] = { 50, 50, 80, 80 };
|
|
constexpr int MaxBuildWorseThanBestModel = 20;
|
|
constexpr int MaxExistWorseThanBestModel = 50;
|
|
|
|
constexpr int PresenceUnknown = 0x10000;
|
|
|
|
constexpr int PlayerHash[nPl] = { 7, 6, 0, 2, 10, 8, 12, 14, 4, 1, 3, 5, 9, 11, 13 };
|
|
|
|
constexpr int Aggressive = 40; // 0 = never attacks, 100 = attacks even with heavy losses
|
|
constexpr int DestroyBonus = 30; // percent of building cost
|
|
|
|
void leaveOutValueProcess(int ad, std::array<int, nAdv> &value)
|
|
{
|
|
if (value[ad] < 0) {
|
|
value[ad] = 0;
|
|
for (int i = 0; i < 2; ++i) {
|
|
if (AdvPreq[ad][i] >= 0) {
|
|
leaveOutValueProcess(AdvPreq[ad][i], value);
|
|
if (isLeaveOutTech(AdvPreq[ad][i]))
|
|
value[ad] += value[AdvPreq[ad][i]] + 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
std::array<int, nAdv> computeLeaveOutValue()
|
|
{
|
|
std::array<int, nAdv> value;
|
|
value.fill(-1);
|
|
for (int ad = 0; ad <= nAdv - 5; ++ad)
|
|
leaveOutValueProcess(ad, value);
|
|
return value;
|
|
}
|
|
|
|
const std::array<int, nAdv> LeaveOutValue = computeLeaveOutValue();
|
|
|
|
} // namespace
|
|
|
|
AI::AI(int nation) : Barbarina(nation) {}
|
|
|
|
void AI::bind(TPlayerContext *playerContext)
|
|
{
|
|
Barbarina::bind(playerContext);
|
|
data = static_cast<TPersistentData *>(ro->Data);
|
|
}
|
|
|
|
void AI::setDataDefaults()
|
|
{
|
|
data->LastResearchTech = -1;
|
|
data->BehaviorFlags = PlayerHash[me] > 7 ? bFemale : bMale;
|
|
debugMessage(1, std::string("Gender:=") + char(48 + (data->BehaviorFlags & bGender)));
|
|
data->TheologyPartner = -1;
|
|
for (auto &row : data->RejectTurn)
|
|
for (auto &v : row)
|
|
v = -1;
|
|
for (auto &v : data->RequestedTechs)
|
|
v = -1;
|
|
}
|
|
|
|
bool AI::onNegoRejected_CancelTreaty()
|
|
{
|
|
data->RejectTurn[static_cast<int>(Suggestion::Contact)][opponent] = static_cast<std::int16_t>(ro->Turn);
|
|
return (data->BehaviorFlags & bBarbarina) != 0;
|
|
}
|
|
|
|
//-------------------------------
|
|
// RESEARCH
|
|
//-------------------------------
|
|
|
|
void AI::rateModel(const TModelInfo &mi, int &category, int &quality) const
|
|
{
|
|
if (mi.Kind >= mkScout) {
|
|
category = mctNone;
|
|
return;
|
|
}
|
|
switch (mi.Domain) {
|
|
case dGround:
|
|
if (mi.Speed >= 250) {
|
|
category = mctGroundAttacker;
|
|
if (mi.Attack == 0) {
|
|
quality = 0;
|
|
} else {
|
|
quality = static_cast<int>(100 * (std::log(static_cast<double>(mi.Attack)) +
|
|
std::log(static_cast<double>(mi.Defense)) +
|
|
std::log(mi.Speed / 150.0) * 1.7 - std::log(static_cast<double>(mi.Cost))));
|
|
if (mi.Cap & (1u << (mcFanatic - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.5));
|
|
if (mi.Cap & (1u << (mcLongRange - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.5));
|
|
}
|
|
} else {
|
|
category = mctGroundDefender;
|
|
quality = static_cast<int>(100 * (std::log(static_cast<double>(mi.Defense)) - std::log(static_cast<double>(mi.Cost)) * 0.6));
|
|
if (mi.Cap & (1u << (mcFanatic - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.5));
|
|
}
|
|
break;
|
|
case dSea:
|
|
if (mi.Attack == 0) {
|
|
category = mctTransport;
|
|
if (mi.TTrans == 0) {
|
|
quality = 0;
|
|
} else {
|
|
int effectiveTransport = mi.TTrans;
|
|
if (effectiveTransport > 4)
|
|
effectiveTransport = 4; // rarely used more
|
|
quality = 100 + static_cast<int>(100 * (std::log(static_cast<double>(effectiveTransport)) +
|
|
std::log(mi.Speed / 150.0) + std::log(static_cast<double>(mi.Defense)) -
|
|
std::log(static_cast<double>(mi.Cost))));
|
|
if (mi.Cap & (1u << (mcNav - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.5));
|
|
if (mi.Cap & (1u << (mcAirDef - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.3));
|
|
}
|
|
} else {
|
|
category = mctCruiser;
|
|
if (mi.Attack == 0) {
|
|
quality = 0;
|
|
} else {
|
|
quality = static_cast<int>(100 * (std::log(static_cast<double>(mi.Attack)) +
|
|
std::log(static_cast<double>(mi.Defense)) * 0.6 - std::log(static_cast<double>(mi.Cost))));
|
|
if (mi.Cap & (1u << (mcNav - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.4));
|
|
if (mi.Cap & (1u << (mcAirDef - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.3));
|
|
if (mi.Cap & (1u << (mcLongRange - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(2.0));
|
|
if (mi.Cap & (1u << (mcRadar - mcFirstNonCap)))
|
|
quality += static_cast<int>(100 * std::log(1.5));
|
|
}
|
|
}
|
|
break;
|
|
case dAir:
|
|
category = mctNone;
|
|
quality = 0;
|
|
break;
|
|
default:
|
|
category = mctNone;
|
|
quality = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
void AI::rateMyModel(int mix, int &category, int &quality) const
|
|
{
|
|
TModelInfo mi;
|
|
MakeModelInfo(me, mix, myModel[mix], mi);
|
|
rateModel(mi, category, quality);
|
|
}
|
|
|
|
bool AI::isBetterModel(const TModelInfo &mi) const
|
|
{
|
|
int cat, quality;
|
|
rateModel(mi, cat, quality);
|
|
for (int mix = 0; mix < ro->nModel; ++mix) {
|
|
if (mi.Domain == myModel[mix].Domain) {
|
|
int cat1, quality1;
|
|
rateMyModel(mix, cat1, quality1);
|
|
if (cat == cat1 && quality < quality1 + BetterQuality[cat])
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
int AI::chooseResearchAdvance()
|
|
{
|
|
if (data->BehaviorFlags & bBarbarina) {
|
|
const int result = barbarina_ChooseResearchAdvance();
|
|
if (result >= 0)
|
|
return result;
|
|
}
|
|
|
|
setAdvanceValues();
|
|
|
|
// always complete traded techs first
|
|
int result = -1;
|
|
for (int ad = 0; ad < nAdv; ++ad)
|
|
if (ro->Tech[ad] == tsSeen && (result < 0 || advanceValue[ad] > advanceValue[result]))
|
|
result = ad;
|
|
if (result >= 0)
|
|
return result;
|
|
|
|
std::array<bool, nAdv> entry{};
|
|
std::function<bool(int)> markEntry = [&](int ad) -> bool {
|
|
if (ro->Tech[ad] >= tsApplicable)
|
|
return false; // nothing more to research here
|
|
if (ro->Tech[ad] == tsSeen) {
|
|
entry[ad] = true;
|
|
return true;
|
|
}
|
|
entry[ad] = true;
|
|
if (ad == adScience) {
|
|
if (markEntry(adTheology))
|
|
entry[ad] = false;
|
|
if (markEntry(adPhilosophy))
|
|
entry[ad] = false;
|
|
} else if (ad == adMassProduction) {
|
|
if (markEntry(adAutomobile))
|
|
entry[ad] = false;
|
|
if ((data->BehaviorFlags & bGender) == bMale) {
|
|
if (markEntry(adElectronics))
|
|
entry[ad] = false;
|
|
} else {
|
|
if (markEntry(adTheCorporation))
|
|
entry[ad] = false;
|
|
}
|
|
} else {
|
|
if (AdvPreq[ad][0] >= 0 && markEntry(AdvPreq[ad][0]))
|
|
entry[ad] = false;
|
|
if (AdvPreq[ad][1] >= 0 && markEntry(AdvPreq[ad][1]))
|
|
entry[ad] = false;
|
|
}
|
|
return true;
|
|
};
|
|
|
|
auto optimizeDevModel = [&](int optimizeCaps) {
|
|
TModelInfo mi;
|
|
MakeModelInfo(me, 0, ro->DevModel, mi);
|
|
int originalCat, bestQuality;
|
|
rateModel(mi, originalCat, bestQuality);
|
|
int best;
|
|
do {
|
|
best = -1;
|
|
for (int f = 0; f < nFeature; ++f) {
|
|
if ((1 << f) & optimizeCaps && (Feature[f].Preq < 0 || isResearched(Feature[f].Preq)) &&
|
|
ro->DevModel.Weight + Feature[f].Weight <= ro->DevModel.MaxWeight &&
|
|
!(f >= mcFirstNonCap && ro->DevModel.Cap[f] > 0)) {
|
|
if (setNewModelFeature(f, ro->DevModel.Cap[f] + 1) >= rExecuted) {
|
|
MakeModelInfo(me, 0, ro->DevModel, mi);
|
|
int cat, quality;
|
|
rateModel(mi, cat, quality);
|
|
if (quality > bestQuality) {
|
|
best = f;
|
|
bestQuality = quality;
|
|
}
|
|
setNewModelFeature(f, ro->DevModel.Cap[f] - 1);
|
|
}
|
|
}
|
|
}
|
|
if (best >= 0)
|
|
setNewModelFeature(best, ro->DevModel.Cap[best] + 1);
|
|
} while (best >= 0);
|
|
};
|
|
|
|
std::function<bool(int)> leaveOutsMissing = [&](int ad) -> bool {
|
|
bool res = false;
|
|
if (ro->Tech[ad] < tsSeen) {
|
|
if (isLeaveOutTech(ad))
|
|
res = true;
|
|
else if (ad == adScience) {
|
|
res = res || leaveOutsMissing(adTheology);
|
|
res = res || leaveOutsMissing(adPhilosophy);
|
|
} else if (ad == adMassProduction) {
|
|
res = true;
|
|
} else {
|
|
for (int i = 0; i < 2; ++i)
|
|
if (AdvPreq[ad][i] >= 0)
|
|
res = res || leaveOutsMissing(AdvPreq[ad][i]);
|
|
}
|
|
}
|
|
return res;
|
|
};
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == 0) {
|
|
// develop new model?
|
|
if (isResearched(adWarriorCode) && isResearched(adHorsebackRiding) &&
|
|
!((data->BehaviorFlags & bGender) == bMale && ro->Tech[adIronWorking] >= tsApplicable &&
|
|
ro->Tech[adGunpowder] < tsApplicable)) { // wait for gunpowder
|
|
// check new ground models
|
|
TModelInfo mi;
|
|
prepareNewModel(dGround);
|
|
setNewModelFeature(mcDefense, 1);
|
|
setNewModelFeature(mcOffense, 2);
|
|
setNewModelFeature(mcMob, 2);
|
|
optimizeDevModel((1 << mcOffense) + (1 << mcDefense) + (1 << mcMob) + (1 << mcLongRange) + (1 << mcFanatic));
|
|
MakeModelInfo(me, 0, ro->DevModel, mi);
|
|
if (isBetterModel(mi))
|
|
return adMilitary;
|
|
|
|
prepareNewModel(dGround);
|
|
setNewModelFeature(mcDefense, 2);
|
|
setNewModelFeature(mcOffense, 1);
|
|
optimizeDevModel((1 << mcOffense) + (1 << mcDefense) + (1 << mcFanatic));
|
|
MakeModelInfo(me, 0, ro->DevModel, mi);
|
|
if (isBetterModel(mi))
|
|
return adMilitary;
|
|
}
|
|
|
|
if (isResearched(adMapMaking) && isResearched(adSeafaring) && isResearched(adNavigation) &&
|
|
isResearched(adSteamEngine)) {
|
|
result = adMilitary;
|
|
for (int mix = 0; mix < ro->nModel; ++mix)
|
|
if (myModel[mix].Cap[mcNav] > 0)
|
|
result = -1;
|
|
if (result == adMilitary) {
|
|
prepareNewModel(dSea);
|
|
setNewModelFeature(mcWeapons, 0);
|
|
setNewModelFeature(mcDefense, 3);
|
|
return result;
|
|
}
|
|
}
|
|
}
|
|
|
|
int newResearch = -1;
|
|
|
|
// check if cooperation with other gender doesn't work -- go for old needed techs then
|
|
int stateOfArt = -1;
|
|
for (int ad = 0; ad < nAdv; ++ad)
|
|
if (ro->Tech[ad] >= tsApplicable && Advancedness[ad] > stateOfArt)
|
|
stateOfArt = Advancedness[ad];
|
|
int earliestNeeded = -1;
|
|
int earliestNeeded_NoLeaveOut = -1;
|
|
for (int ad = 0; ad < nAdv; ++ad) {
|
|
if (ro->Tech[ad] < tsSeen && advanceValue[ad] >= 0x100 &&
|
|
(earliestNeeded < 0 || Advancedness[ad] < Advancedness[earliestNeeded])) {
|
|
bool ok = false;
|
|
for (int iad = 0; iad < nResearchOrder; ++iad)
|
|
if (ResearchOrder[data->BehaviorFlags & bGender][iad] == ad) {
|
|
ok = true;
|
|
break;
|
|
}
|
|
if (!ok) {
|
|
earliestNeeded = ad;
|
|
if (!leaveOutsMissing(ad))
|
|
earliestNeeded_NoLeaveOut = ad;
|
|
}
|
|
}
|
|
}
|
|
if (earliestNeeded >= 0) {
|
|
if (earliestNeeded_NoLeaveOut >= 0 &&
|
|
Advancedness[earliestNeeded_NoLeaveOut] + ForceNeeded_NoLeaveOut < stateOfArt) {
|
|
newResearch = earliestNeeded_NoLeaveOut;
|
|
} else if (Advancedness[earliestNeeded] + ForceNeeded_LeaveOut < stateOfArt) {
|
|
newResearch = earliestNeeded;
|
|
}
|
|
}
|
|
|
|
// choose first directly researchable advance from own branch
|
|
int adNext = -1;
|
|
if (newResearch < 0) {
|
|
for (int iad = 0; iad < nResearchOrder; ++iad) {
|
|
const int ad = ResearchOrder[data->BehaviorFlags & bGender][iad];
|
|
if (ro->Tech[ad] < tsApplicable) {
|
|
if (adNext < 0)
|
|
adNext = ad;
|
|
if (AdvPreq[ad][2] != preNone) { // 2 of 3 required
|
|
int count = 0;
|
|
for (int i = 0; i < 3; ++i)
|
|
if (ro->Tech[AdvPreq[ad][i]] >= tsApplicable)
|
|
++count;
|
|
if (count >= 2)
|
|
return ad;
|
|
} else if ((AdvPreq[ad][0] == preNone || ro->Tech[AdvPreq[ad][0]] >= tsApplicable) &&
|
|
(AdvPreq[ad][1] == preNone || ro->Tech[AdvPreq[ad][1]] >= tsApplicable)) {
|
|
return ad;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (newResearch < 0) {
|
|
if (adNext >= 0) {
|
|
newResearch = adNext; // need tech from other gender
|
|
} else if (earliestNeeded_NoLeaveOut >= 0) {
|
|
newResearch = earliestNeeded_NoLeaveOut;
|
|
} else if (earliestNeeded >= 0) {
|
|
newResearch = earliestNeeded; // own branch complete, pick tech from other gender
|
|
} else { // go for future techs
|
|
result = -1;
|
|
int i = 0;
|
|
for (int ad = nAdv - 4; ad < nAdv; ++ad)
|
|
if (ro->Tech[ad] < MaxFutureTech && ro->Tech[AdvPreq[ad][0]] >= tsApplicable) {
|
|
++i;
|
|
if (randomInt(i) == 0)
|
|
result = ad;
|
|
}
|
|
return result;
|
|
}
|
|
}
|
|
|
|
entry.fill(false);
|
|
markEntry(newResearch);
|
|
result = -1;
|
|
for (int ad = 0; ad < nAdv; ++ad)
|
|
if (entry[ad] && (result < 0 || Advancedness[ad] > Advancedness[result]))
|
|
result = ad;
|
|
return result;
|
|
}
|
|
|
|
int AI::chooseStealAdvance()
|
|
{
|
|
int result = -1;
|
|
for (int ad = 0; ad < nAdv; ++ad)
|
|
if (advanceStealable(ad) && (result < 0 || Advancedness[ad] > Advancedness[result]))
|
|
result = ad;
|
|
return result;
|
|
}
|
|
|
|
//-------------------------------
|
|
// TERRAFORMING
|
|
//-------------------------------
|
|
|
|
void AI::tileWorkPlan(int loc, int cix, int &value, int &nextJob, int &totalWork)
|
|
{
|
|
totalWork = 0;
|
|
nextJob = jNone;
|
|
if (map[loc] & (fRare1 | fRare2)) {
|
|
value = 3 * 8 - 1;
|
|
return; // better than any tile with 2 food
|
|
}
|
|
|
|
const std::uint32_t oldTile = map[loc];
|
|
std::uint32_t terrType = map[loc] & fTerrain;
|
|
if (terrType >= static_cast<std::uint32_t>(fGrass)) {
|
|
if (map[loc] & fPoll) { // clean pollution
|
|
if (nextJob == jNone)
|
|
nextJob = jPoll;
|
|
totalWork += PollWork;
|
|
map[loc] &= ~static_cast<std::uint32_t>(fPoll);
|
|
}
|
|
if ((map[loc] & (fTerrain | fSpecial)) == static_cast<std::uint32_t>(fSwamp)) { // drain swamp
|
|
if (nextJob == jNone)
|
|
nextJob = jClear;
|
|
totalWork += Terrain[terrType].IrrClearWork;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fTerrain)) | fGrass;
|
|
terrType = fGrass;
|
|
map[loc] |= static_cast<std::uint32_t>(SpecialTile(loc, static_cast<int>(terrType), MapWidth())) << 5;
|
|
} else if (isResearched(adExplosives) &&
|
|
((map[loc] & (fTerrain | fSpecial)) == static_cast<std::uint32_t>(fTundra) ||
|
|
(map[loc] & (fTerrain | fSpecial)) == static_cast<std::uint32_t>(fHills)) &&
|
|
(map[loc] & fTerImp) != static_cast<std::uint32_t>(tiMine) &&
|
|
SpecialTile(loc, fHills, MapWidth()) == 0) { // transform
|
|
if (nextJob == jNone)
|
|
nextJob = jTrans;
|
|
totalWork += Terrain[terrType].TransWork;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fTerrain)) | fGrass;
|
|
terrType = fGrass;
|
|
map[loc] |= static_cast<std::uint32_t>(SpecialTile(loc, static_cast<int>(terrType), MapWidth())) << 5;
|
|
}
|
|
if (Terrain[terrType].MineEff > 0 && ro->Government != gDespotism) {
|
|
if ((map[loc] & fTerImp) != static_cast<std::uint32_t>(tiMine)) { // add mine
|
|
if (nextJob == jNone)
|
|
nextJob = jMine;
|
|
totalWork += Terrain[terrType].MineAfforestWork;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fTerImp)) | tiMine;
|
|
}
|
|
} else if (Terrain[terrType].IrrEff > 0) {
|
|
if ((map[loc] & fTerImp) == static_cast<std::uint32_t>(tiIrrigation)) { // add farmland
|
|
if (myCity[cix].Built[imSupermarket] > 0 && isResearched(adRefrigeration) &&
|
|
ro->Government != gDespotism) {
|
|
if (nextJob == jNone)
|
|
nextJob = jFarm;
|
|
totalWork += Terrain[terrType].IrrClearWork * FarmWork;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fTerImp)) | tiFarm;
|
|
}
|
|
} else if ((map[loc] & fTerImp) != static_cast<std::uint32_t>(tiFarm)) { // add irrigation
|
|
if (ro->Government != gDespotism || (map[loc] & (fTerrain | fSpecial)) != static_cast<std::uint32_t>(fGrass)) {
|
|
if (nextJob == jNone)
|
|
nextJob = jIrr;
|
|
totalWork += Terrain[terrType].IrrClearWork;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fTerImp)) | tiIrrigation;
|
|
}
|
|
}
|
|
}
|
|
if (Terrain[terrType].MoveCost == 1 && (map[loc] & (fRoad | fRR)) == 0 &&
|
|
((map[loc] & fRiver) == 0 || isResearched(adBridgeBuilding))) { // add road
|
|
if (nextJob == jNone)
|
|
nextJob = jRoad;
|
|
totalWork += RoadWork;
|
|
map[loc] |= fRoad;
|
|
}
|
|
if (((map[loc] & fTerImp) == static_cast<std::uint32_t>(tiMine) ||
|
|
Terrain[terrType].ProdRes[(map[loc] >> 5) & 3] >= 2) &&
|
|
isResearched(adRailroad) && (map[loc] & fRR) == 0 &&
|
|
((map[loc] & fRiver) == 0 || isResearched(adBridgeBuilding)) && ro->Government != gDespotism) { // add railroad
|
|
if ((map[loc] & fRoad) == 0) {
|
|
if (nextJob == jNone)
|
|
nextJob = jRoad;
|
|
totalWork += RoadWork * Terrain[terrType].MoveCost;
|
|
}
|
|
if (nextJob == jNone)
|
|
nextJob = jRR;
|
|
totalWork += RRWork * Terrain[terrType].MoveCost;
|
|
map[loc] = (map[loc] & ~static_cast<std::uint32_t>(fRoad)) | fRR;
|
|
}
|
|
}
|
|
TTileInfo tileInfo{};
|
|
rawServerCall(sGetTileInfo, loc, &tileInfo);
|
|
value = tileInfo.Food * 8 + tileInfo.Prod * 2 + tileInfo.Trade;
|
|
map[loc] = oldTile;
|
|
}
|
|
|
|
void AI::processSettlers()
|
|
{
|
|
std::array<int, lxmax * lymax> tileFood{};
|
|
std::array<int, lxmax * lymax> resourceScore{};
|
|
std::array<int, lxmax * lymax> cityScore{};
|
|
|
|
auto addJob = [&](int loc, int job, int score) { // score==1 for low-priority jobs
|
|
jobAssignment_AddJob(loc, job, score);
|
|
if (score > 1 && district[loc] >= 0 && district[loc] < maxCOD)
|
|
--settlerSurplus[district[loc]];
|
|
};
|
|
|
|
auto reserveCityRadius = [&](int loc) {
|
|
TVicinity21Loc radius;
|
|
V21_to_Loc(loc, radius);
|
|
for (int v21 = 1; v21 <= 26; ++v21) {
|
|
const int radiusLoc = radius[v21];
|
|
if (radiusLoc >= 0) {
|
|
resourceScore[radiusLoc] = 0;
|
|
tileFood[radiusLoc] = 0;
|
|
}
|
|
}
|
|
};
|
|
|
|
auto scoreRoadConnections = [&] {
|
|
const bool bridgeOk = isResearched(adBridgeBuilding);
|
|
const std::uint32_t fullyDeveloped =
|
|
isResearched(adRailroad) ? static_cast<std::uint32_t>(fRR | fCity) : static_cast<std::uint32_t>(fRoad | fRR | fCity);
|
|
for (int loc = MapWidth(); loc < MapWidth() * (MapHeight() - 1) - 1; ++loc) {
|
|
if ((((1u << (map[loc] & fTerrain)) &
|
|
(1u << fOcean | 1u << fShore | 1u << fDesert | 1u << fArctic | 1u << fUNKNOWN)) == 0) &&
|
|
(*ro->Territory)[loc] == me && (map[loc] & fullyDeveloped) == 0 &&
|
|
(bridgeOk || (map[loc] & fRiver) == 0)) {
|
|
int nFragments = 0;
|
|
int history = 0;
|
|
std::uint32_t connectMask;
|
|
if (map[loc] & fRoad)
|
|
connectMask = fRR | fCity; // check for railroad
|
|
else
|
|
connectMask = fRoad | fRR | fCity; // check for road
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(loc, adjacent);
|
|
for (int v8 = 0; v8 < 10; ++v8) {
|
|
int loc1 = adjacent[v8 & 7];
|
|
history <<= 1;
|
|
if (loc1 >= 0 && (*ro->Territory)[loc1] == me && (map[loc1] & connectMask) != 0) {
|
|
++history;
|
|
if (v8 >= 2) {
|
|
++nFragments;
|
|
switch (v8 & 1) {
|
|
case 0:
|
|
if (history & 6)
|
|
--nFragments;
|
|
break;
|
|
case 1:
|
|
if (history & 2) {
|
|
--nFragments;
|
|
} else if (history & 4) {
|
|
int a, b;
|
|
V8_to_ab((v8 - 1) & 7, a, b);
|
|
ab_to_Loc(loc, a << 1, b << 1, loc1);
|
|
if (loc1 >= 0 && (map[loc1] & connectMask) != 0)
|
|
--nFragments;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (nFragments >= 2) { // road or railroad connection desirable
|
|
int roadScore;
|
|
if (map[loc] & fRiver)
|
|
roadScore = 44 + (nFragments - 2) * 4;
|
|
else
|
|
roadScore = 56 - Terrain[map[loc] & fTerrain].MoveCost * 4 + (nFragments - 2) * 4;
|
|
if (map[loc] & fRoad)
|
|
addJob(loc, jRR, roadScore);
|
|
else
|
|
addJob(loc, jRoad, roadScore);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
settlerSurplus.fill(0);
|
|
jobAssignment_Initialize();
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 || ro->nCity < 3) {
|
|
tileFood.fill(0);
|
|
resourceScore.fill(0);
|
|
for (int loc = 0; loc < MapSize(); ++loc) {
|
|
if ((map[loc] & fTerrain) != static_cast<std::uint32_t>(fUNKNOWN)) {
|
|
if (map[loc] & fDeadLands) {
|
|
if (!isResearched(adMassProduction) || (map[loc] & fModern))
|
|
resourceScore[loc] = 20;
|
|
} else if ((map[loc] & fTerrain) == static_cast<std::uint32_t>(fGrass)) {
|
|
tileFood[loc] = Terrain[fGrass].FoodRes[(map[loc] >> 5) & 3] - 1;
|
|
} else {
|
|
const int special = SpecialTile(loc, static_cast<int>(map[loc] & fTerrain), MapWidth());
|
|
if (special != 0) {
|
|
const TerrainInfo &terrain = Terrain[map[loc] & fTerrain];
|
|
int food = terrain.FoodRes[special];
|
|
if (terrain.MineEff == 0)
|
|
food += terrain.IrrEff;
|
|
const int prod = terrain.ProdRes[special] + terrain.MineEff;
|
|
int trade = terrain.TradeRes[special];
|
|
if (terrain.MoveCost == 1)
|
|
++trade;
|
|
resourceScore[loc] = food + 2 * prod + trade - 7;
|
|
if (food > 2)
|
|
tileFood[loc] = food - 2;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (int cix = 0; cix < ro->nCity; ++cix)
|
|
if (myCity[cix].Loc >= 0)
|
|
reserveCityRadius(myCity[cix].Loc); // these resources already have a city
|
|
for (int uix = 0; uix < ro->nUn; ++uix)
|
|
if (myUnit[uix].Loc >= 0 && myUnit[uix].Job == jCity)
|
|
reserveCityRadius(myUnit[uix].Loc); // these resources almost already have a city
|
|
for (int ecix = 0; ecix < ro->nEnemyCity; ++ecix)
|
|
if ((*ro->EnemyCity)[ecix].Loc >= 0)
|
|
reserveCityRadius((*ro->EnemyCity)[ecix].Loc); // these resources already have an enemy city
|
|
|
|
// rate possible new cities
|
|
cityScore.fill(0);
|
|
for (int loc = 0; loc < MapSize(); ++loc) {
|
|
const bool foodOk =
|
|
tileFood[loc] > 0 &&
|
|
(((map[loc] & fTerrain) == static_cast<std::uint32_t>(fGrass) &&
|
|
(ro->Government != gDespotism || (map[loc] & fSpecial) == static_cast<std::uint32_t>(fSpecial1))) ||
|
|
(map[loc] & (fTerrain | fSpecial)) == static_cast<std::uint32_t>(fPrairie | fSpecial1));
|
|
if (foodOk && ((*ro->Territory)[loc] < 0 || (*ro->Territory)[loc] == me)) {
|
|
int testScore = 0;
|
|
int cityFood = 0;
|
|
int bestNearCityScore = 0;
|
|
TVicinity21Loc radius;
|
|
V21_to_Loc(loc, radius);
|
|
for (int v21 = 1; v21 <= 26; ++v21) { // sum resource scores in potential city radius
|
|
const int radiusLoc = radius[v21];
|
|
if (radiusLoc >= 0) {
|
|
cityFood += tileFood[radiusLoc];
|
|
if (resourceScore[radiusLoc] > 0)
|
|
testScore += resourceScore[radiusLoc];
|
|
if (cityScore[radiusLoc] > bestNearCityScore)
|
|
bestNearCityScore = cityScore[radiusLoc];
|
|
}
|
|
}
|
|
if (cityFood >= MinCityFood) { // city is worth founding
|
|
testScore = ((72 + 2 * testScore) << 8) + ((loc ^ me) * 4567) % 251;
|
|
// some unexactness, random but always the same for this tile
|
|
if (testScore > bestNearCityScore) { // better than all other sites in radius
|
|
if (bestNearCityScore > 0) { // found no other cities in radius
|
|
for (int v21 = 1; v21 <= 26; ++v21) {
|
|
const int radiusLoc = radius[v21];
|
|
if (radiusLoc >= 0)
|
|
cityScore[radiusLoc] = 0;
|
|
}
|
|
}
|
|
cityScore[loc] = testScore;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
for (int loc = 0; loc < MapSize(); ++loc)
|
|
if (cityScore[loc] > 0)
|
|
addJob(loc, jCity, cityScore[loc] >> 8);
|
|
}
|
|
|
|
// improve terrain
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc < 0)
|
|
continue;
|
|
int bestUnusedValue = 0;
|
|
int bestUnusedLoc = -1;
|
|
TCityAreaInfo cityAreaInfo{};
|
|
city_GetAreaInfo(cix, cityAreaInfo);
|
|
TVicinity21Loc radius;
|
|
V21_to_Loc(city.Loc, radius);
|
|
for (int v21 = 1; v21 <= 26; ++v21) {
|
|
if (v21 == CityOwnTile)
|
|
continue;
|
|
int value, nextJob, totalWork;
|
|
if (city.Tiles & (1u << v21)) { // tile is being exploited!
|
|
const int radiusLoc = radius[v21];
|
|
if (!((map[radiusLoc] & fTerrain) == static_cast<std::uint32_t>(fDesert) ||
|
|
(map[radiusLoc] & fTerrain) == static_cast<std::uint32_t>(fArctic))) {
|
|
tileWorkPlan(radiusLoc, cix, value, nextJob, totalWork);
|
|
if (nextJob == jRoad && city.Built[imPalace] + city.Built[imCourt] + city.Built[imTownHall] == 0)
|
|
addJob(radiusLoc, nextJob, 44);
|
|
else if (nextJob != jNone)
|
|
addJob(radiusLoc, nextJob, 84);
|
|
}
|
|
} else if (cityAreaInfo.Available[v21] == faAvailable) { // tile could be exploited
|
|
const int radiusLoc = radius[v21];
|
|
if (!((map[radiusLoc] & fTerrain) == static_cast<std::uint32_t>(fDesert) ||
|
|
(map[radiusLoc] & fTerrain) == static_cast<std::uint32_t>(fArctic))) {
|
|
tileWorkPlan(radiusLoc, cix, value, nextJob, totalWork);
|
|
value = (value << 16) + 0xFFFF - totalWork;
|
|
if (value > bestUnusedValue) {
|
|
bestUnusedValue = value;
|
|
bestUnusedLoc = radiusLoc;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (bestUnusedValue > 0) {
|
|
int value, nextJob, totalWork;
|
|
tileWorkPlan(bestUnusedLoc, cix, value, nextJob, totalWork);
|
|
if (nextJob != jNone)
|
|
addJob(bestUnusedLoc, nextJob, 44);
|
|
}
|
|
}
|
|
|
|
scoreRoadConnections();
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == 0) // low priority jobs
|
|
for (int loc = 0; loc < MapSize(); ++loc)
|
|
if ((*ro->Territory)[loc] == me) {
|
|
const std::uint32_t tile = map[loc];
|
|
if (tile & fPoll) {
|
|
addJob(loc, jPoll, 1);
|
|
} else {
|
|
switch (tile & (fTerrain | fSpecial | fCity)) {
|
|
case fGrass:
|
|
case fGrass + fSpecial1:
|
|
if (isResearched(adExplosives) && SpecialTile(loc, fHills, MapWidth()) > 0)
|
|
addJob(loc, jTrans, 1);
|
|
break;
|
|
case fSwamp:
|
|
if (SpecialTile(loc, fSwamp, MapWidth()) == 0)
|
|
addJob(loc, jClear, 1);
|
|
break;
|
|
case fTundra:
|
|
case fHills:
|
|
if (isResearched(adExplosives) && (tile & fTerImp) != static_cast<std::uint32_t>(tiMine) &&
|
|
SpecialTile(loc, fHills, MapWidth()) == 0)
|
|
addJob(loc, jTrans, 1);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// cities for colony ship production
|
|
if ((data->BehaviorFlags & bBarbarina) == bBarbarina) {
|
|
for (int part = 0; part < nShipPart; ++part) {
|
|
for (int i = 0; i < ColonyShipPlan[part].nLocFoundCity; ++i) {
|
|
const int loc = ColonyShipPlan[part].LocFoundCity[i];
|
|
bool started = false;
|
|
for (int uix = 0; uix < ro->nUn; ++uix)
|
|
if (myUnit[uix].Loc == loc && myUnit[uix].Job == jCity) {
|
|
started = true;
|
|
break;
|
|
}
|
|
if (!started) {
|
|
const std::uint32_t tile = (*ro->Map)[loc];
|
|
if ((tile & fTerrain) == static_cast<std::uint32_t>(fForest) ||
|
|
(tile & fTerrain) == static_cast<std::uint32_t>(fSwamp)) {
|
|
addJob(loc, jClear, 235);
|
|
} else if ((tile & fTerrain) == static_cast<std::uint32_t>(fHills)) {
|
|
if (isResearched(adExplosives))
|
|
addJob(loc, jTrans, 235);
|
|
} else {
|
|
addJob(loc, jCity, 235);
|
|
}
|
|
}
|
|
TVicinity21Loc radius;
|
|
V21_to_Loc(loc, radius);
|
|
for (int v21 = 1; v21 <= 26; ++v21) {
|
|
const int loc1 = radius[v21];
|
|
if (loc1 >= 0 && ((*ro->Map)[loc1] & (fTerrain | fSpecial)) == static_cast<std::uint32_t>(fSwamp))
|
|
addJob(loc1, jClear, 255);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// choose all settlers to work
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 &&
|
|
(unit.mix == mixSettlers || unit.mix == mixSlaves ||
|
|
((data->BehaviorFlags & bBarbarina) != 0 && myModel[unit.mix].Kind == mkSettler))) {
|
|
jobAssignment_AddUnit(uix);
|
|
if (district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD)
|
|
++settlerSurplus[district[unit.Loc]];
|
|
}
|
|
}
|
|
|
|
jobAssignment_Go();
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && (map[unit.Loc] & fCity) == 0 && unit.Job == jNone &&
|
|
(unit.mix == mixSettlers || unit.mix == mixSlaves) && !jobAssignment_GotJob(uix))
|
|
unit_MoveEx(uix, maNextCity);
|
|
}
|
|
|
|
// add settlers to city
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && (map[unit.Loc] & fCity) != 0 && myModel[unit.mix].Kind == mkSettler) {
|
|
const int dtr = district[unit.Loc];
|
|
if (unit.mix != mixSettlers ||
|
|
(dtr >= 0 && dtr < maxCOD && settlerSurplus[dtr] > districtPopulation[dtr] / 8)) {
|
|
const int cix = city_FindMyCity(unit.Loc);
|
|
TCity &city = myCity[cix];
|
|
if (city.Built[imSewer] > 0 ||
|
|
(city.Built[imAqueduct] > 0 && city.Size <= NeedSewerSize - 2) || city.Size <= NeedAqueductSize - 2) {
|
|
// settlers could be added to this city
|
|
int happy = BasicHappy;
|
|
for (int i = 0; i < nWonder; ++i)
|
|
if (city.Built[i] > 0)
|
|
++happy;
|
|
if (city.Built[imTemple] > 0)
|
|
++happy;
|
|
if (city.Built[imCathedral] > 0) {
|
|
happy += 2;
|
|
if (ro->Wonder[woBach].EffectiveOwner == me)
|
|
++happy;
|
|
}
|
|
if (city.Built[imTheater] > 0)
|
|
happy += 2;
|
|
if (city.Built[imColosseum] > 0 || (happy << 1) >= city.Size + 2) { // bigger city would be happy
|
|
unit_AddToCity(uix);
|
|
if (dtr >= 0 && dtr < maxCOD)
|
|
--settlerSurplus[dtr];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
//-------------------------------
|
|
// MY TURN
|
|
//-------------------------------
|
|
|
|
void AI::doTurn()
|
|
{
|
|
warNations = PresenceUnknown;
|
|
for (int p1 = 0; p1 < nPl; ++p1)
|
|
if (p1 != me && (ro->Alive & (1 << p1)) && ro->Treaty[p1] < trPeace)
|
|
warNations += (1 << p1);
|
|
bombardingNations = 0;
|
|
for (int emix = 0; emix < ro->nEnemyModel; ++emix) {
|
|
const TModelInfo &em = (*ro->EnemyModel)[emix];
|
|
if (em.Domain == dSea && (em.Cap & (1u << (mcLongRange - mcFirstNonCap))))
|
|
bombardingNations |= (1 << em.Owner);
|
|
}
|
|
bombardingNations &= warNations;
|
|
|
|
analyzeMap();
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 &&
|
|
ro->Tech[ResearchOrder[data->BehaviorFlags & bGender][8]] < tsApplicable)
|
|
checkGender();
|
|
|
|
if (Difficulty(me) < MaxDiff) { // not on beginner level
|
|
if (data->LastResearchTech == adHorsebackRiding && ro->ResearchTech < 0 && randomInt(6) == 0 &&
|
|
(havePort() || (continentPresence[0] & ~(static_cast<int>(1 << me) | PresenceUnknown)) != 0)) {
|
|
data->BehaviorFlags |= bBarbarina_Hide;
|
|
debugMessage(1, "Early Barbarina!");
|
|
}
|
|
if ((data->BehaviorFlags & bBarbarina) == 0) {
|
|
bool allHateMe = false;
|
|
for (int p1 = 0; p1 < nPl; ++p1) {
|
|
if ((ro->Alive & (1 << p1)) && ro->Treaty[p1] >= trNone) {
|
|
if (ro->Treaty[p1] < trPeace &&
|
|
(data->RejectTurn[static_cast<int>(Suggestion::Contact)][p1] >= 0 ||
|
|
data->RejectTurn[static_cast<int>(Suggestion::Peace)][p1] >= 0)) {
|
|
allHateMe = true;
|
|
} else {
|
|
allHateMe = false;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (allHateMe) {
|
|
data->BehaviorFlags |= bBarbarina_Hide;
|
|
debugMessage(1, "All hate me!");
|
|
}
|
|
}
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 && barbarina_GoHidden()) {
|
|
data->BehaviorFlags |= bBarbarina_Hide;
|
|
debugMessage(1, "Barbarina!");
|
|
}
|
|
if ((data->BehaviorFlags & bBarbarina) == bBarbarina_Hide && barbarina_Go()) {
|
|
data->BehaviorFlags |= bBarbarina;
|
|
debugMessage(1, "Barbarina - no mercy!");
|
|
}
|
|
}
|
|
|
|
// better government form available?
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 && ro->Turn >= LeaveDespotism && ro->Government != gAnarchy) {
|
|
if (isResearched(adDemocracy)) {
|
|
if (ro->Government != gDemocracy)
|
|
revolution();
|
|
} else if (isResearched(adTheRepublic)) {
|
|
if (ro->Government != gRepublic)
|
|
revolution();
|
|
} else if (isResearched(adMonarchy)) {
|
|
if (ro->Government != gMonarchy)
|
|
revolution();
|
|
}
|
|
}
|
|
|
|
collectModelCatStat();
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == bBarbarina) {
|
|
makeColonyShipPlan();
|
|
barbarina_DoTurn();
|
|
} else {
|
|
attackAndPatrol();
|
|
moveUnitsHome();
|
|
}
|
|
|
|
processSettlers();
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) != 0)
|
|
barbarina_SetCityProduction();
|
|
else
|
|
setCityProduction();
|
|
|
|
// correct tax rate if necessary
|
|
if (!isResearched(adWheel)) {
|
|
changeRates(0, 0);
|
|
} else {
|
|
int newTaxRate;
|
|
if (ro->TaxRate == 0 || ro->Money < (totalPopulation[me] - 4) * 2)
|
|
newTaxRate = ro->TaxRate; // don't check decreasing tax
|
|
else
|
|
newTaxRate = ro->TaxRate - 10;
|
|
while (newTaxRate < 100) {
|
|
int taxSum, scienceSum;
|
|
sumCities(newTaxRate, taxSum, scienceSum);
|
|
if (ro->Money + taxSum >= totalPopulation[me] - 4)
|
|
break; // enough
|
|
newTaxRate += 10;
|
|
}
|
|
if (newTaxRate != ro->TaxRate)
|
|
changeRates(newTaxRate, 0);
|
|
}
|
|
|
|
// clean up RequestedTechs
|
|
if (data->LastResearchTech >= 0 && data->LastResearchTech != ro->ResearchTech) { // research completed
|
|
for (int p1 = 0; p1 < nPl; ++p1) {
|
|
if (p1 != me && (ro->Alive & (1 << p1)) &&
|
|
ro->EnemyReport[p1]->TurnOfCivilReport + TechReportOutdated > ro->Turn &&
|
|
ro->EnemyReport[p1]->Tech[data->LastResearchTech] < tsSeen) {
|
|
// latest researched advance might be of interest to this nation
|
|
for (auto &req : data->RequestedTechs)
|
|
if (req >= 0 && ((req >> 8) & 0xF) == p1)
|
|
req = -1;
|
|
}
|
|
}
|
|
}
|
|
if (ro->ResearchTech == adMilitary)
|
|
data->LastResearchTech = -1;
|
|
else
|
|
data->LastResearchTech = ro->ResearchTech;
|
|
for (auto &req : data->RequestedTechs)
|
|
if (req >= 0 && ro->Tech[req & 0xFF] >= tsSeen)
|
|
req = -1;
|
|
|
|
// prepare negotiation
|
|
advanceValuesSet = false;
|
|
setAdvanceValues();
|
|
}
|
|
|
|
void AI::checkGender()
|
|
{
|
|
int newGender = -1;
|
|
for (int p1 = 0; p1 < nPl; ++p1) {
|
|
if (p1 != me && (ro->Alive & (1 << p1)) && ro->Treaty[p1] >= trFriendlyContact) {
|
|
if (PlayerHash[me] > PlayerHash[p1]) {
|
|
if (newGender == bMale) {
|
|
newGender = -2;
|
|
break; // ambiguous, don't change gender
|
|
}
|
|
newGender = bFemale;
|
|
} else {
|
|
if (newGender == bFemale) {
|
|
newGender = -2;
|
|
break; // ambiguous, don't change gender
|
|
}
|
|
newGender = bMale;
|
|
}
|
|
}
|
|
}
|
|
if (newGender >= 0 && newGender != (data->BehaviorFlags & bGender)) {
|
|
data->BehaviorFlags = (data->BehaviorFlags & ~bGender) | newGender;
|
|
debugMessage(1, std::string("Gender:=") + char(48 + newGender));
|
|
}
|
|
}
|
|
|
|
void AI::setAdvanceValues()
|
|
{
|
|
if (advanceValuesSet)
|
|
return;
|
|
advanceValuesSet = true;
|
|
|
|
advanceValue.fill(0);
|
|
|
|
auto rateResearchAdv = [&](int ad, int time) {
|
|
const int value = time == 0 ? TechValue_ForResearch_Next : TechValue_ForResearch - time;
|
|
if (advanceValue[ad] < value)
|
|
advanceValue[ad] = value;
|
|
};
|
|
|
|
std::function<void(int, int)> setPreqValues = [&](int ad, int value) {
|
|
if (ro->Tech[ad] < tsSeen && ad != ro->ResearchTech) {
|
|
if (advanceValue[ad] < value)
|
|
advanceValue[ad] = value;
|
|
if (ad == adScience) {
|
|
setPreqValues(adTheology, value - 1);
|
|
setPreqValues(adPhilosophy, value - 1);
|
|
} else if (ad == adMassProduction) {
|
|
// preqs should be researched now
|
|
} else {
|
|
if (AdvPreq[ad][0] >= 0)
|
|
setPreqValues(AdvPreq[ad][0], value - 1);
|
|
if (AdvPreq[ad][1] >= 0)
|
|
setPreqValues(AdvPreq[ad][1], value - 1);
|
|
}
|
|
}
|
|
};
|
|
|
|
auto rateImpPreq = [&](int iix, int value) {
|
|
if (value > 0 && Imp[iix].Preq >= 0)
|
|
advanceValue[Imp[iix].Preq] += value;
|
|
};
|
|
|
|
// rate techs to ensure research progress
|
|
int time = 0;
|
|
for (int ad = 0; ad < nAdv; ++ad)
|
|
if (ro->Tech[ad] == tsSeen)
|
|
++time;
|
|
int adMissing = -1;
|
|
bool emergency = true;
|
|
for (int iad = 0; iad < nResearchOrder; ++iad) {
|
|
const int ad = ResearchOrder[data->BehaviorFlags & bGender][iad];
|
|
if (ad != ro->ResearchTech && ro->Tech[ad] < tsSeen) {
|
|
if (adMissing < 0)
|
|
adMissing = ad;
|
|
rateResearchAdv(ad, time); // unseen tech of own gender
|
|
if (AdvPreq[ad][2] != preNone) { // 2 of 3 required
|
|
int count = 0;
|
|
for (int i = 0; i < 3; ++i)
|
|
if (AdvPreq[ad][i] == ro->ResearchTech || ro->Tech[AdvPreq[ad][i]] >= tsSeen)
|
|
++count;
|
|
if (count >= 2) {
|
|
emergency = false;
|
|
} else {
|
|
if (ad != adMassProduction) { // don't score third preq for MP
|
|
for (int i = 0; i < 3; ++i)
|
|
if (AdvPreq[ad][i] != ro->ResearchTech && ro->Tech[AdvPreq[ad][i]] < tsSeen)
|
|
rateResearchAdv(AdvPreq[ad][i], time);
|
|
}
|
|
time += 2 - count;
|
|
}
|
|
} else {
|
|
int count = 0;
|
|
for (int i = 0; i < 2; ++i)
|
|
if (AdvPreq[ad][i] != preNone && AdvPreq[ad][i] != ro->ResearchTech && ro->Tech[AdvPreq[ad][i]] < tsSeen) {
|
|
rateResearchAdv(AdvPreq[ad][i], time);
|
|
++count;
|
|
}
|
|
if (count == 0)
|
|
emergency = false;
|
|
time += count;
|
|
}
|
|
time += 2;
|
|
}
|
|
}
|
|
if (emergency && adMissing >= 0)
|
|
setPreqValues(adMissing, TechValue_ForResearch_Urgent);
|
|
for (int iad = 0; iad < nResearchOrder; ++iad) {
|
|
const int ad = ResearchOrder[(data->BehaviorFlags & bGender) ^ 1][iad];
|
|
if (ad == adScience)
|
|
advanceValue[ad] += 5 * TechValue_ForResearch_LeaveOut;
|
|
else if (LeaveOutValue[ad] > 0 && advanceValue[ad] > 0)
|
|
advanceValue[ad] += LeaveOutValue[ad] * TechValue_ForResearch_LeaveOut;
|
|
}
|
|
|
|
// rate military techs
|
|
for (int d = 0; d < nDomains; ++d) {
|
|
int currentCost = 0;
|
|
int currentStrength = 0;
|
|
for (int preView = 1; preView >= 0; --preView) {
|
|
for (int i = 0; i < nUpgrade; ++i) {
|
|
const UpgradeInfo &upgrade = Upgrade[d][i];
|
|
if (upgrade.Preq >= 0 && !isAiFutureTech(upgrade.Preq)) {
|
|
const bool seen = ro->ResearchTech == upgrade.Preq || ro->Tech[upgrade.Preq] >= tsSeen;
|
|
if (seen == static_cast<bool>(preView)) {
|
|
if (preView) {
|
|
if (upgrade.Cost > currentCost)
|
|
currentCost = upgrade.Cost;
|
|
currentStrength += upgrade.Strength;
|
|
} else { // rate
|
|
if (i > 0 && upgrade.Trans > 0)
|
|
advanceValue[upgrade.Preq] += 0x400;
|
|
if (upgrade.Cost <= currentCost)
|
|
advanceValue[upgrade.Preq] +=
|
|
(4 - d) * upgrade.Strength * 0x400 / (currentStrength + Upgrade[d][0].Strength);
|
|
else
|
|
advanceValue[upgrade.Preq] +=
|
|
(4 - d) * upgrade.Strength * 0x200 / (currentStrength + Upgrade[d][0].Strength);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// speed
|
|
advanceValue[adSteamEngine] += 0x400;
|
|
advanceValue[adNuclearPower] += 0x400;
|
|
advanceValue[adRocketry] += 0x400;
|
|
// features
|
|
advanceValue[adBallistics] += 0x800;
|
|
advanceValue[adCommunism] += 0x800;
|
|
// weight
|
|
advanceValue[adAutomobile] += 0x800;
|
|
advanceValue[adSteel] += 0x800;
|
|
advanceValue[adAdvancedFlight] += 0x400;
|
|
|
|
// civil non-improvement
|
|
if (ro->Turn >= LeaveDespotism) {
|
|
advanceValue[adDemocracy] += 0x80 * ro->nCity;
|
|
advanceValue[adTheRepublic] += 0x800;
|
|
}
|
|
advanceValue[adRailroad] += 0x800;
|
|
advanceValue[adBridgeBuilding] += 0x200;
|
|
advanceValue[adSpaceFlight] += 0x200;
|
|
advanceValue[adSelfContainedEnvironment] += 0x200;
|
|
advanceValue[adImpulseDrive] += 0x200;
|
|
advanceValue[adTransstellarColonization] += 0x200;
|
|
|
|
// city improvements
|
|
int maxSize = 0;
|
|
for (int cix = 0; cix < ro->nCity; ++cix)
|
|
if (myCity[cix].Size > maxSize)
|
|
maxSize = myCity[cix].Size;
|
|
int maxTrade;
|
|
if (ro->Government == gRepublic || ro->Government == gDemocracy || ro->Government == gFuture)
|
|
maxTrade = (maxSize - 1) * 3;
|
|
else
|
|
maxTrade = (maxSize - 1) * 2;
|
|
|
|
rateImpPreq(imCourt, (ro->nCity - 1) * 0x100);
|
|
rateImpPreq(imLibrary, (maxTrade - 10) * 0x180);
|
|
rateImpPreq(imMarket, (maxTrade - 10) * 0x140);
|
|
rateImpPreq(imUniversity, (maxTrade - 10) * 0x140);
|
|
rateImpPreq(imBank, (maxTrade - 10) * 0x100);
|
|
rateImpPreq(imObservatory, (maxTrade - 10) * 0x100);
|
|
rateImpPreq(imResLab, (maxTrade - 14) * 0x140);
|
|
rateImpPreq(imStockEx, (maxTrade - 10) * 0x10 * (ro->nCity - 1));
|
|
rateImpPreq(imHighways, (maxSize - 5) * 0x200);
|
|
rateImpPreq(imFactory, (maxSize - 8) * 0x200);
|
|
rateImpPreq(imMfgPlant, (maxSize - 8) * 0x1C0);
|
|
rateImpPreq(imRecycling, (maxSize - 8) * 0x180);
|
|
rateImpPreq(imHarbor, (maxSize - 7) * 0x200);
|
|
rateImpPreq(imSupermarket, 0x300);
|
|
if (ro->Turn >= 40)
|
|
rateImpPreq(imTemple, 0x400);
|
|
if (ro->Government != gDespotism) {
|
|
rateImpPreq(imCathedral, 0x400);
|
|
rateImpPreq(imTheater, 0x400);
|
|
}
|
|
if (maxSize >= NeedAqueductSize - 1) {
|
|
rateImpPreq(imAqueduct, 0x600);
|
|
rateImpPreq(imGrWall, 0x300);
|
|
}
|
|
if (cixStateImp[imPalace - imPalace] >= 0) {
|
|
const TCity &palaceCity = myCity[cixStateImp[imPalace - imPalace]];
|
|
if (palaceCity.Built[imColosseum] + palaceCity.Built[imObservatory] > 0 && palaceCity.Size >= NeedSewerSize - 1)
|
|
rateImpPreq(imSewer, 0x400);
|
|
}
|
|
bool bombarded = false;
|
|
for (int emix = 0; emix < ro->nEnemyModel; ++emix)
|
|
if ((*ro->EnemyModel)[emix].Cap & (1u << (mcLongRange - mcFirstNonCap)))
|
|
bombarded = true;
|
|
if (bombarded)
|
|
rateImpPreq(imCoastalFort, 0x400);
|
|
}
|
|
|
|
void AI::analyzeMap()
|
|
{
|
|
Barbarina::analyzeMap();
|
|
// NOTE: ToolAI::analyzeMap() (which computes Formation[]/District[]) is
|
|
// NEVER called anywhere in the real class hierarchy (verified by
|
|
// exhaustive grep of the original Pascal sources: Barbarina.pas's own
|
|
// `inherited;` call to it is commented out, and this method's
|
|
// `inherited;` only reaches Barbarina::analyzeMap(), one level up). This
|
|
// is a genuine latent dead-code situation in the shipped original StdAI,
|
|
// not a porting mistake - ported faithfully as observed.
|
|
|
|
// collect nation presence information for continents and oceans
|
|
continentPresence.fill(0);
|
|
oceanPresence.fill(0);
|
|
for (int loc = 0; loc < MapSize(); ++loc) {
|
|
int f1 = formation[loc];
|
|
if (f1 >= 0 && f1 < maxCOD) {
|
|
const int p1 = (*ro->Territory)[loc];
|
|
if (p1 >= 0) {
|
|
if ((map[loc] & fTerrain) >= static_cast<std::uint32_t>(fGrass))
|
|
continentPresence[f1] |= (1 << p1);
|
|
else
|
|
oceanPresence[f1] |= (1 << p1);
|
|
}
|
|
} else if (f1 == nfUndiscovered) {
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(loc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int loc1 = adjacent[v8];
|
|
if (loc1 >= 0) {
|
|
f1 = formation[loc1];
|
|
if (f1 >= 0 && f1 < maxCOD) {
|
|
if ((map[loc1] & fTerrain) >= static_cast<std::uint32_t>(fGrass))
|
|
continentPresence[f1] |= PresenceUnknown;
|
|
else
|
|
oceanPresence[f1] |= PresenceUnknown;
|
|
}
|
|
}
|
|
}
|
|
} else if (f1 == nfPeace) {
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(loc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int loc1 = adjacent[v8];
|
|
if (loc1 >= 0) {
|
|
f1 = formation[loc1];
|
|
if (f1 >= 0 && f1 < maxCOD) {
|
|
if ((map[loc1] & fTerrain) >= static_cast<std::uint32_t>(fGrass))
|
|
continentPresence[f1] |= (1 << (*ro->Territory)[loc]);
|
|
else
|
|
oceanPresence[f1] |= (1 << (*ro->Territory)[loc]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
totalPopulation.fill(0);
|
|
for (auto &row : continentPopulation)
|
|
row.fill(0);
|
|
districtPopulation.fill(0);
|
|
|
|
// count population
|
|
for (int cix = 0; cix < ro->nEnemyCity; ++cix) {
|
|
const TCityInfo &city = (*ro->EnemyCity)[cix];
|
|
if (city.Loc >= 0) {
|
|
totalPopulation[city.Owner] += city.Size;
|
|
if (formation[city.Loc] >= 0 && formation[city.Loc] < maxCOD)
|
|
continentPopulation[city.Owner][formation[city.Loc]] += city.Size;
|
|
}
|
|
}
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = (*ro->City)[cix];
|
|
if (city.Loc >= 0) {
|
|
totalPopulation[me] += city.Size;
|
|
if (district[city.Loc] < maxCOD)
|
|
districtPopulation[district[city.Loc]] += city.Size;
|
|
}
|
|
}
|
|
}
|
|
|
|
void AI::collectModelCatStat()
|
|
{
|
|
for (int cat = 0; cat < nAIModelCat; ++cat)
|
|
modelBestQuality[cat] = 0;
|
|
mixCaravan = -1;
|
|
mixSlaves = -1;
|
|
mixCruiser = -1;
|
|
for (int mix = 0; mix < ro->nModel; ++mix) {
|
|
modelCat[mix] = mctNone;
|
|
if (mix == 1) {
|
|
mixMilitia = mix;
|
|
} else {
|
|
const int kind = myModel[mix].Kind;
|
|
if (kind <= 0x0F) { // common units
|
|
if (myModel[mix].Cap[mcNav] > 0) {
|
|
mixCruiser = mix; // temporary!!!
|
|
} else {
|
|
int cat, quality;
|
|
rateMyModel(mix, cat, quality);
|
|
modelCat[mix] = cat;
|
|
modelQuality[mix] = quality;
|
|
if (cat >= 0 && quality > modelBestQuality[cat])
|
|
modelBestQuality[cat] = quality;
|
|
}
|
|
} else if (kind == mkSpecial_TownGuard) {
|
|
mixTownGuard = mix;
|
|
} else if (kind == mkSettler) {
|
|
mixSettlers = mix; // engineers always have higher mix
|
|
} else if (kind == mkCaravan) {
|
|
mixCaravan = mix;
|
|
} else if (kind == mkSlaves) {
|
|
mixSlaves = mix;
|
|
}
|
|
}
|
|
}
|
|
|
|
// mark obsolete models with quality=0
|
|
for (int mix = 0; mix < ro->nModel; ++mix)
|
|
if (myModel[mix].Kind < 0x10 && modelCat[mix] >= 0 &&
|
|
modelQuality[mix] + MaxExistWorseThanBestModel < modelBestQuality[modelCat[mix]])
|
|
modelQuality[mix] -= 0x40000000;
|
|
|
|
oceanWithShip = 0;
|
|
if (mixCruiser >= 0)
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.mix == mixCruiser && (map[unit.Loc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
|
|
const int i = formation[unit.Loc];
|
|
if (i >= 0 && i < maxCOD)
|
|
oceanWithShip |= (1 << i);
|
|
}
|
|
}
|
|
}
|
|
|
|
void AI::moveUnitsHome()
|
|
{
|
|
constexpr int PatrolDestination = lxmax * lymax;
|
|
constexpr int FirstSurplusLoop[2] = { 2, 1 }; // [mctGroundDefender..mctGroundAttacker]
|
|
|
|
std::array<std::int8_t, lxmax * lymax> locNeed{};
|
|
std::array<int, nUmax> destination{};
|
|
std::array<int, maxCOD> districtNeed{};
|
|
std::array<int, maxCOD> districtNeed0{};
|
|
std::array<int, nMmax> modelOrder{};
|
|
|
|
auto isBombarded = [&](int cix) {
|
|
if (bombardingNations == 0)
|
|
return false;
|
|
const TCity &city = myCity[cix];
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(city.Loc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int loc1 = adjacent[v8];
|
|
if (loc1 >= 0 && (map[loc1] & fTerrain) < static_cast<std::uint32_t>(fGrass) && formation[loc1] >= 0 &&
|
|
formation[loc1] < maxCOD && (oceanPresence[formation[loc1]] & (bombardingNations | PresenceUnknown)))
|
|
return true;
|
|
}
|
|
return false;
|
|
};
|
|
|
|
auto tryUtilize = [&](int uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Health == 100 && (map[unit.Loc] & (fCity | fOwned)) == (fCity | fOwned)) {
|
|
const int cix = city_FindMyCity(unit.Loc);
|
|
TCity &city = myCity[cix];
|
|
if ((city.Project & cpImp) == 0) {
|
|
const int prodCost = myModel[city.Project & cpIndex].Cost;
|
|
const int utilizeCost = myModel[unit.mix].Cost;
|
|
if (city.Prod < (prodCost - utilizeCost * 2 / 3) * BuildCostMod[Difficulty(me)] / 12)
|
|
unit_Disband(uix);
|
|
}
|
|
}
|
|
};
|
|
|
|
auto findDestination = [&](int uix) {
|
|
std::array<bool, lxmax * lymax> reached{};
|
|
pile.create(MapSize());
|
|
const TUn &unit = myUnit[uix];
|
|
pile.put(unit.Loc, 0x800 - unit.Movement);
|
|
const int moveStyle = getMyMoveStyle(unit.mix, 100);
|
|
int loc1, time;
|
|
while (pile.get(loc1, time)) {
|
|
if (locNeed[loc1] > 0) {
|
|
locNeed[loc1] = 0;
|
|
if (district[loc1] >= 0 && district[loc1] < maxCOD)
|
|
--districtNeed[district[loc1]];
|
|
destination[uix] = loc1;
|
|
break;
|
|
}
|
|
reached[loc1] = true;
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(loc1, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int nextLoc = adjacent[v8];
|
|
if (nextLoc >= 0 && !reached[nextLoc] && (*ro->Territory)[nextLoc] == me) {
|
|
int nextTime, recoverTurns;
|
|
const int stepResult =
|
|
checkStep(moveStyle, time, v8 & 1, nextTime, recoverTurns, map[loc1], map[nextLoc], false);
|
|
if (stepResult == csOk)
|
|
pile.put(nextLoc, nextTime);
|
|
else if (stepResult == csForbiddenTile)
|
|
reached[nextLoc] = true;
|
|
}
|
|
}
|
|
}
|
|
pile.free();
|
|
};
|
|
|
|
if (ro->Government != gAnarchy && ro->Government != gDespotism) // utilize townguards
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.Master < 0 && unit.mix == mixTownGuard)
|
|
unit_Disband(uix);
|
|
}
|
|
|
|
unitLack = {};
|
|
destination.fill(-1);
|
|
for (int i = 0; i < maxCOD; ++i)
|
|
if (uixPatrol[i] >= 0)
|
|
destination[uixPatrol[i]] = PatrolDestination;
|
|
for (int uix = 0; uix < ro->nUn; ++uix)
|
|
if (myUnit[uix].mix == mixMilitia || myUnit[uix].mix == mixCruiser)
|
|
destination[uix] = PatrolDestination;
|
|
|
|
// distribute attackers and defenders
|
|
for (int cat = mctGroundDefender; cat <= mctGroundAttacker; ++cat) {
|
|
int nModelOrder = 0;
|
|
for (int mix = 0; mix < ro->nModel; ++mix) {
|
|
if (modelCat[mix] == cat) {
|
|
int i = nModelOrder;
|
|
while (i > 0 && modelQuality[mix] < modelQuality[modelOrder[i - 1]]) {
|
|
modelOrder[i] = modelOrder[i - 1];
|
|
--i;
|
|
}
|
|
modelOrder[i] = mix;
|
|
++nModelOrder;
|
|
}
|
|
}
|
|
|
|
int loop = 0;
|
|
bool complete;
|
|
do {
|
|
if (loop == FirstSurplusLoop[cat])
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && destination[uix] < 0 && unit.Master < 0 && modelCat[unit.mix] == cat &&
|
|
modelQuality[unit.mix] < 0)
|
|
tryUtilize(uix);
|
|
}
|
|
|
|
locNeed.fill(0);
|
|
districtNeed.fill(0);
|
|
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 &&
|
|
(cat != mctGroundDefender || loop != 0 || isBombarded(cix)) &&
|
|
(loop != FirstSurplusLoop[cat] || city.Built[imBarracks] + city.Built[imMilAcademy] > 0) &&
|
|
(loop != FirstSurplusLoop[cat] + 1 || city.Built[imBarracks] + city.Built[imMilAcademy] == 0)) {
|
|
locNeed[city.Loc] = 1;
|
|
if (district[city.Loc] >= 0 && district[city.Loc] < maxCOD) {
|
|
++districtNeed[district[city.Loc]];
|
|
if (loop < FirstSurplusLoop[cat])
|
|
++unitLack[district[city.Loc]][cat];
|
|
}
|
|
}
|
|
}
|
|
|
|
if (loop == 0) // protect city building sites
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.Job == jCity && (*ro->Territory)[unit.Loc] == me) {
|
|
locNeed[unit.Loc] = 1;
|
|
if (district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD)
|
|
++districtNeed[district[unit.Loc]];
|
|
}
|
|
}
|
|
|
|
complete = loop >= FirstSurplusLoop[cat];
|
|
for (int i = nModelOrder - 1; i >= 0; --i) {
|
|
for (int fortifiedPass = 1; fortifiedPass >= 0; --fortifiedPass) {
|
|
const bool fortified = fortifiedPass != 0;
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
TUn &unit = myUnit[uix];
|
|
if (unit.mix == modelOrder[i] && unit.Loc >= 0 && destination[uix] < 0 && unit.Master < 0 &&
|
|
((unit.Flags & unFortified) != 0) == fortified && locNeed[unit.Loc] > 0) {
|
|
locNeed[unit.Loc] = 0;
|
|
if (district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD)
|
|
--districtNeed[district[unit.Loc]];
|
|
destination[uix] = unit.Loc;
|
|
complete = false;
|
|
}
|
|
}
|
|
}
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.mix == modelOrder[i] && unit.Loc >= 0 && destination[uix] < 0 && unit.Master < 0) {
|
|
if (district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD && districtNeed[district[unit.Loc]] == 0) {
|
|
// nothing
|
|
} else { // unassigned unit
|
|
findDestination(uix);
|
|
if (destination[uix] >= 0)
|
|
complete = false;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
++loop;
|
|
} while (!complete);
|
|
}
|
|
|
|
// distribute obsolete settlers
|
|
bool complete;
|
|
do {
|
|
locNeed.fill(0);
|
|
districtNeed.fill(0);
|
|
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 &&
|
|
(city.Built[imSewer] > 0 || (city.Built[imAqueduct] > 0 && city.Size <= NeedSewerSize - 2) ||
|
|
city.Size <= NeedAqueductSize - 2 || city.Project == mixSettlers)) {
|
|
locNeed[city.Loc] = 1;
|
|
if (district[city.Loc] >= 0 && district[city.Loc] < maxCOD)
|
|
++districtNeed[district[city.Loc]];
|
|
}
|
|
}
|
|
districtNeed0 = districtNeed;
|
|
|
|
complete = true;
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && destination[uix] < 0 && unit.Master < 0 && myModel[unit.mix].Kind == mkSettler &&
|
|
unit.mix != mixSettlers && unit.Job == jNone) {
|
|
if (district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD && districtNeed[district[unit.Loc]] == 0) {
|
|
if (districtNeed0[district[unit.Loc]] > 0)
|
|
complete = false;
|
|
} else { // unassigned unit
|
|
findDestination(uix);
|
|
}
|
|
}
|
|
}
|
|
} while (!complete);
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc < 0)
|
|
continue;
|
|
if (destination[uix] < 0) {
|
|
if (myModel[unit.mix].Kind != mkSettler && myModel[unit.mix].Kind != mkSlaves && unit.Master < 0 &&
|
|
(map[unit.Loc] & fCity) == 0)
|
|
unit_MoveEx(uix, maNextCity);
|
|
} else if (destination[uix] != PatrolDestination && unit.Loc != destination[uix]) {
|
|
unit_MoveEx(uix, destination[uix]);
|
|
}
|
|
}
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && (*ro->Territory)[unit.Loc] == me && district[unit.Loc] >= 0 && district[unit.Loc] < maxCOD &&
|
|
modelQuality[unit.mix] > 0) {
|
|
if (modelCat[unit.mix] == mctGroundDefender || modelCat[unit.mix] == mctGroundAttacker)
|
|
--unitLack[district[unit.Loc]][modelCat[unit.mix]];
|
|
}
|
|
}
|
|
}
|
|
|
|
void AI::checkAttack(int uix)
|
|
{
|
|
TUn &unit = myUnit[uix];
|
|
const int moveStyle = getMyMoveStyle(unit.mix, unit.Health);
|
|
bool exhausted;
|
|
do {
|
|
int attackScore = -999999;
|
|
int bestCount = 0;
|
|
int attackLoc = -1;
|
|
std::array<bool, lxmax * lymax> reached{};
|
|
pile.create(MapSize());
|
|
pile.put(unit.Loc, 0x800 - unit.Movement);
|
|
int testLoc, testTime;
|
|
// start search for something to do at current location
|
|
while (pile.get(testLoc, testTime)) {
|
|
int testScore = 0;
|
|
const std::uint32_t tile = map[testLoc];
|
|
reached[testLoc] = true;
|
|
|
|
if ((tile & fUnit) != 0 && (tile & fOwned) == 0) { // enemy unit
|
|
const int euix = unit_FindEnemyDefender(testLoc);
|
|
const TUnitInfo &enemy = (*ro->EnemyUn)[euix];
|
|
if (ro->Treaty[enemy.Owner] < trPeace) {
|
|
int attackForecast;
|
|
if (unit_AttackForecast(uix, testLoc, 0x800 - testTime, attackForecast)) {
|
|
// attack possible, but advantageous?
|
|
int myDamage, enemyDamage;
|
|
if (attackForecast == 0) { // enemy unit would be destroyed
|
|
myDamage = unit.Health + DestroyBonus;
|
|
enemyDamage = enemy.Health + DestroyBonus;
|
|
} else if (attackForecast > 0) { // enemy unit would be destroyed
|
|
myDamage = unit.Health - attackForecast;
|
|
enemyDamage = enemy.Health + DestroyBonus;
|
|
} else { // own unit would be destroyed
|
|
myDamage = unit.Health + DestroyBonus;
|
|
enemyDamage = enemy.Health + attackForecast;
|
|
}
|
|
testScore = (Aggressive * 2 * (enemyDamage * (*ro->EnemyModel)[enemy.emix].Cost)) /
|
|
(myDamage * myModel[unit.mix].Cost);
|
|
if (testScore <= 100) {
|
|
testScore = 0; // own losses exceed enemy losses, no good
|
|
} else {
|
|
if (testScore > attackScore)
|
|
bestCount = 0;
|
|
if (testScore >= attackScore) {
|
|
++bestCount;
|
|
if (randomInt(bestCount) == 0) {
|
|
attackScore = testScore;
|
|
attackLoc = testLoc;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else if ((tile & fCity) != 0 && (tile & fOwned) == 0) {
|
|
// enemy city - nothing to do here
|
|
} else { // no enemy city or unit here
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(testLoc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int nextLoc = adjacent[v8];
|
|
if (nextLoc >= 0 && !reached[nextLoc] && (map[nextLoc] & fTerrain) != static_cast<std::uint32_t>(fUNKNOWN)) {
|
|
if ((map[nextLoc] & (fUnit | fOwned)) == fUnit) {
|
|
pile.put(nextLoc, testTime); // foreign unit!
|
|
} else {
|
|
int nextTime, recoverTurns;
|
|
const int stepResult = checkStep(moveStyle, testTime, v8 & 1, nextTime, recoverTurns,
|
|
map[unit.Loc], map[nextLoc], true);
|
|
if (stepResult == csOk || stepResult == csCheckTerritory) {
|
|
if (nextTime < 0x1000)
|
|
pile.put(nextLoc, nextTime);
|
|
} else if (stepResult == csForbiddenTile) {
|
|
reached[nextLoc] = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
pile.free();
|
|
|
|
if (attackLoc >= 0) {
|
|
const int oldLoc = unit.Loc;
|
|
const int moveResult = unit_Move(uix, attackLoc);
|
|
exhausted = (unit.Loc == oldLoc) || ((moveResult & (rMoreTurns | rUnitRemoved)) != 0);
|
|
if (moveResult & rLocationReached) {
|
|
if (unit.Movement < 100) {
|
|
exhausted = true;
|
|
} else {
|
|
const int attackResult = unit_Attack(uix, attackLoc);
|
|
exhausted = (attackResult & rExecuted) == 0 || (attackResult & rUnitRemoved) != 0;
|
|
}
|
|
}
|
|
} else {
|
|
exhausted = true;
|
|
}
|
|
} while (!exhausted);
|
|
}
|
|
|
|
void AI::patrol(int uix)
|
|
{
|
|
constexpr int DistanceScore = 4;
|
|
TUn &unit = myUnit[uix];
|
|
const bool captureOnly = (100 - unit.Health) * Terrain[map[unit.Loc] & fTerrain].Defense > 60 &&
|
|
!((map[unit.Loc] & fTerrain) == static_cast<std::uint32_t>(fOcean) ||
|
|
(map[unit.Loc] & fTerrain) == static_cast<std::uint32_t>(fShore) ||
|
|
(map[unit.Loc] & fTerrain) == static_cast<std::uint32_t>(fArctic) ||
|
|
(map[unit.Loc] & fTerrain) == static_cast<std::uint32_t>(fDesert));
|
|
const int moveStyle = getMyMoveStyle(unit.mix, unit.Health);
|
|
bool exhausted;
|
|
do {
|
|
int patrolScore = -999999;
|
|
int bestCount = 0;
|
|
int patrolLoc = -1;
|
|
static std::array<std::int8_t, lxmax * lymax> adjacentUnknown;
|
|
std::fill_n(adjacentUnknown.begin(), MapSize(), static_cast<std::int8_t>(-1));
|
|
pile.create(MapSize());
|
|
pile.put(unit.Loc, 0x800 - unit.Movement);
|
|
int testLoc, testTime;
|
|
while (pile.get(testLoc, testTime)) {
|
|
if (50 * 0x1000 - DistanceScore * testTime <= patrolScore || // assume 50 is the best achievable
|
|
(captureOnly && testTime >= 0x1000))
|
|
break;
|
|
|
|
int testScore = 0;
|
|
const std::uint32_t tile = map[testLoc];
|
|
adjacentUnknown[testLoc] = 0;
|
|
|
|
if ((tile & fUnit) != 0 && (tile & fOwned) == 0) {
|
|
// enemy unit - nothing to do here
|
|
} else if ((tile & fCity) != 0 && (tile & fOwned) == 0) {
|
|
if ((tile & fObserved) != 0 && myModel[unit.mix].Domain == dGround && myModel[unit.mix].Attack > 0 &&
|
|
((*ro->Territory)[testLoc] < 0 || ro->Treaty[(*ro->Territory)[testLoc]] < trPeace))
|
|
testScore = 40; // unfriendly undefended city -- capture!
|
|
} else { // no enemy city or unit here
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(testLoc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int nextLoc = adjacent[v8];
|
|
if (nextLoc >= 0 && adjacentUnknown[nextLoc] < 0) {
|
|
if ((map[nextLoc] & fTerrain) == static_cast<std::uint32_t>(fUNKNOWN)) {
|
|
++adjacentUnknown[testLoc];
|
|
} else if (formation[nextLoc] == formation[testLoc]) {
|
|
int nextTime, recoverTurns;
|
|
const int stepResult = checkStep(moveStyle, testTime, v8 & 1, nextTime, recoverTurns,
|
|
map[testLoc], map[nextLoc], true);
|
|
if (stepResult == csOk) {
|
|
pile.put(nextLoc, nextTime);
|
|
} else if (stepResult == csForbiddenTile) {
|
|
adjacentUnknown[nextLoc] = 0;
|
|
} else if (stepResult == csCheckTerritory) {
|
|
if ((*ro->Territory)[nextLoc] == (*ro->Territory)[testLoc])
|
|
pile.put(nextLoc, nextTime);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (!captureOnly) {
|
|
if (adjacentUnknown[testLoc] > 0)
|
|
testScore = 20 + adjacentUnknown[testLoc];
|
|
else
|
|
testScore = (ro->Turn - (*ro->MapObservedLast)[testLoc]) / 16;
|
|
}
|
|
}
|
|
|
|
if (testScore > 0) {
|
|
testScore = testScore * 0x1000 - DistanceScore * testTime;
|
|
if (testScore > patrolScore)
|
|
bestCount = 0;
|
|
if (testScore >= patrolScore) {
|
|
++bestCount;
|
|
if (randomInt(bestCount) == 0) {
|
|
patrolScore = testScore;
|
|
patrolLoc = testLoc;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
pile.free();
|
|
|
|
if (patrolLoc >= 0) { // attack/capture/discover/patrol task found, execute it
|
|
const int oldLoc = unit.Loc;
|
|
const int moveResult = unit_Move(uix, patrolLoc);
|
|
exhausted = (unit.Loc == oldLoc) || ((moveResult & (rMoreTurns | rUnitRemoved)) != 0);
|
|
} else {
|
|
exhausted = true;
|
|
}
|
|
} while (!exhausted);
|
|
}
|
|
|
|
void AI::attackAndPatrol()
|
|
{
|
|
constexpr int nAttackCatOrder = 3;
|
|
constexpr int AttackCatOrder[nAttackCatOrder] = { mctGroundAttacker, mctCruiser, mctGroundDefender };
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) { // utilize militia
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.mix == mixMilitia &&
|
|
(formation[unit.Loc] < 0 || formation[unit.Loc] >= maxCOD ||
|
|
(continentPresence[formation[unit.Loc]] & PresenceUnknown) == 0))
|
|
unit_Disband(uix);
|
|
}
|
|
|
|
if (ro->nEnemyUn > 0)
|
|
for (int iCat = 0; iCat < nAttackCatOrder; ++iCat)
|
|
for (int fortifiedPass = 0; fortifiedPass <= 1; ++fortifiedPass) {
|
|
const bool fortified = fortifiedPass != 0;
|
|
for (int uix = ro->nUn - 1; uix >= 0; --uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && modelCat[unit.mix] == AttackCatOrder[iCat] && myModel[unit.mix].Attack > 0 &&
|
|
((unit.Flags & unFortified) != 0) == fortified)
|
|
checkAttack(uix);
|
|
}
|
|
}
|
|
|
|
uixPatrol.fill(-1);
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
const TModel &model = myModel[unit.mix];
|
|
if (unit.Loc >= 0 && model.Domain == dGround && model.Attack > 0 && model.Speed >= 250 &&
|
|
(map[unit.Loc] & fTerrain) >= static_cast<std::uint32_t>(fGrass) && formation[unit.Loc] >= 0 &&
|
|
formation[unit.Loc] < maxCOD &&
|
|
(uixPatrol[formation[unit.Loc]] < 0 || unit.ID < myUnit[uixPatrol[formation[unit.Loc]]].ID))
|
|
uixPatrol[formation[unit.Loc]] = uix;
|
|
}
|
|
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc < 0)
|
|
continue;
|
|
bool isPatrolUnit;
|
|
if (unit.mix == mixMilitia) {
|
|
if ((ro->nUn < 3 && ro->nCity == 1) || (map[unit.Loc] & fCity) == 0) {
|
|
isPatrolUnit = true;
|
|
} else { // militia
|
|
isPatrolUnit = false;
|
|
for (int uix1 = 0; uix1 < ro->nUn; ++uix1)
|
|
if (uix1 != uix && myUnit[uix1].Loc == unit.Loc && myUnit[uix1].mix != mixSettlers)
|
|
isPatrolUnit = true;
|
|
}
|
|
} else {
|
|
isPatrolUnit = unit.mix == mixCruiser ||
|
|
((map[unit.Loc] & fTerrain) >= static_cast<std::uint32_t>(fGrass) && formation[unit.Loc] >= 0 &&
|
|
formation[unit.Loc] < maxCOD && uix == uixPatrol[formation[unit.Loc]]);
|
|
}
|
|
if (isPatrolUnit)
|
|
patrol(uix);
|
|
}
|
|
}
|
|
|
|
bool AI::havePort() const
|
|
{
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc < 0)
|
|
continue;
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(city.Loc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int adjacentLoc = adjacent[v8];
|
|
if (adjacentLoc >= 0 && (map[adjacentLoc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
|
|
const int f = formation[adjacentLoc];
|
|
if (f >= 0 && f < maxCOD && (oceanPresence[f] & ~(1 << me)))
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void AI::setCityProduction()
|
|
{
|
|
std::array<int, nCmax> homeCount{};
|
|
std::array<int, nCmax> cityProdRep{};
|
|
std::array<bool, nCmax> milProdCity{};
|
|
int cixMilAcademy = -1;
|
|
|
|
auto chooseBuildModel = [&](int cat) {
|
|
int count = 0;
|
|
int result = -1;
|
|
for (int mix = 0; mix < ro->nModel; ++mix)
|
|
if (modelCat[mix] == cat && modelQuality[mix] >= modelBestQuality[cat] - MaxBuildWorseThanBestModel) {
|
|
++count;
|
|
if (randomInt(count) == 0)
|
|
result = mix;
|
|
}
|
|
return result;
|
|
};
|
|
|
|
auto nominateMilProdCities = [&] { // find military production cities
|
|
milProdCity.fill(false);
|
|
getCityProdPotential();
|
|
for (int d = 0; d < maxCOD; ++d) {
|
|
int total = 0;
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 && district[city.Loc] == d)
|
|
total += cityResult[cix];
|
|
}
|
|
if (total == 0)
|
|
continue; // district does not exist
|
|
|
|
int share = 0;
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 && district[city.Loc] == d && city.Built[imBarracks] + city.Built[imMilAcademy] > 0) {
|
|
milProdCity[cix] = true;
|
|
share += cityResult[cix];
|
|
}
|
|
}
|
|
|
|
int threshold = 0xFFFF;
|
|
int sharePlus = 0;
|
|
while (threshold > 0 && share < total * MilProdShare / 100) {
|
|
int newThreshold = -1;
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 && district[city.Loc] == d && city.Built[imBarracks] + city.Built[imMilAcademy] == 0 &&
|
|
city.Built[imObservatory] == 0 && cityResult[cix] < threshold && cityResult[cix] >= newThreshold) {
|
|
if (cityResult[cix] > newThreshold) {
|
|
newThreshold = cityResult[cix];
|
|
sharePlus = cityResult[cix];
|
|
} else {
|
|
sharePlus += cityResult[cix];
|
|
}
|
|
}
|
|
}
|
|
threshold = newThreshold;
|
|
share += sharePlus;
|
|
}
|
|
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 && district[city.Loc] == d && city.Built[imBarracks] + city.Built[imMilAcademy] == 0 &&
|
|
cityResult[cix] >= threshold)
|
|
milProdCity[cix] = true;
|
|
}
|
|
}
|
|
|
|
// check best city for military academy
|
|
cixMilAcademy = cixStateImp[imMilAcademy - imPalace];
|
|
if (cixStateImp[imPalace - imPalace] >= 0) {
|
|
const int d = district[myCity[cixStateImp[imPalace - imPalace]].Loc];
|
|
if (d >= 0 && d < maxCOD) {
|
|
cixMilAcademy = -1;
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
const TCity &city = myCity[cix];
|
|
if (city.Loc >= 0 && district[city.Loc] == d && city.Built[imObservatory] + city.Built[imPalace] == 0 &&
|
|
(cixMilAcademy < 0 || cityResult[cix] > cityResult[cixMilAcademy]))
|
|
cixMilAcademy = cix;
|
|
}
|
|
}
|
|
if (cixMilAcademy >= 0 && cixStateImp[imMilAcademy - imPalace] >= 0 &&
|
|
cixMilAcademy != cixStateImp[imMilAcademy - imPalace] &&
|
|
myCity[cixStateImp[imMilAcademy - imPalace]].Built[imObservatory] == 0 &&
|
|
cityResult[cixMilAcademy] <= cityResult[cixStateImp[imMilAcademy - imPalace]] * 3 / 2)
|
|
cixMilAcademy = cixStateImp[imMilAcademy - imPalace]; // because not so much better
|
|
}
|
|
};
|
|
|
|
auto changeHomeCities = [&] {
|
|
if (ro->Government == gAnarchy || ro->Government == gFundamentalism)
|
|
return;
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.Home >= 0 && (map[unit.Loc] & fCity) != 0 && myCity[unit.Home].Loc != unit.Loc &&
|
|
myModel[unit.mix].Kind != mkSettler) {
|
|
const int newHome = city_FindMyCity(unit.Loc);
|
|
int homeSupport, newHomeSupport;
|
|
switch (ro->Government) {
|
|
case gDespotism:
|
|
homeSupport = homeCount[unit.Home] - myCity[unit.Home].Size;
|
|
newHomeSupport = homeCount[newHome] - myCity[newHome].Size;
|
|
break;
|
|
case gMonarchy:
|
|
case gCommunism:
|
|
homeSupport = homeCount[unit.Home] - myCity[unit.Home].Size / 2;
|
|
newHomeSupport = homeCount[newHome] - myCity[newHome].Size / 2;
|
|
break;
|
|
default:
|
|
homeSupport = homeCount[unit.Home];
|
|
newHomeSupport = homeCount[newHome];
|
|
break;
|
|
}
|
|
if (homeSupport > 0) {
|
|
const int singleSupport = (myModel[unit.mix].Flags & mdDoubleSupport) == 0 ? 1 : 2;
|
|
homeSupport -= singleSupport;
|
|
newHomeSupport += singleSupport;
|
|
if (homeSupport < 0)
|
|
homeSupport = 0;
|
|
if (newHomeSupport < 0)
|
|
newHomeSupport = 0;
|
|
if (newHomeSupport <= 0 ||
|
|
cityProdRep[unit.Home] - homeSupport <= cityProdRep[newHome] - newHomeSupport) {
|
|
homeCount[unit.Home] -= singleSupport;
|
|
homeCount[newHome] += singleSupport;
|
|
unit_SetHomeHere(uix);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
homeCount.fill(0);
|
|
for (int uix = 0; uix < ro->nUn; ++uix) {
|
|
const TUn &unit = myUnit[uix];
|
|
if (unit.Loc >= 0 && unit.Home >= 0)
|
|
homeCount[unit.Home] += (myModel[unit.mix].Flags & mdDoubleSupport) == 0 ? 1 : 2;
|
|
}
|
|
|
|
nominateMilProdCities();
|
|
|
|
for (int cix = 0; cix < ro->nCity; ++cix) {
|
|
TCity &city = myCity[cix];
|
|
if (city.Loc < 0 || (city.Flags & chCaptured) != 0 || district[city.Loc] < 0)
|
|
continue;
|
|
|
|
if (city.Size < 4)
|
|
city_OptimizeTiles(cix, rwMaxGrowth);
|
|
else
|
|
city_OptimizeTiles(cix, rwForceProd);
|
|
|
|
TCityReport report{};
|
|
city_GetReport(cix, report);
|
|
cityProdRep[cix] = report.ProdRep;
|
|
|
|
bool destructed = false;
|
|
auto tryBuild = [&](int improvement, int &newImprovement) {
|
|
if (newImprovement == imTrGoods && city.Built[improvement] == 0 &&
|
|
(Imp[improvement].Preq == preNone || ro->Tech[Imp[improvement].Preq] >= tsApplicable) &&
|
|
city_Improvable(cix, improvement))
|
|
newImprovement = improvement;
|
|
};
|
|
auto tryDestruct = [&](int improvement) {
|
|
if (destructed || city.Built[improvement] == 0)
|
|
return;
|
|
if (city_CurrentImprovementProject(cix) >= 0)
|
|
city_RebuildImprovement(cix, improvement);
|
|
else
|
|
city_SellImprovement(cix, improvement);
|
|
destructed = true;
|
|
};
|
|
|
|
bool checkProd = ro->Turn == 0 || (city.Flags & chProduction) != 0 || !city_HasProject(cix);
|
|
if (!checkProd) { // check whether producing double state improvement or wonder
|
|
const int iix = city_CurrentImprovementProject(cix);
|
|
if (iix >= 0 && (((Imp[iix].Kind == ikNatLocal || Imp[iix].Kind == ikNatGlobal) &&
|
|
ro->NatBuilt[iix - nWonder] > 0) ||
|
|
(Imp[iix].Kind == ikWonder && ro->Wonder[iix].CityID != WonderNotBuiltYet)))
|
|
checkProd = true;
|
|
}
|
|
if (checkProd) { // check production
|
|
bool isPort = false;
|
|
bool isNavalBase = false;
|
|
bool needCruiser = false;
|
|
TVicinity8Loc adjacent;
|
|
V8_to_Loc(city.Loc, adjacent);
|
|
for (int v8 = 0; v8 < 8; ++v8) {
|
|
const int adjacentLoc = adjacent[v8];
|
|
if (adjacentLoc >= 0 && (map[adjacentLoc] & fTerrain) < static_cast<std::uint32_t>(fGrass)) {
|
|
isPort = true; // shore tile at adjacent location -- city is port!
|
|
if (formation[adjacentLoc] >= 0 && formation[adjacentLoc] < maxCOD &&
|
|
(oceanPresence[formation[adjacentLoc]] & warNations)) {
|
|
isNavalBase = true;
|
|
if (((1 << formation[adjacentLoc]) & oceanWithShip) == 0)
|
|
needCruiser = true;
|
|
}
|
|
}
|
|
}
|
|
(void)isNavalBase;
|
|
|
|
int newImprovement;
|
|
if (ro->Turn == 0) {
|
|
newImprovement = -1;
|
|
city_StartUnitProduction(cix, mixMilitia); // militia
|
|
} else {
|
|
newImprovement = imTrGoods;
|
|
}
|
|
|
|
const int dtr = district[city.Loc]; // formation of city
|
|
|
|
if (newImprovement == imTrGoods) {
|
|
if (city.Built[imPalace] + city.Built[imCourt] + city.Built[imTownHall] == 0)
|
|
tryBuild(imTownHall, newImprovement);
|
|
}
|
|
|
|
if (newImprovement == imTrGoods && ro->Government == gDespotism && report.Support == 0) {
|
|
// produce town guard
|
|
newImprovement = -1;
|
|
city_StartUnitProduction(cix, mixTownGuard);
|
|
}
|
|
|
|
if (newImprovement == imTrGoods) {
|
|
int maxcount = ro->Government == gDespotism ? city.Size : city.Size / 2;
|
|
|
|
int maxSettlers;
|
|
if ((isResearched(adRailroad) && mixSettlers == 0) || // better wait for engineers
|
|
city.Built[imColosseum] + city.Built[imObservatory] > 0)
|
|
maxSettlers = 1;
|
|
else
|
|
maxSettlers = (city.Size + 2) / 6;
|
|
const bool produceSettlers =
|
|
homeCount[cix] < maxcount + city.Size / 2 &&
|
|
(report.Eaten - city.Size * 2) / SettlerFood[ro->Government] < maxSettlers &&
|
|
(dtr < 0 || dtr >= maxCOD || settlerSurplus[dtr] <= 0);
|
|
|
|
const bool produceMil =
|
|
homeCount[cix] < maxcount + city.Size / 2 && city.Built[imBarracks] + city.Built[imMilAcademy] > 0 &&
|
|
(modelBestQuality[mctGroundDefender] > 0 || modelBestQuality[mctGroundAttacker] > 0) &&
|
|
(((dtr < maxCOD) &&
|
|
(unitLack[dtr][mctGroundAttacker] > 0 || unitLack[dtr][mctGroundDefender] > 0)) ||
|
|
homeCount[cix] < maxcount);
|
|
|
|
if (produceMil || (!produceSettlers && homeCount[cix] < maxcount)) {
|
|
newImprovement = -1;
|
|
if (dtr >= maxCOD || modelBestQuality[mctGroundDefender] == 0 ||
|
|
unitLack[dtr][mctGroundAttacker] >= unitLack[dtr][mctGroundDefender])
|
|
city_StartUnitProduction(cix, chooseBuildModel(mctGroundAttacker));
|
|
else
|
|
city_StartUnitProduction(cix, chooseBuildModel(mctGroundDefender));
|
|
} else if (produceSettlers) {
|
|
newImprovement = -1;
|
|
city_StartUnitProduction(cix, mixSettlers);
|
|
}
|
|
}
|
|
|
|
if (newImprovement >= 0) { // produce improvement
|
|
if (ro->Turn >= 40 && report.Happy * 2 <= city.Size && city.Built[imColosseum] == 0)
|
|
tryBuild(imTemple, newImprovement);
|
|
if (cix == cixMilAcademy)
|
|
tryBuild(imMilAcademy, newImprovement);
|
|
else if ((city.Built[imPalace] > 0 || (milProdCity[cix] && city.Built[imTemple] > 0)) &&
|
|
city.Built[imObservatory] == 0)
|
|
tryBuild(imBarracks, newImprovement);
|
|
if (report.Trade - report.Corruption >= 11)
|
|
tryBuild(imLibrary, newImprovement);
|
|
if (report.Trade - report.Corruption >= 11)
|
|
tryBuild(imMarket, newImprovement);
|
|
if (report.Trade - report.Corruption >= 11 && report.Happy >= 4)
|
|
tryBuild(imUniversity, newImprovement);
|
|
if (city.Built[imPalace] > 0 && report.Trade - report.Corruption >= 11 && report.Happy >= 4 &&
|
|
ro->NatBuilt[imObservatory - nWonder] == 0)
|
|
tryBuild(imObservatory, newImprovement); // always build observatory in capital
|
|
if (report.Trade - report.Corruption >= 15 && report.Happy >= 4)
|
|
tryBuild(imResLab, newImprovement);
|
|
if (city.Size >= 9 && city.Built[imPalace] + city.Built[imCourt] > 0)
|
|
tryBuild(imHighways, newImprovement);
|
|
if (ro->Government != gDespotism && report.Happy * 2 <= city.Size &&
|
|
city.Built[imCathedral] + city.Built[imTheater] + city.Built[imColosseum] == 0) {
|
|
tryBuild(imCathedral, newImprovement);
|
|
tryBuild(imTheater, newImprovement);
|
|
}
|
|
if (ro->Government != gDespotism && city.Size >= NeedAqueductSize)
|
|
tryBuild(imAqueduct, newImprovement);
|
|
if (city.Built[imColosseum] + city.Built[imObservatory] > 0 && city.Size >= NeedSewerSize)
|
|
tryBuild(imSewer, newImprovement);
|
|
if (ro->NatBuilt[imGrWall - nWonder] == 0 && city.Built[imObservatory] + city.Built[imMilAcademy] == 0 &&
|
|
ro->nCity >= 6 && cixStateImp[imPalace - imPalace] >= 0 &&
|
|
formation[city.Loc] == formation[myCity[cixStateImp[imPalace - imPalace]].Loc] &&
|
|
report.ProdRep - report.Support >= 6)
|
|
tryBuild(imGrWall, newImprovement);
|
|
if (ro->NatBuilt[imSpacePort - nWonder] == 0 && city.Built[imObservatory] + city.Built[imMilAcademy] == 0 &&
|
|
report.ProdRep - report.Support >= 10)
|
|
tryBuild(imSpacePort, newImprovement);
|
|
if (report.ProdRep >= 8)
|
|
tryBuild(imFactory, newImprovement);
|
|
if (report.ProdRep >= 12)
|
|
tryBuild(imMfgPlant, newImprovement);
|
|
if (isPort) {
|
|
if (city.Size > 8) {
|
|
tryBuild(imHarbor, newImprovement);
|
|
} else if (city.Built[imHarbor] == 0 && city.Size > 4 &&
|
|
(((city.Size & 1) != 0 && report.Happy * 2 > city.Size) || city.Built[imColosseum] > 0)) {
|
|
// check building harbor
|
|
TVicinity21Loc radius;
|
|
V21_to_Loc(city.Loc, radius);
|
|
for (int v21 = 1; v21 <= 26; ++v21) { // city is in growth mode - using any 1-food tile?
|
|
if (city.Tiles & (1u << v21)) {
|
|
const std::uint32_t terrType = map[radius[v21]] & (fTerrain | fSpecial);
|
|
if (terrType == static_cast<std::uint32_t>(fDesert) ||
|
|
terrType == static_cast<std::uint32_t>(fTundra) ||
|
|
terrType == static_cast<std::uint32_t>(fSwamp) ||
|
|
terrType == static_cast<std::uint32_t>(fForest) ||
|
|
terrType == static_cast<std::uint32_t>(fHills) ||
|
|
terrType == static_cast<std::uint32_t>(fMountains)) {
|
|
tryBuild(imHarbor, newImprovement);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (city.Size <= 10 && report.FoodRep - report.Eaten < 2 && report.Happy * 2 >= city.Size + 2)
|
|
tryBuild(imSupermarket, newImprovement);
|
|
|
|
// less important
|
|
if (city.Built[imPalace] > 0 && ro->NatBuilt[imColosseum - nWonder] == 0 && city.Size >= 10)
|
|
tryBuild(imColosseum, newImprovement); // always build colosseum in capital
|
|
if (city.Built[imPalace] + city.Built[imCourt] == 0 &&
|
|
(report.Corruption > 2 || isResearched(Imp[imHighways].Preq)))
|
|
tryBuild(imCourt, newImprovement); // replace courthouse
|
|
if (report.PollRep >= 15)
|
|
tryBuild(imRecycling, newImprovement);
|
|
if (report.Trade - report.Corruption >= 11 && ro->Money < totalPopulation[me] * 2)
|
|
tryBuild(imBank, newImprovement);
|
|
if (ro->NatBuilt[imStockEx - nWonder] == 0 && city.Built[imObservatory] + city.Built[imMilAcademy] == 0 &&
|
|
report.ProdRep - report.Support >= 8)
|
|
tryBuild(imStockEx, newImprovement);
|
|
|
|
// every improvement checked -- start production now
|
|
if (newImprovement != imTrGoods) {
|
|
if (city_StartImprovement(cix, newImprovement) < rExecuted)
|
|
newImprovement = imTrGoods;
|
|
}
|
|
if (newImprovement == imTrGoods && (ro->Turn & 0xF) == 0) { // try colony ship parts
|
|
newImprovement = imShipComp;
|
|
while (newImprovement <= imShipHab &&
|
|
(ro->Tech[Imp[newImprovement].Preq] < 0 ||
|
|
city_StartImprovement(cix, newImprovement) < rExecuted))
|
|
++newImprovement;
|
|
if (newImprovement > imShipHab)
|
|
newImprovement = imTrGoods;
|
|
}
|
|
}
|
|
|
|
if (newImprovement == imTrGoods && needCruiser && mixCruiser >= 0 &&
|
|
(city.Project & (cpImp | cpIndex)) != mixCruiser && report.ProdRep - report.Support >= 6) {
|
|
newImprovement = -1;
|
|
city_StartUnitProduction(cix, mixCruiser);
|
|
}
|
|
|
|
if (newImprovement == imTrGoods && city_HasProject(cix))
|
|
city_StopProduction(cix);
|
|
|
|
// rebuild imps no longer needed
|
|
if (ro->TaxRate == 0 && ro->Money >= totalPopulation[me] * 4)
|
|
tryDestruct(imBank);
|
|
else if (report.Happy * 2 >= city.Size + 6)
|
|
tryDestruct(imTheater);
|
|
else if (report.Happy * 2 >= city.Size + 4)
|
|
tryDestruct(imTemple);
|
|
}
|
|
|
|
// rebuild imps no longer needed, no report needed
|
|
if (city.Built[imObservatory] > 0 || (city.Project & (cpImp | cpIndex)) == (cpImp | imObservatory))
|
|
tryDestruct(imBarracks);
|
|
if (map[city.Loc] & fGrWall)
|
|
tryDestruct(imWalls);
|
|
if (city.Built[imColosseum] > 0) {
|
|
tryDestruct(imTheater);
|
|
tryDestruct(imCathedral);
|
|
tryDestruct(imTemple);
|
|
}
|
|
}
|
|
|
|
changeHomeCities();
|
|
}
|
|
|
|
int AI::chooseGovernment()
|
|
{
|
|
if (data->BehaviorFlags & bBarbarina)
|
|
return isResearched(adTheology) ? gFundamentalism : gDespotism;
|
|
if (isResearched(adDemocracy))
|
|
return gDemocracy;
|
|
if (isResearched(adTheRepublic))
|
|
return gRepublic;
|
|
if (isResearched(adMonarchy))
|
|
return gMonarchy;
|
|
return gDespotism;
|
|
}
|
|
|
|
//-------------------------------
|
|
// DIPLOMACY
|
|
//-------------------------------
|
|
|
|
int AI::mostWanted(int nation, int adGiveAway) const
|
|
{
|
|
int result = -1;
|
|
if (ro->Tech[adGiveAway] < tsApplicable)
|
|
return result;
|
|
if (adGiveAway == adTheRepublic && (data->BehaviorFlags & bGender) == bFemale && ro->Tech[adTheology] < tsSeen) {
|
|
if (ro->EnemyReport[nation]->Tech[adTheology] >= tsApplicable)
|
|
result = adTheology;
|
|
return result;
|
|
}
|
|
for (int ad = 0; ad <= nAdv - 5; ++ad) { // no future techs
|
|
if (advanceValue[ad] > 0 && ro->Tech[ad] < tsSeen && ad != ro->ResearchTech &&
|
|
ro->EnemyReport[nation]->Tech[ad] >= tsApplicable &&
|
|
(Advancedness[adGiveAway] <= Advancedness[ad] + (advanceValue[ad] >> 8) + Compromise ||
|
|
(adGiveAway == adScience && nation == data->TheologyPartner)) &&
|
|
(result < 0 ||
|
|
(((Advancedness[adGiveAway] + Compromise >= Advancedness[ad]) || ad == adScience) &&
|
|
advanceValue[ad] > advanceValue[result]) ||
|
|
(result != adScience && Advancedness[adGiveAway] + Compromise < Advancedness[result] &&
|
|
Advancedness[ad] < Advancedness[result])) &&
|
|
(ad != adTheRepublic || (data->BehaviorFlags & bGender) == bFemale ||
|
|
ro->EnemyReport[nation]->Tech[adTheology] >= tsSeen))
|
|
result = ad;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void AI::findBestTrade(int nation, int &adWanted, int &adGiveAway)
|
|
{
|
|
adWanted = -1;
|
|
adGiveAway = -1;
|
|
for (int ead = 0; ead <= nAdv - 5; ++ead) { // no future techs
|
|
if (advanceValue[ead] >= 0x100 && ro->Tech[ead] < tsSeen && ead != ro->ResearchTech &&
|
|
ro->EnemyReport[nation]->Tech[ead] >= tsApplicable &&
|
|
(adWanted < 0 || advanceValue[ead] > advanceValue[adWanted])) {
|
|
int adTestGiveAway = -1;
|
|
for (int i = 0; i < nRequestedTechs; ++i)
|
|
if (data->RequestedTechs[i] >= 0 && (data->RequestedTechs[i] & 0xFFFF) == (nation << 8) + ead)
|
|
adTestGiveAway = -2; // already requested before
|
|
if (adTestGiveAway == -1) {
|
|
for (int ad = 0; ad <= nAdv - 5; ++ad) { // no future techs
|
|
if (ro->Tech[ad] >= tsApplicable && ad != ro->EnemyReport[nation]->ResearchTech &&
|
|
ro->EnemyReport[nation]->Tech[ad] < tsSeen &&
|
|
(Advancedness[ad] + Compromise >= Advancedness[ead] || ead == adScience) &&
|
|
Advancedness[ad] <= Advancedness[ead] + (advanceValue[ead] >> 8) + Compromise &&
|
|
(adTestGiveAway < 0 || Advancedness[ad] < Advancedness[adTestGiveAway]))
|
|
adTestGiveAway = ad;
|
|
}
|
|
if (adTestGiveAway >= 0) {
|
|
adWanted = ead;
|
|
adGiveAway = adTestGiveAway;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
bool AI::wantNegotiation(int nation, NegoTime negoTime)
|
|
{
|
|
if ((data->BehaviorFlags & bBarbarina) == bBarbarina)
|
|
return barbarina_WantNegotiation(nation, negoTime);
|
|
|
|
if (ro->Treaty[nation] < trPeace) {
|
|
if (data->BehaviorFlags & bBarbarina)
|
|
return false;
|
|
int count = 0;
|
|
for (int p1 = 0; p1 < nPl; ++p1)
|
|
if (p1 != me && (ro->Alive & (1 << p1)) && ro->Treaty[p1] >= trPeace)
|
|
++count;
|
|
if (count >= 3) // enough peace made
|
|
return false;
|
|
}
|
|
|
|
negoCause = AINegoCause::Routine;
|
|
switch (negoTime) {
|
|
case NegoTime::EnemyCalled:
|
|
return true;
|
|
case NegoTime::EndOfTurn: {
|
|
const int suContact = static_cast<int>(Suggestion::Contact);
|
|
const int suPeace = static_cast<int>(Suggestion::Peace);
|
|
const int suFriendly = static_cast<int>(Suggestion::Friendly);
|
|
if (data->RejectTurn[suContact][nation] >= 0 && data->RejectTurn[suContact][nation] + WaitAfterReject >= ro->Turn)
|
|
return false;
|
|
if (ro->Treaty[nation] < trPeace)
|
|
return data->RejectTurn[suPeace][nation] < 0 ||
|
|
data->RejectTurn[suPeace][nation] + WaitAfterReject < ro->Turn;
|
|
if (ro->Treaty[nation] == trPeace)
|
|
return (data->BehaviorFlags & bBarbarina) == 0 &&
|
|
(data->RejectTurn[suFriendly][nation] < 0 ||
|
|
data->RejectTurn[suFriendly][nation] + WaitAfterReject < ro->Turn);
|
|
int adWanted, adGiveAway;
|
|
findBestTrade(nation, adWanted, adGiveAway);
|
|
return adWanted >= 0;
|
|
}
|
|
case NegoTime::BeginOfTurn: {
|
|
const int suContact = static_cast<int>(Suggestion::Contact);
|
|
if (data->RejectTurn[suContact][nation] >= 0 && data->RejectTurn[suContact][nation] + WaitAfterReject >= ro->Turn)
|
|
return false;
|
|
if ((data->BehaviorFlags & bGender) == bMale && barbarina_WantCheckNegotiation(nation)) {
|
|
negoCause = AINegoCause::CheckBarbarina;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
void AI::doNegotiation()
|
|
{
|
|
if (myAction == scDipOffer) {
|
|
if (oppoAction == scDipAccept) { // evaluate accepted offers
|
|
advanceValuesSet = false;
|
|
if (myLastOffer.nDeliver == 1 && myLastOffer.nCost > 0 && myLastOffer.Price[1] == opTech + adTheology)
|
|
data->TheologyPartner = opponent;
|
|
} else { // evaluate rejected offers
|
|
if (myLastOffer.nDeliver + myLastOffer.nCost == 1) {
|
|
if (myLastOffer.Price[0] == static_cast<std::uint32_t>(opTreaty + trPeace))
|
|
data->RejectTurn[static_cast<int>(Suggestion::Peace)][opponent] = static_cast<std::int16_t>(ro->Turn);
|
|
else if (myLastOffer.Price[0] == static_cast<std::uint32_t>(opTreaty + trFriendlyContact))
|
|
data->RejectTurn[static_cast<int>(Suggestion::Friendly)][opponent] =
|
|
static_cast<std::int16_t>(ro->Turn);
|
|
}
|
|
}
|
|
}
|
|
if (oppoAction == scDipBreak) {
|
|
data->RejectTurn[static_cast<int>(Suggestion::Contact)][opponent] = static_cast<std::int16_t>(ro->Turn);
|
|
} else if (oppoAction == scDipCancelTreaty) {
|
|
if (ro->Treaty[opponent] == trNone)
|
|
data->RejectTurn[static_cast<int>(Suggestion::Peace)][opponent] = static_cast<std::int16_t>(ro->Turn);
|
|
else if (ro->Treaty[opponent] == trPeace)
|
|
data->RejectTurn[static_cast<int>(Suggestion::Friendly)][opponent] = static_cast<std::int16_t>(ro->Turn);
|
|
}
|
|
|
|
if ((data->BehaviorFlags & bBarbarina) == bBarbarina) {
|
|
barbarina_DoNegotiation();
|
|
return;
|
|
}
|
|
|
|
if (negoCause == AINegoCause::CheckBarbarina) {
|
|
barbarina_DoCheckNegotiation();
|
|
return;
|
|
}
|
|
|
|
setAdvanceValues(); // in case no turn played after loading this game
|
|
|
|
bool buildFreeOffer = false;
|
|
int adWanted = -1, adGiveAway = -1;
|
|
if (oppoAction == scDipStart || oppoAction == scDipAccept) {
|
|
buildFreeOffer = true;
|
|
} else if (oppoAction == scDipOffer && oppoOffer.nDeliver + oppoOffer.nCost == 0) {
|
|
buildFreeOffer = true;
|
|
} else if (oppoAction == scDipOffer) {
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 && oppoOffer.nDeliver + oppoOffer.nCost == 1 &&
|
|
(oppoOffer.Price[0] & opMask) == static_cast<std::uint32_t>(opTreaty) &&
|
|
static_cast<int>(oppoOffer.Price[0] - opTreaty) > ro->Treaty[opponent] &&
|
|
(static_cast<int>(oppoOffer.Price[0] - opTreaty) < trAlliance || ro->Tech[adScience] >= tsSeen)) {
|
|
myAction = scDipAccept; // accept all treaties
|
|
} else if (ro->Treaty[opponent] >= trPeace && oppoOffer.nDeliver == 1 &&
|
|
(oppoOffer.Price[0] & 0xFFFF0000) == static_cast<std::uint32_t>(opCivilReport + (opponent << 16)) &&
|
|
oppoOffer.nCost == 1 &&
|
|
(oppoOffer.Price[1] & 0xFFFF0000) == static_cast<std::uint32_t>(opCivilReport + (me << 16))) {
|
|
myAction = scDipAccept; // accept exchange of civil reports
|
|
} else if (oppoOffer.nDeliver == 1 && oppoOffer.nCost == 1 && (oppoOffer.Price[1] & opMask) == static_cast<std::uint32_t>(opTech)) {
|
|
// opponent wants tech
|
|
buildFreeOffer = true;
|
|
adGiveAway = static_cast<int>(oppoOffer.Price[1] - opTech);
|
|
if ((oppoOffer.Price[0] & opMask) == static_cast<std::uint32_t>(opTech) && myLastAction == scDipOffer &&
|
|
myLastOffer.nDeliver == 1 && myLastOffer.nCost == 1 && oppoOffer.Price[0] == myLastOffer.Price[1]) {
|
|
// opponent makes counter offer, check whether to accept
|
|
const int adToGet = static_cast<int>(oppoOffer.Price[0] - opTech);
|
|
if (adGiveAway == adTheRepublic && (data->BehaviorFlags & bGender) == bFemale &&
|
|
ro->Tech[adTheology] < tsSeen) {
|
|
if (adToGet == adTheology)
|
|
myAction = scDipAccept;
|
|
} else if (ro->Tech[adGiveAway] >= tsApplicable && ro->Tech[adToGet] < tsSeen &&
|
|
advanceValue[adToGet] > 0 &&
|
|
(Advancedness[adGiveAway] <= Advancedness[adToGet] + (advanceValue[adToGet] >> 8) + Compromise ||
|
|
(adGiveAway == adScience && opponent == data->TheologyPartner))) {
|
|
myAction = scDipAccept;
|
|
}
|
|
} else if ((oppoOffer.Price[0] & opMask) == static_cast<std::uint32_t>(opChoose) ||
|
|
(oppoOffer.Price[0] & opMask) == static_cast<std::uint32_t>(opTech)) {
|
|
// choose price
|
|
const int wanted = mostWanted(opponent, static_cast<int>(oppoOffer.Price[1] - opTech));
|
|
if ((oppoOffer.Price[0] & opMask) == static_cast<std::uint32_t>(opTech) &&
|
|
static_cast<std::uint32_t>(wanted) == oppoOffer.Price[0] - opTech) {
|
|
myAction = scDipAccept; // opponent's offer is already perfect
|
|
} else if (wanted >= 0) { // make improved counter offer
|
|
myOffer.nDeliver = 1;
|
|
myOffer.nCost = 1;
|
|
myOffer.Price[0] = oppoOffer.Price[1];
|
|
myOffer.Price[1] = opTech + wanted;
|
|
myAction = scDipOffer;
|
|
buildFreeOffer = false;
|
|
}
|
|
}
|
|
if (myAction == scDipAccept)
|
|
buildFreeOffer = false;
|
|
} else {
|
|
buildFreeOffer = true;
|
|
}
|
|
}
|
|
if (myAction == scDipAccept && oppoAction == scDipOffer) {
|
|
advanceValuesSet = false;
|
|
if (oppoOffer.nDeliver > 0 && oppoOffer.Price[0] == opTech + adTheology)
|
|
data->TheologyPartner = opponent;
|
|
}
|
|
|
|
if (buildFreeOffer) {
|
|
const int suPeace = static_cast<int>(Suggestion::Peace);
|
|
const int suFriendly = static_cast<int>(Suggestion::Friendly);
|
|
if ((data->BehaviorFlags & bBarbarina) == 0 && ro->Treaty[opponent] < trPeace &&
|
|
(data->RejectTurn[suPeace][opponent] < 0 || data->RejectTurn[suPeace][opponent] + WaitAfterReject < ro->Turn)) {
|
|
myOffer.nDeliver = 1;
|
|
myOffer.nCost = 0;
|
|
myOffer.Price[0] = opTreaty + trPeace;
|
|
myAction = scDipOffer;
|
|
} else if ((data->BehaviorFlags & bBarbarina) == 0 && ro->Treaty[opponent] == trPeace &&
|
|
(data->RejectTurn[suFriendly][opponent] < 0 ||
|
|
data->RejectTurn[suFriendly][opponent] + WaitAfterReject < ro->Turn)) {
|
|
myOffer.nDeliver = 1;
|
|
myOffer.nCost = 0;
|
|
myOffer.Price[0] = opTreaty + trFriendlyContact;
|
|
myAction = scDipOffer;
|
|
} else {
|
|
findBestTrade(opponent, adWanted, adGiveAway);
|
|
if (adWanted >= 0) {
|
|
myOffer.nDeliver = 1;
|
|
myOffer.nCost = 1;
|
|
myOffer.Price[0] = opTech + adGiveAway;
|
|
myOffer.Price[1] = opTech + adWanted;
|
|
myAction = scDipOffer;
|
|
int slot = 0;
|
|
for (int i = 0; i < nRequestedTechs; ++i) {
|
|
if (data->RequestedTechs[i] < 0) {
|
|
slot = i;
|
|
break;
|
|
}
|
|
if (i == 0 || (data->RequestedTechs[i] >> 16) < (data->RequestedTechs[slot] >> 16))
|
|
slot = i; // find most outdated entry
|
|
}
|
|
data->RequestedTechs[slot] = (ro->Turn << 16) + (opponent << 8) + adWanted;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
} // namespace Cevo
|