1 /*
2  * Seven Kingdoms: Ancient Adversaries
3  *
4  * Copyright 1997,1998 Enlight Software Ltd.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20 
21 //Filename    : OTOWNAI.CPP
22 //Description : Object Town AI
23 
24 #include <OWORLD.h>
25 #include <OUNIT.h>
26 #include <OCONFIG.h>
27 #include <OSITE.h>
28 #include <ONEWS.h>
29 #include <OTECHRES.h>
30 #include <OWALLRES.h>
31 #include <ORACERES.h>
32 #include <OGODRES.h>
33 #include <OSPY.h>
34 #include <OTOWN.h>
35 #include <ONATION.h>
36 #include <OINFO.h>
37 #include <OFIRMALL.h>
38 #include <OLOG.h>
39 
40 
41 //--------- Begin of function Town::process_ai ----------//
42 //
process_ai()43 void Town::process_ai()
44 {
45 	Nation* ownNation = nation_array[nation_recno];
46 
47 #if defined(DEBUG) && defined(ENABLE_LOG)
48 	String logStr;
49 
50 	logStr = "begin Town::process_ai, town_recno=";
51 	logStr += town_recno;
52 	logStr += " nation_recno=";
53 	logStr += nation_recno;
54 	LOG_MSG(logStr);
55 #endif
56 
57 	//---- think about cancelling the base town status ----//
58 
59 	if( info.game_date%30==town_recno%30 )
60 	{
61 		LOG_MSG(" update_base_town_status");
62 		update_base_town_status();
63 		LOG_MSG(misc.get_random_seed());
64 	}
65 
66 	//------ think about granting villagers ---//
67 
68 	if( info.game_date%30==town_recno%30 )
69 	{
70 		LOG_MSG(" think_reward");
71 		think_reward();
72 		LOG_MSG(misc.get_random_seed());
73 	}
74 
75 	//----- if this town should migrate now -----//
76 
77 	if( should_ai_migrate() )
78 	{
79 		if( info.game_date%30==town_recno%30 )
80 		{
81 			LOG_MSG(" think_ai_migrate");
82 			think_ai_migrate();
83 			LOG_MSG(misc.get_random_seed());
84 		}
85 
86 		return;		// don't do anything else if the town is about to migrate
87 	}
88 
89 	//------ think about building camps first -------//
90 
91 	if( info.game_date%30==town_recno%30 && !no_neighbor_space &&		// if there is no space in the neighbor area for building a new firm.
92 		 population > 1 )
93 	{
94 		LOG_MSG(" think_build_camp");
95 		if( think_build_camp() )
96 		{
97 			LOG_MSG(misc.get_random_seed());
98 			return;
99 		}
100 		LOG_MSG(misc.get_random_seed());
101 	}
102 
103 	//----- the following are base town only functions ----//
104 
105 	if( !is_base_town )
106 		return;
107 
108 	//------ think about collecting tax ---//
109 
110 	if( info.game_date%30==(town_recno+15)%30 )
111 	{
112 		LOG_MSG("think_collect_tax");
113 		think_collect_tax();
114 		LOG_MSG(misc.get_random_seed());
115 	}
116 
117 	//---- think about scouting in an unexplored map ----//
118 
119 	if( info.game_date%30==(town_recno+20)%30  )
120 	{
121 		think_scout();
122 	}
123 
124 	//---- think about splitting the town ---//
125 
126 	if( info.game_date%30==town_recno%30 )
127 	{
128 		LOG_MSG("think_move_between_town");
129 		think_move_between_town();
130 		LOG_MSG(misc.get_random_seed() );
131 		LOG_MSG("think_split_town");
132 		think_split_town();
133 		LOG_MSG(misc.get_random_seed() );
134 	}
135 
136 	//---- think about attacking firms/units nearby ---//
137 
138 	if( info.game_date%30==town_recno%30 )
139 	{
140 		LOG_MSG(" think_attack_nearby_enemy");
141 		if( think_attack_nearby_enemy() )
142 		{
143 			LOG_MSG(misc.get_random_seed());
144 			return;
145 		}
146 		LOG_MSG(misc.get_random_seed());
147 
148 		LOG_MSG(" think_attack_linked_enemy");
149 		if( think_attack_linked_enemy() )
150 		{
151 			LOG_MSG(misc.get_random_seed());
152 			return;
153 		}
154 		LOG_MSG(misc.get_random_seed());
155 	}
156 
157 	//---- think about capturing linked enemy firms ----//
158 
159 	if( info.game_date%60==town_recno%60 )
160 	{
161 		LOG_MSG(" think_capture_linked_firm");
162 		think_capture_linked_firm();
163 		LOG_MSG(misc.get_random_seed());
164 	}
165 
166 	//---- think about capturing enemy towns ----//
167 
168 	if( info.game_date%120==town_recno%120 )
169 	{
170 		LOG_MSG(" think_capture_enemy_town");
171 		think_capture_enemy_town();
172 		LOG_MSG(misc.get_random_seed());
173 	}
174 
175 	//---- think about using spies on enemies ----//
176 
177 	if( info.game_date%60==(town_recno+10)%60 )
178 	{
179 		LOG_MSG(" think_spying_town");
180 		if( think_spying_town() )
181 		{
182 			LOG_MSG(misc.get_random_seed());
183 			return;
184 		}
185 	}
186 
187 	//---- think about anti-spies activities ----//
188 
189 	if( info.game_date%60==(town_recno+20)%60 )
190 	{
191 		LOG_MSG(" think_counter_spy");
192 		if( think_counter_spy() )
193 		{
194 			LOG_MSG(misc.get_random_seed());
195 			return;
196 		}
197 	}
198 
199 	//--- think about setting up firms next to this town ---//
200 
201 	if( info.game_date%30==town_recno%30 && !no_neighbor_space &&		// if there is no space in the neighbor area for building a new firm.
202 		 population >= 5 )
203 	{
204 		LOG_MSG(" think_build_market");
205 		if( think_build_market() )
206 		{
207 			LOG_MSG(misc.get_random_seed());
208 			return;
209 		}
210 		LOG_MSG(misc.get_random_seed());
211 
212 		//--- the following functions will only be called when the nation has at least a mine ---//
213 
214 		if( site_array.untapped_raw_count > 0 &&
215 			 ownNation->ai_mine_count==0 &&		// don't build other structures if there are untapped raw sites and our nation still doesn't have any
216 			 ownNation->true_profit_365days() < 0 )
217 		{
218 			return;
219 		}
220 
221 		//---- only build the following if we have enough food ----//
222 
223       if( ownNation->ai_has_enough_food() )
224 		{
225 			LOG_MSG(" think_build_research");
226 			if( think_build_research() )
227 			{
228 				LOG_MSG(misc.get_random_seed());
229 				return;
230 			}
231 			LOG_MSG(misc.get_random_seed());
232 
233 			LOG_MSG(" think_build_war_factory");
234 			if( think_build_war_factory() )
235 			{
236 				LOG_MSG(misc.get_random_seed());
237 				return;
238 			}
239 			LOG_MSG(misc.get_random_seed());
240 
241 			LOG_MSG(" think_build_base");
242 			if( think_build_base() )
243 			{
244 				LOG_MSG(misc.get_random_seed());
245 				return;
246 			}
247 			LOG_MSG(misc.get_random_seed());
248 		}
249 
250 		//-------- think build inn ---------//
251 
252 		LOG_MSG(" think_build_inn");
253 		think_build_inn();
254 		LOG_MSG(misc.get_random_seed());
255 	}
256 }
257 //--------- End of function Town::process_ai ----------//
258 
259 
260 //--------- Begin of function Town::think_defense ----------//
261 //
think_defense()262 void Town::think_defense()
263 {
264 	int enemyUnitRecno = detect_enemy(3);		// only when 3 units are detected, we consider them as enemy
265 
266 	if( !enemyUnitRecno )
267 		return;
268 
269 	Unit* enemyUnit = unit_array[enemyUnitRecno];
270 
271 	int enemyXLoc = enemyUnit->cur_x_loc();
272 	int enemyYLoc = enemyUnit->cur_y_loc();
273 
274 	//----- get our unit that is closet to it to attack it -------//
275 
276 	int   i, closestUnitRecno=0, curDis, minDis=0x7FFF;
277 	Unit* unitPtr;
278 
279 	for( i=unit_array.size() ; i>0 ; i-- )
280 	{
281 		if( unit_array.is_deleted(i) )
282 			continue;
283 
284 		unitPtr = unit_array[i];
285 
286 		if( unitPtr->nation_recno == nation_recno )
287 		{
288 			curDis = MAX( abs(unitPtr->cur_x_loc()-enemyXLoc), abs(unitPtr->cur_y_loc()-enemyYLoc) );
289 
290 			if( curDis < minDis )
291 			{
292 				minDis = curDis;
293 				closestUnitRecno = i;
294 			}
295 		}
296 	}
297 
298 	//-------- attack the enemy now ----------//
299 
300 	if( closestUnitRecno )
301 		unit_array[closestUnitRecno]->attack_unit(enemyUnit->sprite_recno);
302 }
303 //--------- End of function Town::think_defense ----------//
304 
305 
306 //--------- Begin of function Town::detect_enemy ----------//
307 //
308 // Detect if there is any enemy in the town. (within the city
309 // wall area.)
310 //
311 // <int> alertNum - only alert when this number of units are detected.
312 //
detect_enemy(int alertNum)313 int Town::detect_enemy(int alertNum)
314 {
315 	//------ check if any enemies have entered in the city -----//
316 
317 	int xLoc1 = MAX(0, loc_x1-WALL_SPACE_LOC);
318 	int yLoc1 = MAX(0, loc_y1-WALL_SPACE_LOC);
319 	int xLoc2 = MIN(MAX_WORLD_X_LOC-1, loc_x2+WALL_SPACE_LOC);
320 	int yLoc2 = MIN(MAX_WORLD_Y_LOC-1, loc_y2+WALL_SPACE_LOC);
321 	int xLoc, yLoc, unitRecno;
322 	int enemyCount=0;
323 	Location* locPtr;
324 	Unit* unitPtr;
325 
326 	for( yLoc=yLoc1 ; yLoc<=yLoc2 ; yLoc++ )
327 	{
328 		locPtr = world.get_loc(xLoc1, yLoc);
329 
330 		for( xLoc=xLoc1 ; xLoc<=xLoc2 ; xLoc++, locPtr++ )
331 		{
332 			if( locPtr->has_unit(UNIT_LAND) )
333 			{
334 				unitRecno = locPtr->unit_recno(UNIT_LAND);
335 
336 				//------- if any enemy detected -------//
337 
338 				unitPtr = unit_array[unitRecno];
339 
340 				if( unitPtr->nation_recno != nation_recno && unitPtr->nation_recno > 0 )
341 				{
342 					if( ++enemyCount >= alertNum )
343 						return unitRecno;
344 				}
345 			}
346 		}
347 	}
348 
349 	return 0;
350 }
351 //--------- End of function Town::detect_enemy ----------//
352 
353 
354 //------- Begin of function Town::think_build_firm --------//
355 //
356 // Think about building a specific type of firm next to this town.
357 //
358 // <int> firmId  - id. of the firm to be built.
359 // <int> maxFirm - MAX. no. of firm of this type to be built next to this town.
360 //
think_build_firm(int firmId,int maxFirm)361 int Town::think_build_firm(int firmId, int maxFirm)
362 {
363 	Nation* nationPtr = nation_array[nation_recno];
364 
365 	//--- check whether the AI can build a new firm next this firm ---//
366 
367 	if( !nationPtr->can_ai_build(firmId) )
368 		return 0;
369 
370 	//-- only build one market place next to this town, check if there is any existing one --//
371 
372 	Firm* firmPtr;
373 	int 	firmCount=0;
374 
375 	for(int i=0; i<linked_firm_count; i++)
376 	{
377 		err_when(!linked_firm_array[i] || firm_array.is_deleted(linked_firm_array[i]));
378 
379 		firmPtr = firm_array[linked_firm_array[i]];
380 
381 		//---- if there is one firm of this type near the town already ----//
382 
383 		if( firmPtr->firm_id == firmId &&
384 			 firmPtr->nation_recno == nation_recno )
385 		{
386 			if( ++firmCount >= maxFirm )
387 				return 0;
388 		}
389 	}
390 
391 	//------ queue building a new firm -------//
392 
393 	return ai_build_neighbor_firm(firmId);
394 }
395 //-------- End of function Town::think_build_firm ---------//
396 
397 
398 //------- Begin of function Town::think_collect_tax --------//
399 //
400 // Think about collecting tax.
401 //
think_collect_tax()402 void Town::think_collect_tax()
403 {
404 	if( !has_linked_own_camp )
405 		return;
406 
407 	if( should_ai_migrate() )		// if the town should migrate, do collect tax, otherwise the loyalty will be too low for mobilizing the peasants.
408 		return;
409 
410 	if( accumulated_collect_tax_penalty > 0 )
411 		return;
412 
413 	//--- collect tax if the loyalty of all the races >= minLoyalty (55-85) ---//
414 
415 	int yearProfit = (int) nation_array[nation_recno]->profit_365days();
416 
417 	int minLoyalty = 55 + 30 * nation_array[nation_recno]->pref_loyalty_concern / 100;
418 
419 	if( yearProfit < 0 )								// we are losing money now
420 		minLoyalty -= (-yearProfit) / 100;		// more aggressive in collecting tax if we are losing a lot of money
421 
422 	minLoyalty = MAX( 55, minLoyalty );
423 
424 	//---------------------------------------------//
425 
426 	int achievableLoyalty = average_target_loyalty()-10;		// -10 because it's an average, -10 will be safer
427 
428 	if( achievableLoyalty > minLoyalty )		// if the achievable loyalty is higher, then use it
429 		minLoyalty = achievableLoyalty;
430 
431 	if( average_loyalty() < minLoyalty )
432 		return;
433 
434 	//---------- collect tax now ----------//
435 
436 	collect_tax( COMMAND_AI );
437 }
438 //-------- End of function Town::think_collect_tax ---------//
439 
440 
441 //------- Begin of function Town::think_reward --------//
442 //
443 // Think about granting the villagers.
444 //
think_reward()445 void Town::think_reward()
446 {
447 	if( !has_linked_own_camp )
448 		return;
449 
450 	if( accumulated_reward_penalty > 0 )
451 		return;
452 
453 	//---- if accumulated_reward_penalty>0, don't grant unless the villagers are near the rebel level ----//
454 
455 	Nation* ownNation = nation_array[nation_recno];
456 	int averageLoyalty = average_loyalty();
457 
458 	if( averageLoyalty < REBEL_LOYALTY + 5 + ownNation->pref_loyalty_concern/10 )		// 35 to 45
459 	{
460 		int importanceRating;
461 
462 		if( averageLoyalty < REBEL_LOYALTY+5 )
463 			importanceRating = 40+population;
464 		else
465 			importanceRating = population;
466 
467 		if( ownNation->ai_should_spend(importanceRating) )
468 			reward( COMMAND_AI );
469 	}
470 }
471 //-------- End of function Town::think_reward ---------//
472 
473 
474 //------- Begin of function Town::think_ai_migrate --------//
475 //
476 // Think about migrating to another town.
477 //
think_ai_migrate()478 int Town::think_ai_migrate()
479 {
480 	if( info.game_date < setup_date+90 )		// don't move if this town has just been set up for less than 90 days. It may be a town set up by think_split_town()
481 		return 0;
482 
483 	Nation* nationPtr = nation_array[nation_recno];
484 
485 	//-- the higher the loyalty, the higher the chance all the unit can be migrated --//
486 
487 	int averageLoyalty = average_loyalty();
488 	int minMigrateLoyalty = 35 + nationPtr->pref_loyalty_concern/10;		// 35 to 45
489 
490 	if( averageLoyalty < minMigrateLoyalty )
491 	{
492 		//-- if the total population is low (we need people) and the cash is high (we have money), then grant to increase loyalty for migration --//
493 
494 		if( accumulated_reward_penalty==0 &&
495 			 average_target_loyalty() < minMigrateLoyalty+5 )		// if the average target loyalty is also lower than
496 		{
497 			if( nationPtr->ai_should_spend( 20+nationPtr->pref_territorial_cohesiveness/2 ) )		// 20 to 70
498 				reward( COMMAND_AI );
499 		}
500 
501 		if( average_loyalty() < minMigrateLoyalty )
502 			return 0;
503 	}
504 
505 	if( !should_ai_migrate() )
506 		return 0;
507 
508 	//------ think about which town to migrate to ------//
509 
510 	int bestTownRecno = think_ai_migrate_to_town();
511 
512 	if( !bestTownRecno )
513 		return 0;
514 
515 	//--- check if there are already units currently migrating to the destination town ---//
516 
517 	Town* destTownPtr = town_array[bestTownRecno];
518 
519 	if( nationPtr->is_action_exist( destTownPtr->loc_x1, destTownPtr->loc_y1,
520 		 loc_x1, loc_y1, ACTION_AI_SETTLE_TO_OTHER_TOWN, 0, 0, 1 ) )		// last 1-check duplication on the destination town only
521 	{
522 		return 0;
523 	}
524 
525 	//--------- queue for migration now ---------//
526 
527 	int migrateCount = (average_loyalty() - MIN_RECRUIT_LOYALTY) / 5;
528 
529 	migrateCount = MIN( migrateCount, jobless_population );
530 
531 	if( migrateCount <= 0 )
532 		return 0;
533 
534 	nationPtr->add_action( destTownPtr->loc_x1, destTownPtr->loc_y1,
535 		 loc_x1, loc_y1, ACTION_AI_SETTLE_TO_OTHER_TOWN, 0, migrateCount);
536 
537 	return 1;
538 }
539 //-------- End of function Town::think_ai_migrate ---------//
540 
541 
542 //------- Begin of function Town::think_ai_migrate_to_town --------//
543 //
544 // Think about the town to migrate to.
545 //
think_ai_migrate_to_town()546 int Town::think_ai_migrate_to_town()
547 {
548 	//------ think about which town to migrate to ------//
549 
550 	Nation* nationPtr = nation_array[nation_recno];
551 	int 	 curRating, bestRating=0, bestTownRecno=0;
552 	short  *aiTownPtr = nationPtr->ai_town_array;
553 	int	 majorityRace = majority_race();
554 	Town	 *townPtr;
555 
556 	for(int i=0; i<nationPtr->ai_town_count; i++, aiTownPtr++)
557 	{
558 		if( town_recno == *aiTownPtr )
559 			continue;
560 
561 		townPtr = town_array[*aiTownPtr];
562 
563 		err_when( townPtr->nation_recno != nation_recno );
564 
565 		if( !townPtr->is_base_town )		// only migrate to base towns
566 			continue;
567 
568 		if( townPtr->region_id != region_id )
569 			continue;
570 
571 		if( population > MAX_TOWN_POPULATION-townPtr->population )		// if the town does not have enough space for the migration
572 			continue;
573 
574 		//--------- compare the ratings ---------//
575 
576 		curRating = 1000 * townPtr->race_pop_array[majorityRace-1] / townPtr->population;	// *1000 so that this will have a much bigger weight than the distance rating
577 
578 		curRating += world.distance_rating( center_x, center_y, townPtr->center_x, townPtr->center_y );
579 
580 		if( curRating > bestRating )
581 		{
582 			//--- if there is a considerable population of this race, then must migrate to a town with the same race ---//
583 
584 			if( race_pop_array[majorityRace-1] >= 6 )
585 			{
586 				if( townPtr->majority_race() != majorityRace )				// must be commented out otherwise low population town will never be optimized
587 					continue;
588 			}
589 
590 			bestRating   = curRating;
591 			bestTownRecno = townPtr->town_recno;
592 		}
593 	}
594 
595 	return bestTownRecno;
596 }
597 //-------- End of function Town::think_ai_migrate_to_town ---------//
598 
599 
600 //------- Begin of function Town::should_ai_migrate --------//
601 //
602 // Whether this town should think about migration or not.
603 //
should_ai_migrate()604 int Town::should_ai_migrate()
605 {
606 	//--- if this town is the base town of the nation's territory, don't migrate ---//
607 
608 	Nation* nationPtr = nation_array[nation_recno];
609 
610 	if( is_base_town || nationPtr->ai_base_town_count==0 )		// don't migrate if this is a base town or there is no base town in this nation
611 		return 0;
612 
613 	if( population-jobless_population>0 )		// if there are workers in this town, don't migrate the town people
614 		return 0;
615 
616 	return 1;
617 }
618 //-------- End of function Town::should_ai_migrate ---------//
619 
620 
621 //-------- Begin of function Town::protection_needed ------//
622 //
623 // Return an index from 0 to 100 indicating the military
624 // protection needed for this town.
625 //
protection_needed()626 int Town::protection_needed()
627 {
628 	int   protectionNeeded = population * 10;
629 	Firm* firmPtr;
630 
631 	for( int i=linked_firm_count-1 ; i>=0 ; i-- )
632 	{
633 		firmPtr = firm_array[ linked_firm_array[i] ];
634 
635 		if( firmPtr->nation_recno != nation_recno )
636 			continue;
637 
638 		//----- if this is a camp, add combat level points -----//
639 
640 		if( firmPtr->firm_id == FIRM_MARKET )
641 		{
642 			protectionNeeded += ((FirmMarket*)firmPtr)->stock_value_index()*2;
643 		}
644 		else
645 		{
646 			protectionNeeded += (int) firmPtr->productivity*2;
647 
648 			if( firmPtr->firm_id == FIRM_MINE )		// more protection for mines
649 				protectionNeeded += 200;
650 		}
651 	}
652 
653 	return protectionNeeded;
654 }
655 //---------- End of function Town::protection_needed ------//
656 
657 
658 //-------- Begin of function Town::protection_available ------//
659 //
660 // Return an index from 0 to 100 indicating the military
661 // protection currently available for this town.
662 //
protection_available()663 int Town::protection_available()
664 {
665 	int 	protectionLevel=0;
666 	Firm* firmPtr;
667 
668 	for( int i=linked_firm_count-1 ; i>=0 ; i-- )
669 	{
670 		firmPtr = firm_array[ linked_firm_array[i] ];
671 
672 		if( firmPtr->nation_recno != nation_recno )
673 			continue;
674 
675 		//----- if this is a camp, add combat level points -----//
676 
677 		if( firmPtr->firm_id == FIRM_CAMP )
678 			protectionLevel += 10 + ((FirmCamp*)firmPtr)->total_combat_level();		// +10 for the existence of the camp structure
679 	}
680 
681 	return protectionLevel;
682 }
683 //---------- End of function Town::protection_available ------//
684 
685 
686 //-------- Begin of function Town::think_build_market ------//
687 //
think_build_market()688 int Town::think_build_market()
689 {
690 	if( info.game_date < setup_date + 90 )		// don't build the market too soon, as it may need to migrate to other town
691 		return 0;
692 
693 	Nation* ownNation = nation_array[nation_recno];
694 
695 	if( population < 10 + (100-ownNation->pref_trading_tendency)/20 )
696 		return 0;
697 
698 	if( no_neighbor_space )		// if there is no space in the neighbor area for building a new firm.
699 		return 0;
700 
701 	//--- check whether the AI can build a new firm next this firm ---//
702 
703 	if( !ownNation->can_ai_build(FIRM_MARKET) )
704 		return 0;
705 
706 	//----------------------------------------------------//
707 	// If there is already a firm queued for building with
708 	// a building location that is within the effective range
709 	// of the this firm.
710 	//----------------------------------------------------//
711 
712 	if( ownNation->is_build_action_exist(FIRM_MARKET, center_x, center_y) )
713 		return 0;
714 
715 	//-- only build one market place next to this mine, check if there is any existing one --//
716 
717 	FirmMarket* firmPtr;
718 
719 	for(int i=0; i<linked_firm_count; i++)
720 	{
721 		firmPtr = (FirmMarket*) firm_array[linked_firm_array[i]];
722 
723 		if(firmPtr->firm_id!=FIRM_MARKET)
724 			continue;
725 
726 		//------ if this market is our own one ------//
727 
728 		if( firmPtr->nation_recno == nation_recno &&
729 			 ((FirmMarket*)firmPtr)->is_retail_market )
730 		{
731 			return 0;
732 		}
733 	}
734 
735 	//------ queue building a new market -------//
736 
737 	short buildXLoc, buildYLoc;
738 
739 	if( !ownNation->find_best_firm_loc(FIRM_MARKET, loc_x1, loc_y1, buildXLoc, buildYLoc) )
740 	{
741 		no_neighbor_space = 1;
742 		return 0;
743 	}
744 
745 	ownNation->add_action(buildXLoc, buildYLoc, loc_x1, loc_y1, ACTION_AI_BUILD_FIRM, FIRM_MARKET);
746 
747 	return 1;
748 }
749 //-------- End of function Town::think_build_market ------//
750 
751 
752 //-------- Begin of function Town::think_build_camp ------//
753 //
754 // Think about building military camps for protecting this town.
755 //
think_build_camp()756 int Town::think_build_camp()
757 {
758 	//----- check if any of the other camps protecting this town is still recruiting soldiers, if so, wait until their recruitment is finished. So we can measure the protection available accurately.
759 
760 	Nation* 	 ownNation = nation_array[nation_recno];
761 	FirmCamp* firmCamp;
762 	Firm*		 firmPtr;
763 	int		 campCount=0;
764 
765 	for(int i=linked_firm_count-1; i>=0; --i)
766 	{
767 		err_when(firm_array.is_deleted(linked_firm_array[i]));
768 
769 		firmPtr = firm_array[linked_firm_array[i]];
770 
771 		if(firmPtr->firm_id!=FIRM_CAMP)
772 			continue;
773 
774 		firmCamp = (FirmCamp*) firmPtr;
775 
776 		if( firmCamp->nation_recno != nation_recno )
777 			continue;
778 
779 		if( firmCamp->under_construction || firmCamp->ai_recruiting_soldier )  			// if this camp is still trying to recruit soldiers
780 			return 0;
781 
782 		campCount++;
783 	}
784 
785 	//--- this is one of the few base towns the nation has, then a camp must be built ---//
786 
787 	if( campCount==0 && is_base_town && ownNation->ai_base_town_count<=2 )
788 	{
789 		return ai_build_neighbor_firm(FIRM_CAMP);
790 	}
791 
792 	//---- only build camp if we have enough cash and profit ----//
793 
794 	if( !ownNation->ai_should_spend(70+ownNation->pref_military_development/4) ) 		// 70 to 95
795 		return 0;
796 
797 	//---- only build camp if we need more protection than it is currently available ----//
798 
799 	int protectionNeeded 	= protection_needed();
800 	int protectionAvailable = protection_available();
801 
802 	if( protectionAvailable >= protectionNeeded )
803 		return 0;
804 
805 	Nation* nationPtr = nation_array[nation_recno];
806 
807 	if( !(protectionNeeded>0 && protectionAvailable==0) )		// if protection needed > 0, and protection available is 0, we must build a camp now
808 	{
809 		int needUrgency = 100 * (protectionNeeded-protectionAvailable) / protectionNeeded;
810 
811 		if( nationPtr->total_jobless_population-MAX_WORKER <
812 			 (100-needUrgency) * (200 - nationPtr->pref_military_development) / 200 )
813 		{
814 			return 0;
815 		}
816 	}
817 
818 	//--- check if we have enough people to recruit ---//
819 
820 	int buildFlag = 0;
821 
822 	if( nationPtr->total_jobless_population >= 16 )
823 	{
824 		buildFlag = 1;
825 	}
826 	if( nationPtr->total_jobless_population >= 8 && is_base_town )
827 	{
828 		buildFlag = 1;
829 	}
830 	else if( nationPtr->ai_has_should_close_camp(region_id) )		// there is camp that can be closed
831 	{
832 		buildFlag = 1;
833 	}
834 
835 	if( !buildFlag )
836 		return 0;
837 
838 	return ai_build_neighbor_firm(FIRM_CAMP);
839 }
840 //---------- End of function Town::think_build_camp ------//
841 
842 
843 //-------- Begin of function Town::update_product_supply ------//
844 //
update_product_supply()845 void Town::update_product_supply()
846 {
847 	FirmMarket* firmPtr;
848 	int  productId;
849 
850 	memset( has_product_supply, 0, sizeof(has_product_supply) );
851 
852 	//----- scan for linked market place -----//
853 
854 	for( int i=linked_firm_count-1 ; i>=0 ; i-- )
855 	{
856 		firmPtr = (FirmMarket*) firm_array[ linked_firm_array[i] ];
857 
858 		if( firmPtr->nation_recno != nation_recno ||
859 			 firmPtr->firm_id != FIRM_MARKET )
860 		{
861 			continue;
862 		}
863 
864 		//---- check what type of products they are selling ----//
865 
866 		for( int j=0 ; j<MAX_MARKET_GOODS ; j++ )
867 		{
868 			productId = firmPtr->market_goods_array[j].product_raw_id;
869 
870 			if (productId > 1)
871 				has_product_supply[productId-1]++;
872 		}
873 	}
874 }
875 //---------- End of function Town::update_product_supply ------//
876 
877 
878 //------- Begin of function Town::think_build_research -------//
879 
think_build_research()880 int Town::think_build_research()
881 {
882 	Nation* nationPtr = nation_array[nation_recno];
883 
884 	if( !is_base_town )
885 		return 0;
886 
887 	if( jobless_population < MAX_WORKER ||
888 		 nationPtr->total_jobless_population < MAX_WORKER*2 )
889 	{
890 		return 0;
891 	}
892 
893 	if( nationPtr->true_profit_365days() < 0 )
894 		return 0;
895 
896 	if( !nationPtr->ai_should_spend( 25 + nationPtr->pref_use_weapon/2 - nationPtr->ai_research_count*10 ) )
897 		return 0;
898 
899 	int totalTechLevel = nationPtr->total_tech_level();
900 
901 	if( totalTechLevel == tech_res.total_tech_level )		// all technology have been researched
902 		return 0;
903 
904 	//--------------------------------------------//
905 
906 	int maxResearch = 2 * (50+nationPtr->pref_use_weapon) / 50;
907 
908 	maxResearch = MIN(nationPtr->ai_town_count, maxResearch);
909 
910 	if( nationPtr->ai_research_count >= maxResearch )
911 		return 0;
912 
913 	//---- if any of the existing ones are not full employed ----//
914 
915 	FirmResearch* firmResearch;
916 
917 	for( int i=0 ; i<nationPtr->ai_research_count ; i++ )
918 	{
919 		firmResearch = (FirmResearch*) firm_array[ nationPtr->ai_research_array[i] ];
920 
921 		if( firmResearch->region_id != region_id )
922 			continue;
923 
924 		if( firmResearch->worker_count < MAX_WORKER )
925 			return 0;
926 	}
927 	//------- queue building a war factory -------//
928 
929 	return ai_build_neighbor_firm(FIRM_RESEARCH);
930 }
931 //-------- End of function Town::think_build_research -------//
932 
933 
934 //------- Begin of function Town::think_build_war_factory -------//
935 
think_build_war_factory()936 int Town::think_build_war_factory()
937 {
938 	Nation* nationPtr = nation_array[nation_recno];
939 
940 	if( !is_base_town )
941 		return 0;
942 
943 	if( jobless_population < MAX_WORKER ||
944 		 nationPtr->total_jobless_population < MAX_WORKER*2 )
945 	{
946 		return 0;
947 	}
948 
949 	int totalWeaponTechLevel = nationPtr->total_tech_level(UNIT_CLASS_WEAPON);
950 
951 	if( totalWeaponTechLevel==0 )
952 		return 0;
953 
954 	//----- see if we have enough money to build & support the weapon ----//
955 
956 	if( nationPtr->true_profit_365days() < 0 && nationPtr->ai_war_count > 0 )		// if we don't have any war factory, we may want to build one despite that we are losing money
957 		return 0;
958 
959 	if( !nationPtr->ai_should_spend( nationPtr->pref_use_weapon/2 ) )
960 		return 0;
961 
962 	//--------------------------------------------//
963 
964 	int maxWarFactory = (1+totalWeaponTechLevel) * nationPtr->pref_use_weapon / 100;
965 
966 	maxWarFactory = MIN(nationPtr->ai_town_count, maxWarFactory);
967 
968 	if( nationPtr->ai_war_count >= maxWarFactory )
969 		return 0;
970 
971 	//---- if any of the existing ones are not full employed or under capacity ----//
972 
973 	FirmWar* firmWar;
974 
975 	for( int i=0 ; i<nationPtr->ai_war_count ; i++ )
976 	{
977 		firmWar = (FirmWar*) firm_array[ nationPtr->ai_war_array[i] ];
978 
979 		if( firmWar->region_id != region_id )
980 			continue;
981 
982 		if( firmWar->worker_count < MAX_WORKER || !firmWar->build_unit_id )
983 			return 0;
984 	}
985 
986 	//------- queue building a war factory -------//
987 
988 	return ai_build_neighbor_firm(FIRM_WAR_FACTORY);
989 }
990 //-------- End of function Town::think_build_war_factory -------//
991 
992 
993 //------- Begin of function Town::think_build_base -------//
994 //
995 // Think about building seats of power.
996 //
think_build_base()997 int Town::think_build_base()
998 {
999 	Nation* nationPtr = nation_array[nation_recno];
1000 
1001 	if( !is_base_town )
1002 		return 0;
1003 
1004 	//----- see if we have enough money to build & support the weapon ----//
1005 
1006 	if( !nationPtr->ai_should_spend(50) )
1007 		return 0;
1008 
1009 	if( jobless_population < MAX_BASE_PRAYER/2 ||
1010 		 nationPtr->total_jobless_population < MAX_BASE_PRAYER )
1011 	{
1012 		return 0;
1013 	}
1014 
1015 	//------ do a scan on the existing bases first ------//
1016 
1017 	static short buildRatingArray[MAX_RACE];
1018 
1019 	memset( buildRatingArray, 0, sizeof(buildRatingArray) );
1020 
1021 	//--- increase build rating for the seats that this nation knows how to build ---//
1022 
1023 	GodInfo* godInfo;
1024 
1025 	int i;
1026 	for( i=1 ; i<=god_res.god_count ; i++ )
1027 	{
1028 		godInfo = god_res[i];
1029 
1030 		if( godInfo->is_nation_know(nation_recno) )
1031 			buildRatingArray[godInfo->race_id-1] += 100;
1032 	}
1033 
1034 	//--- decrease build rating for the seats that the nation currently has ---//
1035 
1036 	FirmBase* firmBase;
1037 
1038 	for( i=0 ; i<nationPtr->ai_base_count ; i++ )
1039 	{
1040 		firmBase = (FirmBase*) firm_array[ nationPtr->ai_base_array[i] ];
1041 
1042 		buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] = 0;		// only build one
1043 
1044 		/*
1045 		if( firmBase->prayer_count < MAX_BASE_PRAYER )
1046 			buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] = 0;
1047 		else
1048 			buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] -= 10;		// -10 for one existing instance
1049 		*/
1050 	}
1051 
1052 	//------ decide which is the best to build -------//
1053 
1054 	int bestRating=0, bestRaceId=0;
1055 
1056 	for( i=0 ; i<MAX_RACE ; i++ )
1057 	{
1058 		if( buildRatingArray[i] > bestRating )
1059 		{
1060 			bestRating = buildRatingArray[i];
1061 			bestRaceId = i+1;
1062 		}
1063 	}
1064 
1065 	//------- queue building a seat of power ------//
1066 
1067 	if( bestRaceId )
1068 		return ai_build_neighbor_firm(FIRM_BASE, bestRaceId);
1069 
1070 	return 0;
1071 }
1072 //-------- End of function Town::think_build_base -------//
1073 
1074 
1075 //------- Begin of function Town::think_build_inn -------//
1076 //
think_build_inn()1077 int Town::think_build_inn()
1078 {
1079 	Nation* ownNation = nation_array[nation_recno];
1080 
1081 	if( ownNation->ai_inn_count < ownNation->ai_supported_inn_count() )
1082 	{
1083 		return think_build_firm( FIRM_INN, 1 );
1084 	}
1085 
1086 	return 0;
1087 }
1088 //-------- End of function Town::think_build_inn -------//
1089 
1090 
1091 //------- Begin of function Town::ai_build_neighbor_firm -------//
1092 //
1093 // Build a specific firm next to this town.
1094 //
ai_build_neighbor_firm(int firmId,int firmRaceId)1095 int Town::ai_build_neighbor_firm(int firmId, int firmRaceId)
1096 {
1097 	short buildXLoc, buildYLoc;
1098 	Nation* nationPtr = nation_array[nation_recno];
1099 
1100 	if( !nationPtr->find_best_firm_loc(firmId, loc_x1, loc_y1, buildXLoc, buildYLoc) )
1101 	{
1102 		no_neighbor_space = 1;
1103 		return 0;
1104 	}
1105 
1106 	nationPtr->add_action(buildXLoc, buildYLoc, loc_x1, loc_y1, ACTION_AI_BUILD_FIRM, firmId, 1, 0, firmRaceId);
1107 
1108 	return 1;
1109 }
1110 //-------- End of function Town::ai_build_neighbor_firm -------//
1111 
1112 
1113 //------- Begin of function Town::think_split_town -------//
1114 //
1115 // Split the town into two, migrating some population to the new
1116 // town.
1117 //
think_split_town()1118 int Town::think_split_town()
1119 {
1120 	if( jobless_population==0 )			// cannot move if we don't have any mobilizable unit
1121 		return 0;
1122 
1123 	//--- split when the population is close to its limit ----//
1124 
1125 	Nation* nationPtr = nation_array[nation_recno];
1126 
1127 	if( population < 45 + nationPtr->pref_territorial_cohesiveness / 10 )
1128 		return 0;
1129 
1130 	//-------- think about which race to move --------//
1131 
1132 	int mostRaceId1, mostRaceId2, raceId=0;
1133 
1134 	get_most_populated_race(mostRaceId1, mostRaceId2);
1135 
1136 	if( mostRaceId2 && jobless_race_pop_array[mostRaceId2-1] > 0 && can_recruit(mostRaceId2) )
1137 		raceId = mostRaceId2;
1138 
1139 	else if( mostRaceId1 && jobless_race_pop_array[mostRaceId1-1] > 0 && can_recruit(mostRaceId1) )
1140 		raceId = mostRaceId1;
1141 
1142 	else
1143 		raceId = pick_random_race(0, 1);			// 0-recruitable only, 1-also pick spy.
1144 
1145 	if( !raceId )
1146 	{
1147 		//---- if the racial mix favors a split of town -----//
1148 		//
1149 		// This is when there are two major races, both of significant
1150 		// population in the town. This is a good time for us to move
1151 		// the second major race to a new town.
1152 		//
1153 		//---------------------------------------------------//
1154 
1155 		if( mostRaceId2 && jobless_race_pop_array[mostRaceId2] > 0 &&
1156 			 race_pop_array[mostRaceId2] >= population/3 &&		// the race's has at least 1/3 of the town's total population
1157 			 can_recruit(mostRaceId2) )
1158 		{
1159 			raceId = mostRaceId2;
1160 		}
1161 	}
1162 
1163 	if( !raceId )
1164 		return 0;
1165 
1166 	//---- check if there is already a town of this race with low population linked to this town, then don't split a new one ---//
1167 
1168 	Town* townPtr;
1169 
1170 	for( int i=0 ; i<linked_town_count ; i++ )
1171 	{
1172 		townPtr = town_array[ linked_town_array[i] ];
1173 
1174 		if( townPtr->nation_recno == nation_recno &&
1175 			 townPtr->population < 20 &&
1176 			 townPtr->majority_race() == raceId )
1177 		{
1178 			return 0;
1179 		}
1180 	}
1181 
1182 	//-------- settle to a new town ---------//
1183 
1184 	return ai_settle_new(raceId);
1185 }
1186 //-------- End of function Town::think_split_town -------//
1187 
1188 
1189 //------- Begin of function Town::think_move_between_town -------//
1190 //
think_move_between_town()1191 void Town::think_move_between_town()
1192 {
1193 	//------ move people between linked towns ------//
1194 
1195 	int	ourMajorityRace = majority_race();
1196 	int	raceId, rc, loopCount;
1197 	Town* townPtr;
1198 
1199 	for( int i=0 ; i<linked_town_count ; i++ )
1200 	{
1201 		townPtr = town_array[ linked_town_array[i] ];
1202 
1203 		if( townPtr->nation_recno != nation_recno )
1204 			continue;
1205 
1206 		loopCount=0;
1207 
1208 		//--- migrate people to the new town ---//
1209 
1210 		while(1)
1211 		{
1212 			err_when( ++loopCount > 100 );
1213 
1214 			rc = 0;
1215 			raceId = townPtr->majority_race();		// get the linked town's major race
1216 
1217 			if( ourMajorityRace != raceId )		// if our major race is not this race, then move the person to the target town
1218 			{
1219 				rc = 1;
1220 			}
1221 			else //-- if this town's major race is the same as the target town --//
1222 			{
1223 				if( population - townPtr->population > 10 )	// if this town's population is larger than the target town by 10 people, then move
1224 					rc = 1;
1225 			}
1226 
1227 			if( rc )
1228 			{
1229 				if( !migrate_to(townPtr->town_recno, COMMAND_AI, raceId) )
1230 					break;
1231 			}
1232 			else
1233 				break;
1234 		}
1235 	}
1236 }
1237 //-------- End of function Town::think_move_between_town -------//
1238 
1239 
1240 //------- Begin of function Town::ai_settle_new -------//
1241 //
ai_settle_new(int raceId)1242 int Town::ai_settle_new(int raceId)
1243 {
1244 	//-------- locate space for the new town --------//
1245 
1246 	int xLoc=loc_x1, yLoc=loc_y1;    // xLoc & yLoc are used for returning results
1247 
1248 	if( !world.locate_space( &xLoc, &yLoc, loc_x2, loc_y2, STD_TOWN_LOC_WIDTH+2,			// STD_TOWN_LOC_WIDTH+2 for space around the town
1249 									 STD_TOWN_LOC_HEIGHT+2, UNIT_LAND, region_id, 1 ) )
1250 	{
1251 		return 0;
1252 	}
1253 
1254 	//------- it must be within the effective town-to-town distance ---//
1255 
1256 	if( misc.points_distance( center_x, center_y, xLoc+1+(STD_TOWN_LOC_WIDTH-1)/2,
1257 		yLoc+1+(STD_TOWN_LOC_HEIGHT-1)/2 ) > EFFECTIVE_TOWN_TOWN_DISTANCE )
1258 	{
1259 		return 0;
1260 	}
1261 
1262 	// TODO: Should preferably check for a space that has an attached camp, and if can't find then immediately issue order to build a new camp.
1263 
1264 	//--- recruit a unit from the town and order it to settle a new town ---//
1265 
1266 	int unitRecno = recruit(-1, raceId, COMMAND_AI);
1267 
1268 	if( !unitRecno || !unit_array[unitRecno]->is_visible() )
1269 		return 0;
1270 
1271 	unit_array[unitRecno]->settle( xLoc+1, yLoc+1 );
1272 
1273 	return 1;
1274 }
1275 //-------- End of function Town::ai_settle_new -------//
1276 
1277 
1278 //------- Begin of function Town::think_attack_nearby_enemy -------//
1279 //
1280 // Think about attacking enemies near the town.
1281 //
think_attack_nearby_enemy()1282 int Town::think_attack_nearby_enemy()
1283 {
1284 	enum { SCAN_X_RANGE = 6,
1285 			 SCAN_Y_RANGE = 6  };
1286 
1287 	int xLoc1 = loc_x1 - SCAN_X_RANGE;
1288 	int yLoc1 = loc_y1 - SCAN_Y_RANGE;
1289 	int xLoc2 = loc_x2 + SCAN_X_RANGE;
1290 	int yLoc2 = loc_y2 + SCAN_Y_RANGE;
1291 
1292 	xLoc1 = MAX( xLoc1, 0 );
1293 	yLoc1 = MAX( yLoc1, 0 );
1294 	xLoc2 = MIN( xLoc2, MAX_WORLD_X_LOC-1 );
1295 	yLoc2 = MIN( yLoc2, MAX_WORLD_Y_LOC-1 );
1296 
1297 	//------------------------------------------//
1298 
1299 	int		enemyCombatLevel=0;		// the higher the rating, the easier we can attack the target town.
1300 	int 		xLoc, yLoc;
1301 	int		enemyXLoc= -1, enemyYLoc;
1302 	Unit* 	unitPtr;
1303 	Nation* 	nationPtr = nation_array[nation_recno];
1304 	Firm*		firmPtr;
1305 	Location* locPtr;
1306 
1307 	for( yLoc=yLoc1 ; yLoc<=yLoc2 ; yLoc++ )
1308 	{
1309 		locPtr = world.get_loc(xLoc1, yLoc);
1310 
1311 		for( xLoc=xLoc1 ; xLoc<=xLoc2 ; xLoc++, locPtr++ )
1312 		{
1313          //--- if there is an enemy unit here ---//
1314 
1315 			if( locPtr->has_unit(UNIT_LAND) )
1316 			{
1317 				unitPtr = unit_array[ locPtr->unit_recno(UNIT_LAND) ];
1318 
1319 				if( !unitPtr->nation_recno )
1320 					continue;
1321 
1322 				//--- if the unit is idle and he is our enemy ---//
1323 
1324 				if( unitPtr->cur_action == SPRITE_IDLE &&
1325 					 nationPtr->get_relation_status(unitPtr->nation_recno) == NATION_HOSTILE )
1326 				{
1327 					err_when( unitPtr->nation_recno == nation_recno );
1328 
1329 					enemyCombatLevel += (int) unitPtr->hit_points;
1330 
1331 					if( enemyXLoc == -1 || misc.random(5)==0 )
1332 					{
1333 						enemyXLoc = xLoc;
1334 						enemyYLoc = yLoc;
1335 					}
1336 				}
1337 			}
1338 
1339 			//--- if there is an enemy firm here ---//
1340 
1341 			else if( locPtr->is_firm() )
1342 			{
1343 				firmPtr = firm_array[locPtr->firm_recno()];
1344 
1345 				//------- if this is a monster firm ------//
1346 
1347 				if( firmPtr->firm_id == FIRM_MONSTER )		// don't attack monster here, OAI_MONS.CPP will handle that
1348 					continue;
1349 
1350 				//------- if this is a firm of our enemy -------//
1351 
1352 				if( nationPtr->get_relation_status(firmPtr->nation_recno) == NATION_HOSTILE )
1353 				{
1354 					err_when( firmPtr->nation_recno == nation_recno );
1355 
1356 					if( firmPtr->worker_count == 0 )
1357 						enemyCombatLevel += 50;			// empty firm
1358 					else
1359 					{
1360 						Worker* workerPtr = firmPtr->worker_array;
1361 
1362 						for( int i=firmPtr->worker_count ; i>0 ; i--, workerPtr++ )
1363 							enemyCombatLevel += workerPtr->hit_points;
1364 					}
1365 
1366 					if( enemyXLoc == -1 || misc.random(5)==0 )
1367 					{
1368 						enemyXLoc = firmPtr->loc_x1;
1369 						enemyYLoc = firmPtr->loc_y1;
1370 					}
1371 				}
1372 			}
1373 		}
1374 	}
1375 
1376 	//--------- attack the target now -----------//
1377 
1378 	if( enemyCombatLevel > 0 )
1379 	{
1380 		err_when( enemyXLoc < 0 );
1381 
1382 		nationPtr->ai_attack_target( enemyXLoc, enemyYLoc, enemyCombatLevel );
1383 		return 1;
1384 	}
1385 
1386 	return 0;
1387 }
1388 //-------- End of function Town::think_attack_nearby_enemy -------//
1389 
1390 
1391 //------- Begin of function Town::think_attack_linked_enemy -------//
1392 //
1393 // Think about attacking enemy camps that are linked to this town.
1394 //
think_attack_linked_enemy()1395 int Town::think_attack_linked_enemy()
1396 {
1397 	Firm*   firmPtr;
1398 	Nation* ownNation = nation_array[nation_recno];
1399 	int	  targetCombatLevel;
1400 
1401 	for(int i=0; i<linked_firm_count; i++)
1402 	{
1403 		if( linked_firm_enable_array[i] != LINK_EE )		// don't attack if the link is not enabled
1404 			continue;
1405 
1406 		firmPtr = firm_array[ linked_firm_array[i] ];
1407 
1408 		if( firmPtr->nation_recno == nation_recno )
1409 			continue;
1410 
1411 		if( firmPtr->should_close_flag )		// if this camp is about to close
1412 			continue;
1413 
1414 		//--- only attack AI firms when they belong to a hostile nation ---//
1415 
1416 		if( firmPtr->firm_ai &&
1417 			 ownNation->get_relation_status(firmPtr->nation_recno) != NATION_HOSTILE )
1418 		{
1419 			continue;
1420 		}
1421 
1422 		//---- if this is a camp -----//
1423 
1424 		if( firmPtr->firm_id == FIRM_CAMP )
1425 		{
1426 			//----- if we are friendly with the target nation ------//
1427 
1428 			int nationStatus = ownNation->get_relation_status(firmPtr->nation_recno);
1429 
1430 			if( nationStatus >= NATION_FRIENDLY )
1431 			{
1432 				if( !ownNation->ai_should_attack_friendly(firmPtr->nation_recno, 100) )
1433 					continue;
1434 
1435 				ownNation->ai_end_treaty(firmPtr->nation_recno);
1436 			}
1437 			else if( nationStatus == NATION_NEUTRAL )
1438 			{
1439 				//-- if the link is off and the nation's miliary strength is bigger than us, don't attack --//
1440 
1441 				if( nation_array[firmPtr->nation_recno]->military_rank_rating() >
1442 					 ownNation->military_rank_rating() )
1443 				{
1444 					continue;
1445 				}
1446 			}
1447 
1448 			//--- don't attack when the trade rating is high ----//
1449 
1450 			int tradeRating = ownNation->trade_rating(firmPtr->nation_recno);
1451 
1452 			if( tradeRating > 50 ||
1453 				 tradeRating + ownNation->ai_trade_with_rating(firmPtr->nation_recno) > 100 )
1454 			{
1455 				continue;
1456 			}
1457 
1458 			targetCombatLevel = ((FirmCamp*)firmPtr)->total_combat_level();
1459 		}
1460 		else //--- if this is another type of firm ----//
1461 		{
1462 			//--- only attack other types of firm when the status is hostile ---//
1463 
1464 			if( ownNation->get_relation_status(firmPtr->nation_recno) != NATION_HOSTILE )
1465 				continue;
1466 
1467 			targetCombatLevel = 50;
1468 		}
1469 
1470 		//--------- attack now ----------//
1471 
1472 		ownNation->ai_attack_target( firmPtr->loc_x1, firmPtr->loc_y1, targetCombatLevel );
1473 
1474 		return 1;
1475 	}
1476 
1477 	return 0;
1478 }
1479 //-------- End of function Town::think_attack_linked_enemy -------//
1480 
1481 
1482 //-------- Begin of function Town::think_capture_linked_firm --------//
1483 //
1484 // Try to capture firms linked to this town if all the workers in firms
1485 // resident in this town.
1486 //
think_capture_linked_firm()1487 void Town::think_capture_linked_firm()
1488 {
1489 	Firm* firmPtr;
1490 
1491 	//----- scan for linked firms -----//
1492 
1493 	for( int i=linked_firm_count-1 ; i>=0 ; i-- )
1494 	{
1495 		firmPtr = firm_array[ linked_firm_array[i] ];
1496 
1497 		if( firmPtr->nation_recno == nation_recno )		// this is our own firm
1498 			continue;
1499 
1500 		if( firmPtr->can_worker_capture(nation_recno) )	// if we can capture this firm, capture it now
1501 		{
1502 			firmPtr->capture_firm(nation_recno);
1503 		}
1504 	}
1505 }
1506 //-------- End of function Town::think_capture_linked_firm --------//
1507 
1508 
1509 //-------- Begin of function Town::think_capture_enemy_town --------//
1510 //
1511 // Think about sending troops from this town to capture enemy towns.
1512 //
think_capture_enemy_town()1513 int Town::think_capture_enemy_town()
1514 {
1515 	if( !is_base_town )
1516 		return 0;
1517 
1518 	Nation* nationPtr = nation_array[nation_recno];
1519 
1520 	if( nationPtr->ai_capture_enemy_town_recno )		// a capturing action is already in process
1521 		return 0;
1522 
1523 	int surplusProtection = protection_available() - protection_needed();
1524 
1525 	//-- only attack enemy town if we have enough military protection surplus ---//
1526 
1527 	if( surplusProtection < 300 - nationPtr->pref_military_courage*2 )
1528 		return 0;
1529 
1530 	return nationPtr->think_capture_new_enemy_town(this);
1531 }
1532 //-------- End of function Town::think_capture_enemy_town --------//
1533 
1534 
1535 //-------- Begin of function Town::think_counter_spy --------//
1536 //
1537 // Think about planting anti-spy units in this town.
1538 //
think_counter_spy()1539 int Town::think_counter_spy()
1540 {
1541 	if( population >= MAX_TOWN_POPULATION )
1542 		return 0;
1543 
1544 	Nation* ownNation = nation_array[nation_recno];
1545 
1546 	if( ownNation->total_spy_count > ownNation->total_population * (10+ownNation->pref_spy/5) / 100 )		// 10% to 30%
1547 		return 0;
1548 
1549 	if( !ownNation->ai_should_spend(ownNation->pref_counter_spy/2) )		// 0 to 50
1550 		return 0;
1551 
1552 	//--- the expense of spies should not be too large ---//
1553 
1554 	if( ownNation->expense_365days(EXPENSE_SPY) >
1555 		 ownNation->expense_365days() * (50+ownNation->pref_counter_spy) / 400 )
1556 	{
1557 		return 0;
1558 	}
1559 
1560 	//------- check if we need additional spies ------//
1561 
1562 	int spyCount;
1563 	int curSpyLevel = spy_array.total_spy_skill_level( SPY_TOWN, town_recno, nation_recno, spyCount );
1564 
1565 	if( spyCount >= 1+ownNation->pref_counter_spy/40 )		// 1 to 3 spies at MAX in each town
1566 		return 0;
1567 
1568 	//---- if the spy skill needed is more than the current skill level ----//
1569 
1570 	int neededSpyLevel = needed_anti_spy_level();
1571 
1572 	if( neededSpyLevel > curSpyLevel+30 )
1573 	{
1574 		return ownNation->ai_assign_spy_to_town(town_recno);
1575 	}
1576 	else
1577 		return 0;
1578 }
1579 //-------- End of function Town::think_counter_spy --------//
1580 
1581 
1582 //-------- Begin of function Town::needed_anti_spy_level --------//
1583 //
1584 // Return the total needed spy level for anti-spying in this town.
1585 //
needed_anti_spy_level()1586 int Town::needed_anti_spy_level()
1587 {
1588 	return ( linked_firm_count*10 +
1589 				100 * population / MAX_TOWN_POPULATION )
1590 			 * nation_array[nation_recno]->pref_counter_spy / 100;
1591 }
1592 //-------- End of function Town::needed_anti_spy_level --------//
1593 
1594 
1595 //-------- Begin of function Town::think_spying_town --------//
1596 //
1597 // Think about planting spies into independent towns and enemy towns.
1598 //
think_spying_town()1599 int Town::think_spying_town()
1600 {
1601 	int majorityRace = majority_race();
1602 
1603 	//---- don't recruit spy if we are low in cash or losing money ----//
1604 
1605 	Nation* ownNation = nation_array[nation_recno];
1606 
1607 	if( ownNation->total_population < 30-ownNation->pref_spy/10 )		// don't use spies if the population is too low, we need to use have people to grow population
1608 		return 0;
1609 
1610 	if( ownNation->total_spy_count > ownNation->total_population * (10+ownNation->pref_spy/5) / 100 )		// 10% to 30%
1611 		return 0;
1612 
1613 	if( !ownNation->ai_should_spend(ownNation->pref_spy/2) )		// 0 to 50
1614 		return 0;
1615 
1616 	//--- pick minority units first (also for increasing town harmony) ---//
1617 
1618 	for( int raceId=1 ; raceId<=MAX_RACE ; raceId++ )
1619 	{
1620 		if( race_pop_array[raceId-1]==0 || raceId==majorityRace )
1621 			continue;
1622 
1623 		if( !can_recruit(raceId) )
1624 			continue;
1625 
1626 		if( think_spying_town_assign_to(raceId) )
1627 			return 1;
1628 	}
1629 
1630 	//---- then think about assign spies of majority race ----//
1631 
1632 	if( ownNation->pref_spy > 50 )		// only if pref_spy is > 50, it will consider using spies of majority race
1633 	{
1634 		if( can_recruit(majorityRace) )
1635 		{
1636 			if( think_spying_town_assign_to(majorityRace) )
1637 				return 1;
1638 		}
1639 	}
1640 
1641 	return 0;
1642 }
1643 //-------- End of function Town::think_spying_town --------//
1644 
1645 
1646 //-------- Begin of function Town::think_spying_town_assign_to --------//
1647 //
1648 // Think about planting spies into independent towns and enemy towns.
1649 //
think_spying_town_assign_to(int raceId)1650 int Town::think_spying_town_assign_to(int raceId)
1651 {
1652 	Nation* ownNation = nation_array[nation_recno];
1653 
1654 	int targetTownRecno = ownNation->think_assign_spy_target_town(race_id, region_id);
1655 
1656 	if( !targetTownRecno )
1657 		return 0;
1658 
1659 	//------- assign the spy now -------//
1660 
1661 	int unitRecno = recruit(SKILL_SPYING, raceId, COMMAND_AI);
1662 
1663 	if( !unitRecno )
1664 		return 0;
1665 
1666 	Town* targetTown = town_array[targetTownRecno];
1667 
1668 	int actionRecno = ownNation->add_action( targetTown->loc_x1, targetTown->loc_y1,
1669 							-1, -1, ACTION_AI_ASSIGN_SPY, targetTown->nation_recno, 1, unitRecno );
1670 
1671 	if( !actionRecno )
1672 		return 0;
1673 
1674 	train_unit_action_id = ownNation->get_action(actionRecno)->action_id;
1675 
1676 	return 1;
1677 }
1678 //-------- End of function Town::think_spying_town_assign_to --------//
1679 
1680 
1681 //-------- Begin of function Town::update_base_town_status --------//
1682 //
update_base_town_status()1683 void Town::update_base_town_status()
1684 {
1685 	int newBaseTownStatus = new_base_town_status();
1686 
1687 	if( newBaseTownStatus == is_base_town )
1688 		return;
1689 
1690 	Nation* ownNation = nation_array[nation_recno];
1691 
1692 	if( is_base_town )
1693 		ownNation->ai_base_town_count--;
1694 
1695 	if( newBaseTownStatus )
1696 		ownNation->ai_base_town_count++;
1697 
1698 	is_base_town = newBaseTownStatus;
1699 }
1700 //-------- End of function Town::update_base_town_status --------//
1701 
1702 
1703 //-------- Begin of function Town::new_base_town_status --------//
1704 //
new_base_town_status()1705 int Town::new_base_town_status()
1706 {
1707 	Nation* ownNation = nation_array[nation_recno];
1708 
1709 	if( population > 20 + ownNation->pref_territorial_cohesiveness/10 )
1710 		return 1;
1711 
1712 	//---- if there is only 1 town, then it must be the base town ---//
1713 
1714 	if( ownNation->ai_town_count==1 )
1715 		return 1;
1716 
1717 	//---- if there is only 1 town in this region, then it must be the base town ---//
1718 
1719 	AIRegion* aiRegion = ownNation->get_ai_region(region_id);
1720 
1721 	if( aiRegion && aiRegion->town_count==1 )
1722 		return 1;
1723 
1724 	//--- don't drop if there are employed villagers ---//
1725 
1726 	if( jobless_population != population )
1727 		return 1;
1728 
1729 	//---- if this town is linked to a base town, also don't drop it ----//
1730 
1731 	Town* townPtr;
1732 
1733 	for( int i=linked_town_count-1 ; i>=0 ; i-- )
1734 	{
1735 		townPtr = town_array[ linked_town_array[i] ];
1736 
1737 		if( townPtr->nation_recno == nation_recno &&
1738 			 townPtr->is_base_town )
1739 		{
1740 			return 1;
1741 		}
1742 	}
1743 /*
1744 	//---- if there is not a single town meeting the above criteria, then set the town with the largest population to be the base town. ----//
1745 
1746 	if( ownNation->ai_base_town_count <= 1 )
1747 	{
1748 		for( i=ownNation->ai_town_count-1 ; i>=0 ; i-- )
1749 		{
1750 			townPtr = town_array[ ownNation->ai_town_array[i] ];
1751 
1752 			if( townPtr->population > population )		// if this town is not the largest town return 0.
1753 				return 0;
1754 		}
1755 
1756 		return 1;		// return 1 if this town is the largest town.
1757 	}
1758 */
1759 	return 0;
1760 }
1761 //-------- End of function Town::new_base_town_status --------//
1762 
1763 
1764 //-------- Begin of function Town::think_scout --------//
1765 //
think_scout()1766 int Town::think_scout()
1767 {
1768 	Nation* ownNation = nation_array[nation_recno];
1769 
1770 	if( config.explore_whole_map )
1771 		return 0;
1772 
1773 	if( info.game_date > info.game_start_date + 50 + ownNation->pref_scout )	// only in the first half year of the game
1774 		return 0;
1775 
1776 	if( ownNation->ai_town_count > 1 ) 													// only when there is only one town
1777 		return 0;
1778 
1779 	//-------------------------------------------//
1780 
1781 	int destX, destY;
1782 
1783 	if( misc.random(2)==0 )
1784 		destX = center_x + 50 + misc.random(50);
1785 	else
1786 		destX = center_x - 50 - misc.random(50);
1787 
1788 	if( misc.random(2)==0 )
1789 		destY = center_y + 50 + misc.random(50);
1790 	else
1791 		destY = center_y - 50 - misc.random(50);
1792 
1793 	destX = MAX(0, destX);
1794 	destX = MIN(MAX_WORLD_X_LOC-1, destX);
1795 
1796 	destY = MAX(0, destY);
1797 	destY = MIN(MAX_WORLD_Y_LOC-1, destY);
1798 
1799 	ownNation->add_action( destX, destY, loc_x1, loc_y1, ACTION_AI_SCOUT, 0);
1800 
1801 	return 1;
1802 }
1803 //-------- End of function Town::think_scout --------//
1804