Fixed AI trade route evaluation to use correct speculated homecity instead of unit's
[freeciv.git] / doc / README.AI
blob7dbcc38385a7ba351ad3c53d9ea80dca21434cc9
1 ==============
2 THE FREECIV AI
3 ==============
5 This document is about freeciv's default AI. Freeciv supports also
6 using custom AI modules, though at the time of writing none exist.
7 See README.AI_modules about support of custom modules.
10 CONTENTS
11 ========
12 Introduction
13 Contacting the current AI developers
14 Long-term AI development goals
15 Want calculations
16 Amortize
17 Estimation of profit from a military operation
18 Selecting military units
19 Ferry system
20 Diplomacy
21 Difficulty levels
22 Things that needs to be fixed
23 Idea space
26 INTRODUCTION 
27 ============ 
29 The Freeciv AI is widely recognized as being as good as or better
30 military-wise as the AI of certain other games it is natural to compare
31 it with.  It is, however, still too easy for experienced players.
33 The code base used to be in a bad shape but it has gotten a lot
34 better.  The reason for this is that the developer (Syela) who in a
35 few months put together a working AI had suddenly disappeared.  His
36 bright ideas could only be matched by his inability to name variables
37 and to comment the code.  Subsequent AI developers were not brave (or
38 stupid?) enough to start from scratch, taking instead a small bite
39 here and there, trying hard not to break much, to understand Syela's
40 original design and only then to throw it away.  Or perfect it.
42 Code that implements the AI is divided between ai/ and server/advisors.
43 Latter is used also by human players for such automatic helpers
44 as auto-settlers and auto-explorers.
47 CONTACTING THE CURRENT AI DEVELOPERS
48 ====================================
50 AI development used to have its own mailing list, freeciv-ai@freeciv.org.
51 Go to 
53   http://www.freeciv.org/wiki/Community_Forums
55 to read the archives.
57 Currently freeciv-dev@gna.org is used for all discussion about freeciv
58 development.
61 LONG-TERM AI DEVELOPMENT GOALS
62 ==============================
64 The long-term goals for Freeciv AI development are
65  -> to create a challenging and fun AI for human players to defeat
66  -> to create an AI that can handle all the rules possibilities that
67     Freeciv can offer
70 WANT CALCULATIONS
71 =================
73 Build calculations are expressed through a structure called adv_choice. 
74 This has a variable called "want", which determines how much the AI 
75 wants whatever item is pointed to by choice->type. choice->want is
77    -199   get_a_boat
78    < 0    an error
79    == 0   no want, nothing to do
80    <= 100 normal want
81     > 100 critical want, used to requisition emergency needs
82     > ??? probably an error (1024 is a reasonable upper bound)
83     > 200 Frequently used as a cap. When want exceeds this value,
84           it is reduced to a lower number.
86 These are ideal numbers, your mileage while travelling through the 
87 code may vary considerably.  Technology and diplomats, in particular, 
88 seem to violate these standards.
91 AMORTIZE
92 ========
94 Hard fact:
95 amortize(benefit, delay) returns benefit * ((MORT - 1)/MORT)^delay
96 (where "^" == "to the power of")
98 Speculation:
99 What is better, to receive 10$ annually starting in 5 years from now
100 or 5$ annually starting from this year?  How can you take inflation
101 into account?  The function amortize is meant to help you answer these
102 questions.  To achieve this, it rescales the future benefit in terms of
103 todays money.
105 Suppose we have a constant rate of inflation, x percent.  Then in five
106 years time 10$ will buy as much as 10*(100/(100+x))^5 will buy today.
107 Denoting 100/(100+x) by q we get the general formula, N dollars Y
108 years from now will be worth N*q^Y in todays money.  If we will
109 receive N every year starting Y years from now, the total amount
110 receivable (in todays money) is N*q^Y / (1-q) --- this is the sum of
111 infinite geometric series.  This is exactly the operation that
112 amortize performs, the multiplication by some q < 1 raised to power Y.
113 Note that the factor 1/(1-q) does not depend on the parameters N and Y
114 and can be ignored.  The connection between MORT constant and the
115 inflation rate x is given by
116     (MORT - 1) / MORT = q = 100 / (100 + x).
117 Thus the current value of MORT = 24 corresponds to the inflation rate
118 (or the rate of expansion of your civ) of 4.3%
120 Most likely this explanation is not what the authors of amortize() had
121 in mind, but the basic idea is correct: the value of the payoff decays
122 exponentially with the delay.
124 The version of amortize used in the military code (military_amortize())
125 remains a complete mystery.
128 ESTIMATION OF PROFIT FROM A MILITARY OPERATION
129 ==============================================
131 This estimation is implemented by kill_desire function (which isn't
132 perfect: multi-victim part is flawed) plus some corrections.  In
133 general,
134         Want = Operation_Profit * Amortization_Factor
135 where 
137 * Amortization_Factor is completely beyond me (but it's a function of the
138 estimated time length of the operation).
140 * Operation_Profit = Battle_Profit - Maintenance
142 where
144 * Maintenance 
145   = (Support + Unhappiness_Compensation) * Operation_Time 
146   (here unhappiness is from military unit being away from home
147    and Support is the number of shields spent on supporting this unit 
148    per turn )
150 * Battle_Profit
151   = Shields_Lost_By_Enemy * Probability_To_Win 
152     - Shields_Lost_By_Us * Probability_To_Lose
154 That is Battle_Profit is a probabilistic average.  It answer the
155 question "how much better off, on average, we would be from attacking
156 this enemy unit?"
159 SELECTING MILITARY UNITS
160 ========================
162 The code dealing with choosing military units to be built and targets
163 for them is especially messy.  Here is what we've managed to decipher.
165 Military units are requested in military_advisor_choose_build
166 function.  It first considers the defensive units and then ventures
167 into selection of attackers (if home is safe).  There are 2
168 possibilities here: we just build a new attacker or we already have an
169 attacker which was forced, for some reason, to defend.  In the second
170 case it's easy: we calculate how good the existing attacker is and if
171 it's good, we build a defender to free it up.
173 Building a brand-new attacker is more complicated.  Firstly,
174 ai_choose_attacker_* functions are charged to find the first
175 approximation to the best attacker that can be built here.  This
176 prototype attacker is selected using very simple attack_power * speed
177 formula.  Then (already in kill_something_with) we search for targets
178 for the prototype attacker (using find_something_to_kill).  Having
179 found a target, we do the last refinement by calling
180 process_attacker_want to look for the best attacker type to take out
181 the target.  This type will be our attacker choice.  Note that the
182 function process_attacker_want has side-effects wrt the tech selection. 
184 Here is an example:
186 First ai_choose_attacker_land selects a Dragoon because it's strong
187 and fast.  Then find_something_to_kill finds a victim for the
188 (virtual) Dragoon, an enemy Riflemen standing right next to the town.
189 Then process_attacker_want figures out that since the enemy is right
190 beside us, it can be taken out easier using an Artillery.  It also
191 figures that a Howitzer would do this job even better, so bumps up our
192 desire for Robotics.
194 This is the idea, anyway.  In practice, it is more complicated and
195 probably less efficient.
198 FERRY SYSTEM
199 ============
201 The ferry (i.e. boats transporting land units) system of Freeciv is
202 probably better described by statistical mechanics than by logic.
203 Both ferries and prospective passenger (PP) move around in what looks
204 like a random fashion, trying to get closer to each other.  On
205 average, they succeed.  This behaviour has good reasons behind it, is
206 hell to debug but means that small bugs don't affect overall picture
207 visibly (and stay unfixed as a result).
209 Each turn both boats and PPs forget all about prior arrangements
210 (unless the passenger is actually _in_ the boat).  Then each will look
211 for the closest partner, exchange cards and head towards it.  This is
212 done in a loop which goes through all units in essentially random
213 order.
215 Because most units recalculate their destination every turn, ignoring
216 prior arrangements is the only good strategy -- it means that a boat
217 will not rely on the PP to notify it when it's not needed anymore.
218 This is not very effective but can only be changed when the PPs behave
219 more responsibly.  See diplomat code for more responsible behaviour --
220 they try to check if the old target is still good before trying to
221 find a new one.
223 When a boat has a passenger, it's a different story.  The boat doesn't
224 do any calculations, instead one of the passengers is given full
225 control and it is the passenger who drives the boat.
227 Here are the main data fields used by the system.
228 Value of ai.ferry in the passenger unit is:
229   FERRY_NONE : means that the unit has no need of a ferry
230   FERRY_WANTED : means that the unit wants a ferry
231   >0 : id of it's ferry
232 Value of ai.passenger in the ferry unit can be either of:
233   FERRY_AVAILABLE : means that the unit is a ferry and is available
234   >0 : id of it's passenger
236 When boat-building code stabilizes, it can be seen how many free boats
237 there are, on average, per PP.  If there are more boats than PPs, it
238 makes sense that only PPs should look for boats.  If boats are few,
239 they should be the ones choosing.  This can be done both dynamically
240 (both possibilities are coded and the appropriate is chosen every
241 turn) and statically (after much testing only one system remains).
242 Now they exist in parallel, although developed to a different degree.
245 DIPLOMACY
246 =========
248 The AI's diplomatic behaviour is current only regulated by the 
249 'diplomacy' server setting.
251 AI proposes cease-fire on first contact.
253 AI is not very trusting for NEUTRAL and PEACE modes, but once it hits 
254 ALLIANCE, this changes completely, and it will happily hand over 
255 any tech and maps it has to you.  The only thing that will make the AI 
256 attack you then is if you build a spaceship.
258 For people who want to hack at this part of the AI code, please note
259  * pplayers_at_war(p1,p2) returns FALSE if p1==p2
260  * pplayers_non_attack(p1,p2) returns FALSE if p1==p2
261  * pplayers_allied(p1,p2) returns TRUE if p1==p2 
262  * pplayer_has_embassy(p1,p2) returns TRUE if p1==p2
263 i.e. we do not ever consider a player to be at war with himself, we
264 never consider a player to have any kind of non-attack treaty with
265 himself, and we always consider a player to have an alliance with
266 himself. 
268 The introduction of diplomacy is fraught with many problems.  One is
269 that it usually gains only human players, not AI players, since humans
270 are so much smarter and know how to exploit diplomacy, while for AIs
271 they mostly only add constraints on what it can do.  Another is that it
272 can be very difficult to write diplomacy that is useful for and not in
273 the way of modpacks.  Which means diplomacy either has to be optional,
274 or have fine-grained controls on who can do what diplomatic deals to
275 whom, set from rulesets.  The latter is not yet well implemented.
278 DIFFICULTY LEVELS
279 =================
281 There are currently seven difficulty levels: 'handicapped, 'novice',
282 'easy', 'normal', 'hard', 'cheating', and 'experimental'.
283 The 'hard' level is no-holds-barred. 'Cheating' is the same
284 except that it has ruleset defined extra bonuses, while 'normal'
285 has a number of handicaps. In 'easy', the AI also does random stupid
286 things through the ai_fuzzy function. The 'experimental' level is
287 only for coding - you can gate new code
288 with the H_EXPERIMENTAL handicap and test 'experimental' level
289 AIs against 'hard' level AIs. In 'novice' the AI researches slower
290 than normal players.
292 Other handicaps used are:
293   H_DIPLOMAT     Can't build offensive diplomats
294   H_LIMITEDHUTS  Can get only 25 gold and barbs from huts
295   H_DEFENSIVE    Build defensive buildings without calculating need
296   H_RATES        Can't set its rates beyond government limits
297   H_TARGETS      Can't target anything it doesn't know exists
298   H_HUTS         Doesn't know which unseen tiles have huts on them
299   H_FOG          Can't see through fog of war
300   H_NOPLANES     Doesn't build air units
301   H_MAP          Only knows map_is_known tiles
302   H_DIPLOMACY    Not very good at diplomacy
303   H_REVOLUTION   Cannot skip anarchy
304   H_EXPANSION    Don't like being much larger than human
305   H_DANGER       Always thinks its city is in danger
307 For an up-to-date list of all handicaps and their use for each
308 difficulty level see ./ai/handicaps.h.
311 THINGS THAT NEED TO BE FIXED
312 ============================
314 * Cities don't realize units are on their way to defend it.
315 * AI builds cities without regard to danger at that location.
316 * AI won't build cross-country roads outside of city radii.
317 * Locally_zero_minimap is not implemented when wilderness tiles 
318 change.
319 * If no path to chosen victim is found, new victim should be chosen.
320 * Emergencies in two cities at once aren't handled properly.
321 * Explorers will not use ferryboats to get to new lands to explore.
322 The AI will also not build units to explore new islands, leaving huts alone.
323 * AI sometimes believes that wasting a horde of weak military units to
324 kill one enemy is profitable (PR#1340)
325 * Stop building shore defense in landlocked cities with a pond adjacent.
326 * Fix the AI valuation of supermarket. (It currently never builds it).
327 See farmland_food() and ai_eval_buildings() in advdomestic.c
328 * Teach the AI to coordinate the units in an attack (ok, this one is a bit
329 big...)
332 IDEA SPACE
333 ==========
335 * Friendly cities can be used as beachheads
336 * Assess_danger should acknowledge positive feedback between multiple 
337 attackers
338 * It would be nice for bodyguard and charge to meet en-route more 
339 elegantly.
340 * struct choice should have a priority indicator in it.  This will
341 reduce the number of "special" want values and remove the necessity to
342 have want capped, thus reducing confusion.