1 /* Pioneers - Implementation of the excellent Settlers of Catan board game.
2  *   Go buy a copy.
3  *
4  * Copyright (C) 1999 Dave Cole
5  * Copyright (C) 2003 Bas Wijnen <shevek@fmf.nl>
6  * Copyright (C) 2005,2010 Roland Clobus <rclobus@rclobus.nl>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21  */
22 
23 #include "config.h"
24 #include "ai.h"
25 #include "cost.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 /*
29  * This is a rudimentary AI for Pioneers.
30  *
31  * What it does _NOT_ do:
32  *
33  * -Make roads explicitly to get the longest road card
34  * -Initiate trade with other players
35  * -Do anything seafarers
36  *
37  */
38 
39 typedef struct resource_values_s {
40 	float value[NO_RESOURCE];
41 	MaritimeInfo info;
42 	gint ports[NO_RESOURCE];
43 } resource_values_t;
44 
45 static int quote_num;
46 
47 /* things we can buy, in the order that we want them. */
48 typedef enum {
49 	BUY_CITY,
50 	BUY_SETTLEMENT,
51 	BUY_ROAD,
52 	BUY_DEVEL_CARD,
53 	BUY_LAST
54 } BuyType;
55 
56 /*
57  * Forward declarations
58  */
59 static Edge *best_road_to_road_spot(Node * n, float *score,
60 				    const resource_values_t * resval);
61 
62 static Edge *best_road_to_road(const resource_values_t * resval);
63 
64 static Edge *best_road_spot(const resource_values_t * resval);
65 
66 static Node *best_city_spot(const resource_values_t * resval);
67 
68 static Node *best_settlement_spot(gboolean during_setup,
69 				  const resource_values_t * resval);
70 
71 static int places_can_build_settlement(void);
72 static gint determine_monopoly_resource(void);
73 
74 /*
75  * Functions to keep track of what nodes we've visited
76  */
77 
78 typedef struct node_seen_set_s {
79 
80 	Node *seen[MAP_SIZE * MAP_SIZE];
81 	int size;
82 
83 } node_seen_set_t;
84 
nodeset_reset(node_seen_set_t * set)85 static void nodeset_reset(node_seen_set_t * set)
86 {
87 	set->size = 0;
88 }
89 
nodeset_set(node_seen_set_t * set,Node * n)90 static void nodeset_set(node_seen_set_t * set, Node * n)
91 {
92 	int i;
93 
94 	for (i = 0; i < set->size; i++)
95 		if (set->seen[i] == n)
96 			return;
97 
98 	set->seen[set->size] = n;
99 	set->size++;
100 }
101 
nodeset_isset(node_seen_set_t * set,Node * n)102 static int nodeset_isset(node_seen_set_t * set, Node * n)
103 {
104 	int i;
105 
106 	for (i = 0; i < set->size; i++)
107 		if (set->seen[i] == n)
108 			return 1;
109 
110 	return 0;
111 }
112 
113 typedef void iterate_node_func_t(Node * n, void *rock);
114 
115 /*
116  * Iterate over all the nodes on the map calling func() with 'rock'
117  *
118  */
for_each_node(iterate_node_func_t * func,void * rock)119 static void for_each_node(iterate_node_func_t * func, void *rock)
120 {
121 	Map *map;
122 	int i, j, k;
123 
124 	map = callbacks.get_map();
125 	for (i = 0; i < map->x_size; i++) {
126 		for (j = 0; j < map->y_size; j++) {
127 			for (k = 0; k < 6; k++) {
128 				Node *n = map_node(map, i, j, k);
129 
130 				if (n)
131 					func(n, rock);
132 			}
133 		}
134 	}
135 
136 }
137 
138 /** Determine the required resources.
139  *  @param assets The resources that are available
140  *  @param cost   The cost to buy something
141  *  @retval need  The additional resources required to buy this
142  *  @return TRUE if the assets are enough
143  */
can_pay_for(const gint assets[NO_RESOURCE],const gint cost[NO_RESOURCE],gint need[NO_RESOURCE])144 static gboolean can_pay_for(const gint assets[NO_RESOURCE],
145 			    const gint cost[NO_RESOURCE],
146 			    gint need[NO_RESOURCE])
147 {
148 	gint i;
149 	gboolean have_enough;
150 
151 	have_enough = TRUE;
152 	for (i = 0; i < NO_RESOURCE; i++) {
153 		if (assets[i] >= cost[i])
154 			need[i] = 0;
155 		else {
156 			need[i] = cost[i] - assets[i];
157 			have_enough = FALSE;
158 		}
159 	}
160 	return have_enough;
161 }
162 
163 /* How much does this cost to build? */
cost_of(BuyType bt)164 static const gint *cost_of(BuyType bt)
165 {
166 	switch (bt) {
167 	case BUY_CITY:
168 		return cost_upgrade_settlement();
169 	case BUY_SETTLEMENT:
170 		return cost_settlement();
171 	case BUY_ROAD:
172 		return cost_road();
173 	case BUY_DEVEL_CARD:
174 		return cost_development();
175 	default:
176 		g_assert(0);
177 		return NULL;
178 	}
179 }
180 
181 /*
182  * Do I have the resources to buy this, is it available, and do I want it?
183  */
should_buy(const gint assets[NO_RESOURCE],BuyType bt,const resource_values_t * resval,gint need[NO_RESOURCE])184 static gboolean should_buy(const gint assets[NO_RESOURCE], BuyType bt,
185 			   const resource_values_t * resval,
186 			   gint need[NO_RESOURCE])
187 {
188 	if (!can_pay_for(assets, cost_of(bt), need))
189 		return FALSE;
190 
191 	switch (bt) {
192 	case BUY_CITY:
193 		return (stock_num_cities() > 0 &&
194 			best_city_spot(resval) != NULL);
195 	case BUY_SETTLEMENT:
196 		return (stock_num_settlements() > 0 &&
197 			best_settlement_spot(FALSE, resval) != NULL);
198 	case BUY_ROAD:
199 		/* don't sprawl :) */
200 		return (stock_num_roads() > 0 &&
201 			places_can_build_settlement() <= 2 &&
202 			(best_road_spot(resval) != NULL ||
203 			 best_road_to_road(resval) != NULL));
204 	case BUY_DEVEL_CARD:
205 		return (stock_num_develop() > 0 && can_buy_develop());
206 	default:
207 		/* xxx bridge, ship */
208 		return FALSE;
209 	}
210 }
211 
212 /*
213  * If I buy this, what will I have left?  Note that some values in need[]
214  * can be negative if I can't afford it.
215  */
leftover_resources(const gint assets[NO_RESOURCE],BuyType bt,gint need[NO_RESOURCE])216 static void leftover_resources(const gint assets[NO_RESOURCE],
217 			       BuyType bt, gint need[NO_RESOURCE])
218 {
219 	gint i;
220 	const gint *cost = cost_of(bt);
221 
222 	for (i = 0; i < NO_RESOURCE; i++)
223 		need[i] = assets[i] - cost[i];
224 }
225 
226 /*
227  * Probability of a dice roll
228  */
229 
dice_prob(gint roll)230 static float dice_prob(gint roll)
231 {
232 	switch (roll) {
233 	case 2:
234 	case 12:
235 		return 3;
236 	case 3:
237 	case 11:
238 		return 6;
239 	case 4:
240 	case 10:
241 		return 8;
242 	case 5:
243 	case 9:
244 		return 11;
245 	case 6:
246 	case 8:
247 		return 14;
248 	default:
249 		return 0;
250 	}
251 }
252 
253 /*
254  * By default how valuable is this terrain?
255  */
256 
default_score_terrain(Terrain terrain)257 static float default_score_terrain(Terrain terrain)
258 {
259 	float score;
260 
261 	switch (terrain) {
262 	case GOLD_TERRAIN:	/* gold */
263 		score = 1.25f;
264 		break;
265 	case HILL_TERRAIN:	/* brick */
266 		score = 1.1f;
267 		break;
268 	case FIELD_TERRAIN:	/* grain */
269 		score = 1.0f;
270 		break;
271 	case MOUNTAIN_TERRAIN:	/* rock */
272 		score = 1.05f;
273 		break;
274 	case PASTURE_TERRAIN:	/* sheep */
275 		score = 1.0f;
276 		break;
277 	case FOREST_TERRAIN:	/* wood */
278 		score = 1.1f;
279 		break;
280 	case DESERT_TERRAIN:
281 	case SEA_TERRAIN:
282 	default:
283 		score = 0.0f;
284 		break;
285 	}
286 
287 	return score;
288 }
289 
290 /* For each node I own see how much i produce with it. keep a
291  * tally with 'produce'
292  */
293 
reevaluate_iterator(Node * n,void * rock)294 static void reevaluate_iterator(Node * n, void *rock)
295 {
296 	float *produce = (float *) rock;
297 
298 	/* if i own this node */
299 	if ((n) && (n->owner == my_player_num())) {
300 		int l;
301 		for (l = 0; l < 3; l++) {
302 			Hex *h = n->hexes[l];
303 			float mult = 1.0;
304 
305 			if (n->type == BUILD_CITY)
306 				mult = 2.0;
307 
308 			if (h && h->terrain < DESERT_TERRAIN) {
309 				produce[h->terrain] +=
310 				    mult *
311 				    default_score_terrain(h->terrain) *
312 				    dice_prob(h->roll);
313 			}
314 
315 		}
316 	}
317 
318 }
319 
320 /*
321  * Reevaluate the value of all the resources to us
322  */
323 
reevaluate_resources(resource_values_t * outval)324 static void reevaluate_resources(resource_values_t * outval)
325 {
326 	float produce[NO_RESOURCE];
327 	int i;
328 
329 	for (i = 0; i < NO_RESOURCE; i++) {
330 		produce[i] = 0;
331 	}
332 
333 	for_each_node(&reevaluate_iterator, (void *) produce);
334 
335 	/* Now invert all the positive numbers and give any zeros a weight of 2
336 	 *
337 	 */
338 	for (i = 0; i < NO_RESOURCE; i++) {
339 		if (produce[i] == 0) {
340 			outval->value[i] =
341 			    default_score_terrain(resource_to_terrain(i));
342 		} else {
343 			outval->value[i] = 1.0f / produce[i];
344 		}
345 
346 	}
347 
348 	/*
349 	 * Save the maritime info too so we know if we can do port trades
350 	 */
351 	map_maritime_info(callbacks.get_map(), &outval->info,
352 			  my_player_num());
353 
354 	for (i = 0; i < NO_RESOURCE; i++) {
355 		if (outval->info.specific_resource[i])
356 			outval->ports[i] = 2;
357 		else if (outval->info.any_resource)
358 			outval->ports[i] = 3;
359 		else
360 			outval->ports[i] = 4;
361 	}
362 }
363 
364 
365 /*
366  *
367  */
resource_value(Resource resource,const resource_values_t * resval)368 static float resource_value(Resource resource,
369 			    const resource_values_t * resval)
370 {
371 	if (resource < NO_RESOURCE)
372 		return resval->value[resource];
373 	else if (resource == GOLD_RESOURCE)
374 		return default_score_terrain(GOLD_TERRAIN);
375 	else
376 		return 0.0;
377 }
378 
379 
380 /*
381  * How valuable is this hex to me?
382  */
score_hex(Hex * hex,const resource_values_t * resval)383 static float score_hex(Hex * hex, const resource_values_t * resval)
384 {
385 	float score;
386 
387 	if (hex == NULL)
388 		return 0;
389 
390 	/* multiple resource value by dice probability */
391 	score =
392 	    resource_value(terrain_to_resource(hex->terrain),
393 			   resval) * dice_prob(hex->roll);
394 
395 	/* if we don't have a 3 for 1 port yet and this is one it's valuable! */
396 	if (!resval->info.any_resource) {
397 		if (hex->resource == ANY_RESOURCE)
398 			score += 0.5f;
399 	}
400 
401 	return score;
402 }
403 
404 /*
405  * How valuable is this hex to others
406  */
default_score_hex(Hex * hex)407 static float default_score_hex(Hex * hex)
408 {
409 	float score;
410 
411 	if (hex == NULL)
412 		return 0;
413 
414 	/* multiple resource value by dice probability */
415 	score = default_score_terrain(hex->terrain) * dice_prob(hex->roll);
416 
417 	return score;
418 }
419 
420 /*
421  * Give a numerical score to how valuable putting a settlement/city on this spot is
422  *
423  */
score_node(const Node * node,gboolean city,const resource_values_t * resval)424 static float score_node(const Node * node, gboolean city,
425 			const resource_values_t * resval)
426 {
427 	int i;
428 	float score = 0;
429 
430 	/* if not a node, how did this happen? */
431 	g_assert(node != NULL);
432 
433 	/* if already occupied, in water, or too close to others  give a score of -1 */
434 	if (is_node_on_land(node) == FALSE)
435 		return -1;
436 	if (is_node_spacing_ok(node) == FALSE)
437 		return -1;
438 	if (!city) {
439 		if (node->owner != -1)
440 			return -1;
441 	}
442 
443 	for (i = 0; i < 3; i++) {
444 		score += score_hex(node->hexes[i], resval);
445 	}
446 
447 	return score;
448 }
449 
450 /*
451  * Road connects here
452  */
road_connects(Node * n)453 static int road_connects(Node * n)
454 {
455 	int i;
456 
457 	if (n == NULL)
458 		return 0;
459 
460 	for (i = 0; i < 3; i++) {
461 		Edge *e = n->edges[i];
462 
463 		if ((e) && (e->owner == my_player_num()))
464 			return 1;
465 	}
466 
467 	return 0;
468 }
469 
470 
471 /** Find the best spot for a settlement
472  * @param during_setup Build a settlement during the setup phase?
473  *                     During setup: no connected road is required,
474  *                                   and the no_setup must be taken into account
475  *                     Normal play:  settlement must be next to a road we own.
476  */
best_settlement_spot(gboolean during_setup,const resource_values_t * resval)477 static Node *best_settlement_spot(gboolean during_setup,
478 				  const resource_values_t * resval)
479 {
480 	int i, j, k;
481 	Node *best = NULL;
482 	float bestscore = -1.0;
483 	float score;
484 	Map *map = callbacks.get_map();
485 
486 	for (i = 0; i < map->x_size; i++) {
487 		for (j = 0; j < map->y_size; j++) {
488 			for (k = 0; k < 6; k++) {
489 				Node *n = map_node(map, i, j, k);
490 				if (!n)
491 					continue;
492 				if (during_setup) {
493 					if (n->no_setup)
494 						continue;
495 				} else {
496 					if (!road_connects(n))
497 						continue;
498 				}
499 
500 				score = score_node(n, FALSE, resval);
501 				if (score > bestscore) {
502 					best = n;
503 					bestscore = score;
504 				}
505 			}
506 
507 		}
508 	}
509 
510 	return best;
511 }
512 
513 
514 /*
515  * What is the best settlement to upgrade to a city?
516  *
517  */
best_city_spot(const resource_values_t * resval)518 static Node *best_city_spot(const resource_values_t * resval)
519 {
520 	int i, j, k;
521 	Node *best = NULL;
522 	float bestscore = -1.0;
523 	Map *map = callbacks.get_map();
524 
525 	for (i = 0; i < map->x_size; i++) {
526 		for (j = 0; j < map->y_size; j++) {
527 			for (k = 0; k < 6; k++) {
528 				Node *n = map_node(map, i, j, k);
529 				if (!n)
530 					continue;
531 				if ((n->owner == my_player_num())
532 				    && (n->type == BUILD_SETTLEMENT)) {
533 					float score =
534 					    score_node(n, TRUE, resval);
535 
536 					if (score > bestscore) {
537 						best = n;
538 						bestscore = score;
539 					}
540 				}
541 			}
542 
543 		}
544 	}
545 
546 	return best;
547 }
548 
549 /*
550  * Return the opposite end of this node, edge
551  *
552  */
other_node(Edge * e,Node * n)553 static Node *other_node(Edge * e, Node * n)
554 {
555 	if (e->nodes[0] == n)
556 		return e->nodes[1];
557 	else
558 		return e->nodes[0];
559 }
560 
561 /*
562  *
563  *
564  */
traverse_out(Node * n,node_seen_set_t * set,float * score,const resource_values_t * resval)565 static Edge *traverse_out(Node * n, node_seen_set_t * set, float *score,
566 			  const resource_values_t * resval)
567 {
568 	float bscore = 0.0;
569 	Edge *best = NULL;
570 	int i;
571 
572 	/* mark this node as seen */
573 	nodeset_set(set, n);
574 
575 	for (i = 0; i < 3; i++) {
576 		Edge *e = n->edges[i];
577 		Edge *cur_e = NULL;
578 		Node *othernode;
579 		float cur_score;
580 
581 		if (!e)
582 			continue;
583 
584 		othernode = other_node(e, n);
585 		g_assert(othernode != NULL);
586 
587 		/* if our road traverse it */
588 		if (e->owner == my_player_num()) {
589 
590 			if (!nodeset_isset(set, othernode))
591 				cur_e =
592 				    traverse_out(othernode, set,
593 						 &cur_score, resval);
594 
595 		} else if (can_road_be_built(e, my_player_num())) {
596 
597 			/* no owner, how good is the other node ? */
598 			cur_e = e;
599 
600 			cur_score = score_node(othernode, FALSE, resval);
601 
602 			/* umm.. can we build here? */
603 			/*if (!can_settlement_be_built(othernode, my_player_num ()))
604 			   cur_e = NULL;       */
605 		}
606 
607 		/* is this the best edge we've seen? */
608 		if ((cur_e != NULL) && (cur_score > bscore)) {
609 			best = cur_e;
610 			bscore = cur_score;
611 
612 		}
613 	}
614 
615 	*score = bscore;
616 	return best;
617 }
618 
619 /*
620  * Best road to a road
621  *
622  */
best_road_to_road_spot(Node * n,float * score,const resource_values_t * resval)623 static Edge *best_road_to_road_spot(Node * n, float *score,
624 				    const resource_values_t * resval)
625 {
626 	float bscore = -1.0;
627 	Edge *best = NULL;
628 	int i, j;
629 
630 	for (i = 0; i < 3; i++) {
631 		Edge *e = n->edges[i];
632 		if (e) {
633 			Node *othernode = other_node(e, n);
634 
635 			if (can_road_be_built(e, my_player_num())) {
636 
637 				for (j = 0; j < 3; j++) {
638 					Edge *e2 = othernode->edges[j];
639 					if (e2 == NULL)
640 						continue;
641 
642 					/* We need to look further, temporarily mark this edge as having our road on it. */
643 					e->owner = my_player_num();
644 					e->type = BUILD_ROAD;
645 
646 					if (can_road_be_built
647 					    (e2, my_player_num())) {
648 						float nscore =
649 						    score_node(other_node
650 							       (e2,
651 								othernode),
652 							       FALSE,
653 							       resval);
654 
655 						if (nscore > bscore) {
656 							bscore = nscore;
657 							best = e;
658 						}
659 					}
660 					/* restore map to its real state */
661 					e->owner = -1;
662 					e->type = BUILD_NONE;
663 				}
664 			}
665 
666 		}
667 	}
668 
669 	*score = bscore;
670 	return best;
671 }
672 
673 /*
674  * Best road to road on whole map
675  *
676  */
best_road_to_road(const resource_values_t * resval)677 static Edge *best_road_to_road(const resource_values_t * resval)
678 {
679 	int i, j, k;
680 	Edge *best = NULL;
681 	float bestscore = -1.0;
682 	Map *map = callbacks.get_map();
683 
684 	for (i = 0; i < map->x_size; i++) {
685 		for (j = 0; j < map->y_size; j++) {
686 			for (k = 0; k < 6; k++) {
687 				Node *n = map_node(map, i, j, k);
688 				Edge *e;
689 				float score;
690 
691 				if ((n) && (n->owner == my_player_num())) {
692 					e = best_road_to_road_spot(n,
693 								   &score,
694 								   resval);
695 					if (score > bestscore) {
696 						best = e;
697 						bestscore = score;
698 					}
699 				}
700 			}
701 		}
702 	}
703 
704 	return best;
705 }
706 
707 /*
708  * Best road spot
709  *
710  */
best_road_spot(const resource_values_t * resval)711 static Edge *best_road_spot(const resource_values_t * resval)
712 {
713 	int i, j, k;
714 	Edge *best = NULL;
715 	float bestscore = -1.0;
716 	node_seen_set_t nodeseen;
717 	Map *map = callbacks.get_map();
718 
719 	/*
720 	 * For every node that we're the owner of traverse out to find the best
721 	 * node we're one road away from and build that road
722 	 *
723 	 *
724 	 * xxx loops
725 	 */
726 
727 	for (i = 0; i < map->x_size; i++) {
728 		for (j = 0; j < map->y_size; j++) {
729 			for (k = 0; k < 6; k++) {
730 				Node *n = map_node(map, i, j, k);
731 
732 				if ((n != NULL)
733 				    && (n->owner == my_player_num())) {
734 					float score = -1.0;
735 					Edge *e;
736 
737 					nodeset_reset(&nodeseen);
738 
739 					e = traverse_out(n, &nodeseen,
740 							 &score, resval);
741 
742 					if (score > bestscore) {
743 						best = e;
744 						bestscore = score;
745 					}
746 				}
747 			}
748 
749 		}
750 	}
751 
752 	return best;
753 }
754 
755 
756 /*
757  * Any road at all that's valid for us to build
758  */
759 
rand_road_iterator(Node * n,void * rock)760 static void rand_road_iterator(Node * n, void *rock)
761 {
762 	int i;
763 	Edge **out = (Edge **) rock;
764 
765 	if (n == NULL)
766 		return;
767 
768 	for (i = 0; i < 3; i++) {
769 		Edge *e = n->edges[i];
770 
771 		if ((e) && (can_road_be_built(e, my_player_num())))
772 			*out = e;
773 	}
774 }
775 
776 /*
777  * Find any road we can legally build
778  *
779  */
find_random_road(void)780 static Edge *find_random_road(void)
781 {
782 	Edge *e = NULL;
783 
784 	for_each_node(&rand_road_iterator, &e);
785 
786 	return e;
787 }
788 
789 
places_can_build_iterator(Node * n,void * rock)790 static void places_can_build_iterator(Node * n, void *rock)
791 {
792 	int *count = (int *) rock;
793 
794 	if (can_settlement_be_built(n, my_player_num()))
795 		(*count)++;
796 }
797 
places_can_build_settlement(void)798 static int places_can_build_settlement(void)
799 {
800 	int count = 0;
801 
802 	for_each_node(&places_can_build_iterator, (void *) &count);
803 
804 	return count;
805 }
806 
807 /*
808  * How many resource cards does player have?
809  *
810  */
num_assets(gint assets[NO_RESOURCE])811 static int num_assets(gint assets[NO_RESOURCE])
812 {
813 	int i;
814 	int count = 0;
815 
816 	for (i = 0; i < NO_RESOURCE; i++) {
817 		count += assets[i];
818 	}
819 
820 	return count;
821 }
822 
player_get_num_resource(int player)823 static int player_get_num_resource(int player)
824 {
825 	return player_get(player)->statistics[STAT_RESOURCES];
826 }
827 
828 /*
829  * Does this resource list contain one element? If so return it
830  * otherwise return NO_RESOURCE
831  */
which_one(gint assets[NO_RESOURCE])832 static int which_one(gint assets[NO_RESOURCE])
833 {
834 	int i;
835 	int res = NO_RESOURCE;
836 	int tot = 0;
837 
838 	for (i = 0; i < NO_RESOURCE; i++) {
839 
840 		if (assets[i] > 0) {
841 			tot += assets[i];
842 			res = i;
843 		}
844 	}
845 
846 	if (tot == 1)
847 		return res;
848 
849 	return NO_RESOURCE;
850 }
851 
852 /*
853  * Does this resource list contain just one kind of element? If so return it
854  * otherwise return NO_RESOURCE
855  */
which_resource(gint assets[NO_RESOURCE])856 static int which_resource(gint assets[NO_RESOURCE])
857 {
858 	int i;
859 	int res = NO_RESOURCE;
860 	int n_nonzero = 0;
861 
862 	for (i = 0; i < NO_RESOURCE; i++) {
863 
864 		if (assets[i] > 0) {
865 			n_nonzero++;
866 			res = i;
867 		}
868 	}
869 
870 	if (n_nonzero == 1)
871 		return res;
872 
873 	return NO_RESOURCE;
874 }
875 
876 /*
877  * What resource do we want the most?
878  *
879  * NOTE: If a resource is not available (players or bank), the
880  * resval->value[resource] should be zero.
881  */
resource_desire(gint assets[NO_RESOURCE],const resource_values_t * resval)882 static int resource_desire(gint assets[NO_RESOURCE],
883 			   const resource_values_t * resval)
884 {
885 	int i;
886 	BuyType bt;
887 	int res = NO_RESOURCE;
888 	float value = 0.0;
889 	gint need[NO_RESOURCE];
890 
891 	/* do i need just 1 more for something? */
892 	for (bt = 0; bt < BUY_LAST; bt++) {
893 		if (should_buy(assets, bt, resval, need))
894 			continue;
895 		res = which_one(need);
896 		if (res == NO_RESOURCE || resval->value[res] == 0)
897 			continue;
898 		return res;
899 	}
900 
901 	/* desire the one we don't produce the most */
902 	res = NO_RESOURCE;
903 	for (i = 0; i < NO_RESOURCE; i++) {
904 		if ((resval->value[i] > value) && (assets[i] < 2)) {
905 			res = i;
906 			value = resval->value[i];
907 		}
908 	}
909 
910 	return res;
911 }
912 
913 
findit_iterator(Node * n,void * rock)914 static void findit_iterator(Node * n, void *rock)
915 {
916 	Node **node = (Node **) rock;
917 	int i;
918 
919 	if (!n)
920 		return;
921 	if (n->owner != my_player_num())
922 		return;
923 
924 	/* if i own this node */
925 	for (i = 0; i < 3; i++) {
926 		if (n->edges[i] == NULL)
927 			continue;
928 		if (n->edges[i]->owner == my_player_num())
929 			return;
930 	}
931 
932 	*node = n;
933 }
934 
935 
936 /* Find the settlement with no roads yet
937  *
938  */
939 
void_settlement(void)940 static Node *void_settlement(void)
941 {
942 	Node *ret = NULL;
943 
944 	for_each_node(&findit_iterator, (void *) &ret);
945 
946 	return ret;
947 }
948 
949 /*
950  * Game setup
951  * Build one house and one road
952  */
greedy_setup_house(void)953 static void greedy_setup_house(void)
954 {
955 	Node *node;
956 	resource_values_t resval;
957 
958 	reevaluate_resources(&resval);
959 
960 	if (stock_num_settlements() == 0) {
961 		ai_panic(N_("No settlements in stock to use for setup"));
962 		return;
963 	}
964 
965 	node = best_settlement_spot(TRUE, &resval);
966 
967 	if (node == NULL) {
968 		ai_panic(N_("There is no place to setup a settlement"));
969 		return;
970 	}
971 
972 	/*node_add(player, BUILD_SETTLEMENT, node->x, node->y, node->pos, FALSE); */
973 	cb_build_settlement(node);
974 }
975 
976 
977 /*
978  * Game setup
979  * Build one house and one road
980  */
greedy_setup_road(void)981 static void greedy_setup_road(void)
982 {
983 	Node *node;
984 	Edge *e = NULL;
985 	guint i;
986 	resource_values_t resval;
987 	float tmp;
988 
989 	reevaluate_resources(&resval);
990 
991 	if (stock_num_roads() == 0) {
992 		ai_panic(N_("No roads in stock to use for setup"));
993 		return;
994 	}
995 
996 	node = void_settlement();
997 
998 	e = best_road_to_road_spot(node, &tmp, &resval);
999 
1000 	/* if didn't find one just pick one randomly */
1001 	if (e == NULL) {
1002 		for (i = 0; i < G_N_ELEMENTS(node->edges); i++) {
1003 			if (is_edge_on_land(node->edges[i])) {
1004 				e = node->edges[i];
1005 				break;
1006 			}
1007 		}
1008 		if (e == NULL) {
1009 			ai_panic(N_("There is no place to setup a road"));
1010 			return;
1011 		}
1012 	}
1013 
1014 	cb_build_road(e);
1015 }
1016 
1017 /*
1018  * Determine if there are any trades that I can do which will give me
1019  * enough to buy something.
1020  */
find_optimal_trade(gint assets[NO_RESOURCE],const resource_values_t * resval,gint * amount,Resource * trade_away,Resource * want_resource)1021 static gboolean find_optimal_trade(gint assets[NO_RESOURCE],
1022 				   const resource_values_t * resval,
1023 				   gint * amount,
1024 				   Resource * trade_away,
1025 				   Resource * want_resource)
1026 {
1027 	Resource res = NO_RESOURCE;
1028 	Resource temp;
1029 	gint need[NO_RESOURCE];
1030 	BuyType bt;
1031 
1032 	for (bt = 0; bt < BUY_LAST; bt++) {
1033 
1034 		/* If we should buy something, why haven't we bought it? */
1035 		if (should_buy(assets, bt, resval, need))
1036 			continue;
1037 
1038 		/* See what we need, and if we can get it. */
1039 		res = which_one(need);
1040 		if (res == NO_RESOURCE || get_bank()[res] == 0)
1041 			continue;
1042 
1043 		/* See what we have left after we buy this (one value
1044 		 * will be negative), and whether we have enough of something
1045 		 * to trade for what's missing.
1046 		 */
1047 		leftover_resources(assets, bt, need);
1048 		for (temp = 0; temp < NO_RESOURCE; temp++) {
1049 			if (temp == res)
1050 				continue;
1051 			if (need[temp] > resval->ports[temp]) {
1052 				*amount = resval->ports[temp];
1053 				*trade_away = temp;
1054 				*want_resource = res;
1055 				return TRUE;
1056 			}
1057 		}
1058 	}
1059 	return FALSE;
1060 }
1061 
1062 /** I am allowed to do a maritime trade, but will I do it?
1063  * @param assets The resources I already have
1064  * @param resval The value of the resources
1065  * @retval amount The amount to trade
1066  * @retval trade_away The resource to trade away
1067  * @retval want_resource The resource I want to have
1068  * @return TRUE if I want to do the trade
1069  */
will_do_maritime_trade(gint assets[NO_RESOURCE],const resource_values_t * resval,gint * amount,Resource * trade_away,Resource * want_resource)1070 static gboolean will_do_maritime_trade(gint assets[NO_RESOURCE],
1071 				       const resource_values_t * resval,
1072 				       gint * amount,
1073 				       Resource * trade_away,
1074 				       Resource * want_resource)
1075 {
1076 	Resource res, want, discard;
1077 
1078 	/* See if we can trade at all. */
1079 	for (res = 0; res < NO_RESOURCE; res++) {
1080 		if (assets[res] >= resval->ports[res])
1081 			break;
1082 	}
1083 	if (res == NO_RESOURCE)
1084 		return FALSE;
1085 
1086 	/* See if we can do a single trade that allows us to buy something. */
1087 	if (find_optimal_trade(assets, resval, amount, trade_away,
1088 			       want_resource))
1089 		return TRUE;
1090 
1091 	/*
1092 	 * We can trade, but we won't be able to buy anything.
1093 	 *
1094 	 * Try a simple heuristic - if there's a resource we can trade away
1095 	 * and still have at least 1 left, and we need something (and we can
1096 	 * get it), do the trade.  Try to use the best port for this.
1097 	 */
1098 	want = resource_desire(assets, resval);
1099 	if (want == NO_RESOURCE || get_bank()[want] == 0)
1100 		return FALSE;
1101 
1102 	discard = NO_RESOURCE;
1103 	for (res = 0; res < NO_RESOURCE; res++) {
1104 		if (res == want)
1105 			continue;
1106 		if (assets[res] > resval->ports[res] &&
1107 		    (discard == NO_RESOURCE
1108 		     || resval->ports[discard] > resval->ports[res]))
1109 			discard = res;
1110 	}
1111 
1112 	if (discard != NO_RESOURCE) {
1113 		*trade_away = discard;
1114 		*want_resource = want;
1115 		*amount = resval->ports[discard];
1116 		return TRUE;
1117 	}
1118 
1119 	return FALSE;
1120 }
1121 
1122 /** I can play the card, but will I do it?
1123  *  @param cardtype The type of card to consider
1124  *  @return TRUE if the card is to be played
1125  */
will_play_development_card(DevelType cardtype)1126 static gboolean will_play_development_card(DevelType cardtype)
1127 {
1128 	gint amount, i;
1129 
1130 	if (is_victory_card(cardtype)) {
1131 		return TRUE;
1132 	}
1133 
1134 	switch (cardtype) {
1135 	case DEVEL_SOLDIER:
1136 		return TRUE;
1137 	case DEVEL_YEAR_OF_PLENTY:
1138 		/* only when the bank is full enough */
1139 		amount = 0;
1140 		for (i = 0; i < NO_RESOURCE; i++)
1141 			amount += get_bank()[i];
1142 		if (amount >= 2) {
1143 			return TRUE;
1144 		}
1145 		break;
1146 	case DEVEL_ROAD_BUILDING:
1147 		/* don't if don't have two roads left */
1148 		if (stock_num_roads() < 2)
1149 			break;
1150 		return TRUE;
1151 	case DEVEL_MONOPOLY:
1152 		return determine_monopoly_resource() != NO_RESOURCE;
1153 	default:
1154 		break;
1155 	}
1156 	return FALSE;
1157 }
1158 
1159 /*
1160  * What to do? what to do?
1161  *
1162  */
1163 
greedy_turn(void)1164 static void greedy_turn(void)
1165 {
1166 	resource_values_t resval;
1167 	guint i;
1168 	gint need[NO_RESOURCE], assets[NO_RESOURCE];
1169 
1170 	/* play soldier card before the turn when an own resource is blocked */
1171 	Hex *hex = map_robber_hex(callbacks.get_map());
1172 	if (hex && !have_rolled_dice() && can_play_any_develop()) {
1173 		const Deck *deck = get_devel_deck();
1174 		for (i = 0; i < deck_count(deck); i++) {
1175 			DevelType cardtype = deck_get_guint(deck, i);
1176 			if (cardtype == DEVEL_SOLDIER
1177 			    && can_play_develop(i)) {
1178 				int j;
1179 				for (j = 0; j < 6; j++) {
1180 					if (hex->nodes[j]->owner ==
1181 					    my_player_num()) {
1182 						cb_play_develop(i);
1183 						return;
1184 					}
1185 				}
1186 			}
1187 		}
1188 	}
1189 
1190 	if (!have_rolled_dice()) {
1191 		cb_roll();
1192 		return;
1193 	}
1194 
1195 	/* Don't wait before the dice roll, that will take too long */
1196 	ai_wait();
1197 	for (i = 0; i < NO_RESOURCE; ++i)
1198 		assets[i] = resource_asset(i);
1199 
1200 	reevaluate_resources(&resval);
1201 
1202 	/* if can then buy city */
1203 	if (should_buy(assets, BUY_CITY, &resval, need)) {
1204 
1205 		Node *n = best_city_spot(&resval);
1206 		if (n != NULL) {
1207 			cb_build_city(n);
1208 			return;
1209 		}
1210 	}
1211 
1212 	/* if can then buy settlement */
1213 	if (should_buy(assets, BUY_SETTLEMENT, &resval, need)) {
1214 
1215 		Node *n = best_settlement_spot(FALSE, &resval);
1216 		if (n != NULL) {
1217 			cb_build_settlement(n);
1218 			return;
1219 		}
1220 
1221 	}
1222 
1223 	if (should_buy(assets, BUY_ROAD, &resval, need)) {
1224 
1225 		Edge *e = best_road_spot(&resval);
1226 
1227 		if (e == NULL) {
1228 			e = best_road_to_road(&resval);
1229 		}
1230 
1231 		if (e != NULL) {
1232 			cb_build_road(e);
1233 			return;
1234 		}
1235 	}
1236 
1237 	/* if we can buy a development card and there are some left */
1238 	if (should_buy(assets, BUY_DEVEL_CARD, &resval, need)) {
1239 		cb_buy_develop();
1240 		return;
1241 	}
1242 
1243 	/* if we have a lot of cards see if we can trade anything */
1244 	if (num_assets(assets) >= 3) {
1245 		if (can_trade_maritime()) {
1246 			gint amount;
1247 			Resource trade_away, want_resource;
1248 			if (will_do_maritime_trade
1249 			    (assets, &resval, &amount, &trade_away,
1250 			     &want_resource)) {
1251 				cb_maritime(amount, trade_away,
1252 					    want_resource);
1253 				return;
1254 			}
1255 		}
1256 	}
1257 
1258 	/* play development cards */
1259 	if (can_play_any_develop()) {
1260 		const Deck *deck = get_devel_deck();
1261 		gint num_victory_cards = 0;
1262 		gint victory_point_target, my_points;
1263 
1264 		for (i = 0; i < deck_count(deck); i++) {
1265 			DevelType cardtype = deck_get_guint(deck, i);
1266 
1267 			/* if it's a vp card, note this for later */
1268 			if (is_victory_card(cardtype)) {
1269 				num_victory_cards++;
1270 				continue;
1271 			}
1272 
1273 			/* can't play card we just bought */
1274 			if (can_play_develop(i)) {
1275 				if (will_play_development_card(cardtype)) {
1276 					cb_play_develop(i);
1277 					return;
1278 				}
1279 			}
1280 		}
1281 
1282 		/* if we have enough victory cards to win, then play them */
1283 		victory_point_target = game_victory_points();
1284 		my_points = player_get_score(my_player_num());
1285 		if (num_victory_cards + my_points >= victory_point_target) {
1286 			for (i = 0; i < deck_count(deck); i++) {
1287 				DevelType cardtype =
1288 				    deck_get_guint(deck, i);
1289 
1290 				if (is_victory_card(cardtype)) {
1291 					cb_play_develop(i);
1292 					return;
1293 				}
1294 			}
1295 		}
1296 	}
1297 	cb_end_turn();
1298 }
1299 
score_node_hurt_opponents(Node * node)1300 static float score_node_hurt_opponents(Node * node)
1301 {
1302 	/* no building there */
1303 	if (node->owner == -1)
1304 		return 0;
1305 
1306 	/* do I have a house there? */
1307 	if (my_player_num() == node->owner) {
1308 		if (node->type == BUILD_SETTLEMENT) {
1309 			return -2.0;
1310 		} else {
1311 			return -3.5;
1312 		}
1313 	}
1314 
1315 	/* opponent has house there */
1316 	if (node->type == BUILD_SETTLEMENT) {
1317 		return 1.5;
1318 	} else {
1319 		return 2.5;
1320 	}
1321 }
1322 
1323 /*
1324  * How much does putting the robber here hurt my opponents?
1325  */
score_hex_hurt_opponents(Hex * hex)1326 static float score_hex_hurt_opponents(Hex * hex)
1327 {
1328 	int i;
1329 	float score = 0;
1330 
1331 	if (hex == NULL)
1332 		return -1000;
1333 
1334 	/* don't move the pirate. */
1335 	if (!can_robber_or_pirate_be_moved(hex)
1336 	    || hex->terrain == SEA_TERRAIN)
1337 		return -1000;
1338 
1339 	for (i = 0; i < 6; i++) {
1340 		score += score_node_hurt_opponents(hex->nodes[i]);
1341 	}
1342 
1343 	/* multiply by resource/roll value */
1344 	score *= default_score_hex(hex);
1345 
1346 	return score;
1347 }
1348 
1349 /*
1350  * Find the best (worst for opponents) place to put the robber
1351  *
1352  */
greedy_place_robber(void)1353 static void greedy_place_robber(void)
1354 {
1355 	int i, j;
1356 	float bestscore = -1000;
1357 	Hex *besthex = NULL;
1358 	Map *map = callbacks.get_map();
1359 
1360 	ai_wait();
1361 	for (i = 0; i < map->x_size; i++) {
1362 		for (j = 0; j < map->y_size; j++) {
1363 			Hex *hex = map_hex(map, i, j);
1364 			float score = score_hex_hurt_opponents(hex);
1365 
1366 			if (score > bestscore) {
1367 				bestscore = score;
1368 				besthex = hex;
1369 			}
1370 
1371 		}
1372 	}
1373 	cb_place_robber(besthex);
1374 }
1375 
greedy_steal_building(void)1376 static void greedy_steal_building(void)
1377 {
1378 	int i;
1379 	int victim = -1;
1380 	int victim_resources = -1;
1381 	Hex *hex = map_robber_hex(callbacks.get_map());
1382 
1383 	/* which opponent to steal from */
1384 	for (i = 0; i < 6; i++) {
1385 		int numres = 0;
1386 
1387 		/* if has owner (and isn't me) */
1388 		if ((hex->nodes[i]->owner != -1) &&
1389 		    (hex->nodes[i]->owner != my_player_num())) {
1390 
1391 			numres =
1392 			    player_get_num_resource(hex->nodes[i]->owner);
1393 		}
1394 
1395 		if (numres > victim_resources) {
1396 			victim = hex->nodes[i]->owner;
1397 			victim_resources = numres;
1398 		}
1399 	}
1400 	cb_rob(victim);
1401 	ai_chat_self_moved_robber();
1402 }
1403 
1404 /*
1405  * A devel card game us two free roads. let's build them
1406  *
1407  */
1408 
greedy_free_road(void)1409 static void greedy_free_road(void)
1410 {
1411 	Edge *e;
1412 	resource_values_t resval;
1413 
1414 	reevaluate_resources(&resval);
1415 
1416 	e = best_road_spot(&resval);
1417 
1418 	if (e == NULL) {
1419 		e = best_road_to_road(&resval);
1420 	}
1421 
1422 	if (e == NULL) {
1423 		e = find_random_road();
1424 	}
1425 
1426 	if (e != NULL) {
1427 
1428 		cb_build_road(e);
1429 		return;
1430 
1431 	} else {
1432 		log_message(MSG_ERROR,
1433 			    "unable to find spot to build free road\n");
1434 		cb_disconnect();
1435 	}
1436 }
1437 
1438 /*
1439  * We played a year of plenty card. pick the two resources we most need
1440  */
1441 
greedy_year_of_plenty(const gint bank[NO_RESOURCE])1442 static void greedy_year_of_plenty(const gint bank[NO_RESOURCE])
1443 {
1444 	gint want[NO_RESOURCE];
1445 	gint assets[NO_RESOURCE];
1446 	int i;
1447 	int r1, r2;
1448 	resource_values_t resval;
1449 
1450 	ai_wait();
1451 	for (i = 0; i < NO_RESOURCE; i++) {
1452 		want[i] = 0;
1453 		assets[i] = resource_asset(i);
1454 	}
1455 
1456 	/* what two resources do we desire most */
1457 	reevaluate_resources(&resval);
1458 
1459 	r1 = resource_desire(assets, &resval);
1460 
1461 	/* If we don't desire anything anymore, ask for a road.
1462 	 * This happens if we have at least 2 of each resource
1463 	 */
1464 	if (r1 == NO_RESOURCE)
1465 		r1 = BRICK_RESOURCE;
1466 
1467 	assets[r1]++;
1468 
1469 	reevaluate_resources(&resval);
1470 
1471 	r2 = resource_desire(assets, &resval);
1472 
1473 	if (r2 == NO_RESOURCE)
1474 		r2 = LUMBER_RESOURCE;
1475 
1476 	assets[r1]--;
1477 
1478 	/* If we want something that is not in the bank, request something else */
1479 	/* WARNING: This code can cause a lockup if the bank is empty, but
1480 	 * then the year of plenty must not have been playable */
1481 	while (bank[r1] < 1)
1482 		r1 = (r1 + 1) % NO_RESOURCE;
1483 	while (bank[r2] < (r1 == r2 ? 2 : 1))
1484 		r2 = (r2 + 1) % NO_RESOURCE;
1485 
1486 	want[r1]++;
1487 	want[r2]++;
1488 
1489 	cb_choose_plenty(want);
1490 }
1491 
1492 /*
1493  * We played a monopoly card.  Pick a resource
1494  */
1495 
other_players_have(Resource res)1496 static gint other_players_have(Resource res)
1497 {
1498 	return game_resources() - get_bank()[res] - resource_asset(res);
1499 }
1500 
monopoly_wildcard_value(const resource_values_t * resval,const gint assets[NO_RESOURCE],gint resource)1501 static float monopoly_wildcard_value(const resource_values_t * resval,
1502 				     const gint assets[NO_RESOURCE],
1503 				     gint resource)
1504 {
1505 	return (float) (other_players_have(resource) +
1506 			assets[resource]) / resval->ports[resource];
1507 }
1508 
1509 /** Determine the best resource to get with a monopoly card.
1510  * @return the resource
1511 */
determine_monopoly_resource(void)1512 static gint determine_monopoly_resource(void)
1513 {
1514 	gint assets[NO_RESOURCE];
1515 	int i;
1516 	gint most_desired;
1517 	gint most_wildcards;
1518 	resource_values_t resval;
1519 
1520 	for (i = 0; i < NO_RESOURCE; i++)
1521 		assets[i] = resource_asset(i);
1522 
1523 	/* order resources by preference */
1524 	reevaluate_resources(&resval);
1525 
1526 	/* try to get something we need */
1527 	most_desired = resource_desire(assets, &resval);
1528 
1529 	/* try to get the optimal maritime trade. */
1530 	most_wildcards = 0;
1531 	for (i = 1; i < NO_RESOURCE; i++) {
1532 		if (monopoly_wildcard_value(&resval, assets, i) >
1533 		    monopoly_wildcard_value(&resval, assets,
1534 					    most_wildcards))
1535 			most_wildcards = i;
1536 	}
1537 
1538 	/* choose the best */
1539 	if (most_desired != NO_RESOURCE
1540 	    && other_players_have(most_desired) >
1541 	    monopoly_wildcard_value(&resval, assets, most_wildcards)) {
1542 		return most_desired;
1543 	} else if (monopoly_wildcard_value(&resval, assets, most_wildcards)
1544 		   >= 1.0) {
1545 		return most_wildcards;
1546 	} else {
1547 		return NO_RESOURCE;
1548 	}
1549 }
1550 
greedy_monopoly(void)1551 static void greedy_monopoly(void)
1552 {
1553 	ai_wait();
1554 	cb_choose_monopoly(determine_monopoly_resource());
1555 }
1556 
1557 /*
1558  * Of these resources which is least valuable to us
1559  *
1560  * Get rid of the one we have the most of
1561  * if there's a tie let resource_values_t settle it
1562  */
1563 
least_valuable(gint assets[NO_RESOURCE],const resource_values_t * resval)1564 static int least_valuable(gint assets[NO_RESOURCE],
1565 			  const resource_values_t * resval)
1566 {
1567 	int ret = NO_RESOURCE;
1568 	int res;
1569 	int most = 0;
1570 	float mostval = -1;
1571 
1572 	for (res = 0; res < NO_RESOURCE; res++) {
1573 		if (assets[res] > most) {
1574 			if (resval->value[res] > mostval) {
1575 				ret = res;
1576 				most = assets[res];
1577 				mostval = resval->value[res];
1578 			}
1579 		}
1580 	}
1581 
1582 	return ret;
1583 }
1584 
1585 /*
1586  * Which resource do we desire the least?
1587  */
1588 
resource_desire_least(gint my_assets[NO_RESOURCE],const resource_values_t * resval)1589 static int resource_desire_least(gint my_assets[NO_RESOURCE],
1590 				 const resource_values_t * resval)
1591 {
1592 	BuyType bt;
1593 	int res;
1594 	gint assets[NO_RESOURCE];
1595 	gint need[NO_RESOURCE];
1596 	int leastval;
1597 
1598 	/* make copy of what we got */
1599 	for (res = 0; res != NO_RESOURCE; res++) {
1600 		assets[res] = my_assets[res];
1601 	}
1602 
1603 	/* eliminate things we need to build stuff */
1604 	for (bt = 0; bt < BUY_LAST; bt++) {
1605 		if (should_buy(assets, bt, resval, need)) {
1606 			cost_buy(cost_of(bt), assets);
1607 		}
1608 	}
1609 
1610 	/* of what's left what do do we care for least */
1611 	leastval = least_valuable(assets, resval);
1612 	if (leastval != NO_RESOURCE)
1613 		return leastval;
1614 
1615 	/* otherwise least valuable of what we have in total */
1616 	leastval = least_valuable(my_assets, resval);
1617 	if (leastval != NO_RESOURCE)
1618 		return leastval;
1619 
1620 	/* last resort just pick something */
1621 	for (res = 0; res < NO_RESOURCE; res++) {
1622 		if (my_assets[res] > 0)
1623 			return res;
1624 	}
1625 
1626 	/* Should never get here */
1627 	g_assert_not_reached();
1628 	return 0;
1629 }
1630 
1631 
1632 /*
1633  * A seven was rolled. we need to discard some resources :(
1634  *
1635  */
greedy_discard(int num)1636 static void greedy_discard(int num)
1637 {
1638 	int res;
1639 	gint todiscard[NO_RESOURCE];
1640 	int i;
1641 	resource_values_t resval;
1642 	gint assets[NO_RESOURCE];
1643 
1644 	/* zero out */
1645 	for (res = 0; res != NO_RESOURCE; res++) {
1646 		todiscard[res] = 0;
1647 		assets[res] = resource_asset(res);
1648 	}
1649 
1650 	for (i = 0; i < num; i++) {
1651 
1652 		reevaluate_resources(&resval);
1653 
1654 		res = resource_desire_least(assets, &resval);
1655 
1656 		todiscard[res]++;
1657 		assets[res]--;
1658 	}
1659 
1660 	cb_discard(todiscard);
1661 }
1662 
1663 /*
1664  * Domestic Trade
1665  *
1666  */
quote_next_num(void)1667 static int quote_next_num(void)
1668 {
1669 	return quote_num++;
1670 }
1671 
greedy_quote_start(void)1672 static void greedy_quote_start(void)
1673 {
1674 	quote_num = 0;
1675 }
1676 
trade_desired(gint assets[NO_RESOURCE],gint give,gint take,gboolean free_offer)1677 static int trade_desired(gint assets[NO_RESOURCE], gint give, gint take,
1678 			 gboolean free_offer)
1679 {
1680 	int i, n;
1681 	int res = NO_RESOURCE;
1682 	resource_values_t resval;
1683 	float value = 0.0;
1684 	gint need[NO_RESOURCE];
1685 
1686 	if (!free_offer) {
1687 		/* don't give away cards we have only once */
1688 		if (assets[give] <= 1) {
1689 			return 0;
1690 		}
1691 
1692 		/* make it as if we don't have what we're trading away */
1693 		assets[give] -= 1;
1694 	}
1695 
1696 	reevaluate_resources(&resval);
1697 	for (n = 1; n <= 3; ++n) {
1698 		/* do i need something more for something? */
1699 		if (!should_buy(assets, BUY_CITY, &resval, need)) {
1700 			if ((res = which_resource(need)) == take
1701 			    && need[res] == n)
1702 				break;
1703 		}
1704 		if (!should_buy(assets, BUY_SETTLEMENT, &resval, need)) {
1705 			if ((res = which_resource(need)) == take
1706 			    && need[res] == n)
1707 				break;
1708 		}
1709 		if (!should_buy(assets, BUY_ROAD, &resval, need)) {
1710 			if ((res = which_resource(need)) == take
1711 			    && need[res] == n)
1712 				break;
1713 		}
1714 		if (!should_buy(assets, BUY_DEVEL_CARD, &resval, need)) {
1715 			if ((res = which_resource(need)) == take
1716 			    && need[res] == n)
1717 				break;
1718 		}
1719 	}
1720 	if (!free_offer)
1721 		assets[give] += 1;
1722 	if (n <= 3)
1723 		return n;
1724 
1725 	/* desire the one we don't produce the most */
1726 	for (i = 0; i < NO_RESOURCE; i++) {
1727 		if ((resval.value[i] > value) && (assets[i] < 2)) {
1728 			res = i;
1729 			value = resval.value[i];
1730 		}
1731 	}
1732 
1733 	if (res == take && assets[give] > 2) {
1734 		return 1;
1735 	}
1736 
1737 	return 0;
1738 }
1739 
greedy_consider_quote(G_GNUC_UNUSED gint partner,gint we_receive[NO_RESOURCE],gint we_supply[NO_RESOURCE])1740 static void greedy_consider_quote(G_GNUC_UNUSED gint partner,
1741 				  gint we_receive[NO_RESOURCE],
1742 				  gint we_supply[NO_RESOURCE])
1743 {
1744 	gint give, take, ntake;
1745 	gint give_res[NO_RESOURCE], take_res[NO_RESOURCE],
1746 	    my_assets[NO_RESOURCE];
1747 	gint i;
1748 	gboolean free_offer;
1749 
1750 	free_offer = TRUE;
1751 	for (i = 0; i < NO_RESOURCE; ++i) {
1752 		my_assets[i] = resource_asset(i);
1753 		free_offer &= we_supply[i] == 0;
1754 	}
1755 
1756 	for (give = 0; give < NO_RESOURCE; give++) {
1757 		/* A free offer is always accepted */
1758 		if (!free_offer) {
1759 			if (we_supply[give] == 0)
1760 				continue;
1761 			if (my_assets[give] == 0)
1762 				continue;
1763 		}
1764 		for (take = 0; take < NO_RESOURCE; take++) {
1765 			/* Don't do stupid offers */
1766 			if (!free_offer && take == give)
1767 				continue;
1768 			if (we_receive[take] == 0)
1769 				continue;
1770 			if ((ntake =
1771 			     trade_desired(my_assets, give, take,
1772 					   free_offer)) > 0)
1773 				goto doquote;
1774 		}
1775 	}
1776 
1777 	/* Do not decline anything for free, just take it all */
1778 	if (free_offer) {
1779 		cb_quote(quote_next_num(), we_supply, we_receive);
1780 		log_message(MSG_INFO, "Taking the whole free offer.\n");
1781 		return;
1782 	}
1783 
1784 	log_message(MSG_INFO, _("Rejecting trade.\n"));
1785 	cb_end_quote();
1786 	return;
1787 
1788       doquote:
1789 	for (i = 0; i < NO_RESOURCE; ++i) {
1790 		give_res[i] = (give == i && !free_offer) ? 1 : 0;
1791 		take_res[i] = take == i ? ntake : 0;
1792 	}
1793 	cb_quote(quote_next_num(), give_res, take_res);
1794 	log_message(MSG_INFO, "Quoting.\n");
1795 }
1796 
greedy_setup(gint num_settlements,gint num_roads)1797 static void greedy_setup(gint num_settlements, gint num_roads)
1798 {
1799 	ai_wait();
1800 	if (num_settlements > 0)
1801 		greedy_setup_house();
1802 	else if (num_roads > 0)
1803 		greedy_setup_road();
1804 	else
1805 		cb_end_turn();
1806 }
1807 
greedy_roadbuilding(gint num_roads)1808 static void greedy_roadbuilding(gint num_roads)
1809 {
1810 	ai_wait();
1811 	if (num_roads > 0)
1812 		greedy_free_road();
1813 	else
1814 		cb_end_turn();
1815 }
1816 
greedy_discard_add(gint player_num,gint discard_num)1817 static void greedy_discard_add(gint player_num, gint discard_num)
1818 {
1819 	ai_chat_discard(player_num, discard_num);
1820 	if (player_num == my_player_num()) {
1821 		ai_wait();
1822 		greedy_discard(discard_num);
1823 	}
1824 }
1825 
greedy_gold_choose(gint gold_num,const gint * bank)1826 static void greedy_gold_choose(gint gold_num, const gint * bank)
1827 {
1828 	resource_values_t resval;
1829 	gint assets[NO_RESOURCE];
1830 	gint want[NO_RESOURCE];
1831 	gint my_bank[NO_RESOURCE];
1832 	gint i;
1833 	int r1;
1834 
1835 	for (i = 0; i < NO_RESOURCE; i++) {
1836 		want[i] = 0;
1837 		assets[i] = resource_asset(i);
1838 		my_bank[i] = bank[i];
1839 	}
1840 
1841 	for (i = 0; i < gold_num; i++) {
1842 		gint j;
1843 
1844 		reevaluate_resources(&resval);
1845 
1846 		/* If the bank has been emptied, don't desire it */
1847 		for (j = 0; j < NO_RESOURCE; j++) {
1848 			if (my_bank[j] == 0) {
1849 				resval.value[j] = 0;
1850 			}
1851 		}
1852 
1853 		r1 = resource_desire(assets, &resval);
1854 		/* If we don't want anything, start emptying the bank */
1855 		if (r1 == NO_RESOURCE) {
1856 			r1 = 0;
1857 			/* Potential deadlock, but bank is always full enough */
1858 			while (my_bank[r1] == 0)
1859 				r1++;
1860 		}
1861 		want[r1]++;
1862 		assets[r1]++;
1863 		my_bank[r1]--;
1864 	}
1865 	cb_choose_gold(want);
1866 }
1867 
greedy_init(void)1868 void greedy_init(void)
1869 {
1870 	callbacks.setup = &greedy_setup;
1871 	callbacks.turn = &greedy_turn;
1872 	callbacks.robber = &greedy_place_robber;
1873 	callbacks.steal_building = &greedy_steal_building;
1874 	callbacks.roadbuilding = &greedy_roadbuilding;
1875 	callbacks.plenty = &greedy_year_of_plenty;
1876 	callbacks.monopoly = &greedy_monopoly;
1877 	callbacks.discard_add = &greedy_discard_add;
1878 	callbacks.quote_start = &greedy_quote_start;
1879 	callbacks.quote = &greedy_consider_quote;
1880 	callbacks.gold_choose = &greedy_gold_choose;
1881 }
1882