/*
 *    Copyright (C) 1987, 1988 Chuck Simmons
 * 
 * See the file COPYING, distributed with empire, for restriction
 * and warranty information.
 */

/*
compmove.c -- Make a move for the computer. 

For each move the user wants us to make, we do the following:

    1)  Handle city production;
    2)  Move computer's pieces;
    3)  Check to see if the game is over.
*/

#include <string.h>
#include "empire.h"
#include "extern.h"

static view_map_t emap[MAP_SIZE]; /* pruned explore map */

bool load_army(piece_info_t *obj);
bool lake( loc_t loc );
bool overproduced( city_info_t *cityp, int *city_count );
bool nearby_load( piece_info_t *obj, loc_t loc );
count_t nearby_count( loc_t loc );
void move_objective(piece_info_t *obj,path_map_t pathmap[],loc_t new_loc,char *adj_list);
void comp_set_prod(city_info_t *, int);
void comp_set_needed(city_info_t *, int *, bool, bool);
void comp_prod(city_info_t *, bool);

void
comp_move(int nmoves) 
{
    void do_cities(void), do_pieces(void), check_endgame(void);

    int i;
    piece_info_t *obj;

    /* Update our view of the world. */
	
    for (i = 0; i < NUM_OBJECTS; i++)
	for (obj = game.comp_obj[i]; obj != NULL; obj = obj->piece_link.next)
	    scan (game.comp_map, obj->loc); /* refresh comp's view of world */

    for (i = 1; i <= nmoves; i++) { /* for each move we get... */
	comment ("Thinking...");

	(void) memcpy (emap, game.comp_map, MAP_SIZE * sizeof (view_map_t));
	vmap_prune_explore_locs (emap);
	
	do_cities (); /* handle city production */
	do_pieces (); /* move pieces */
		
	if (game.save_movie) save_movie_screen ();
	check_endgame (); /* see if game is over */

	topini ();
	(void) redisplay ();
    }
}

/*
Handle city production.  First, we set production for new cities.
Then we produce new pieces.  After producing a piece, we will see
if we should change our production.

Our goals for city production are first, not to change production
while something is in the process of being built.  Second, we attempt
to have enough city producing armies on a continent to counter any
threat on the continent, and to adequately explore and control the
continent.  Third, we attempt to always have at least one transport
producer.  Fourth, we attempt to maintain a good ratio between the
number of producers we have of each type of piece.  Fifth, we never
build carriers, as we don't have a good strategy for moving these.
*/

void
do_cities(void)
{
    int i;
    bool is_lake;

    for (i = 0; i < NUM_CITY; i++) /* new production */
	if (game.city[i].owner == COMP) {
	    scan (game.comp_map, game.city[i].loc);

	    if (game.city[i].prod == NOPIECE)
		comp_prod (&game.city[i], lake (game.city[i].loc));
	}
    for (i = 0; i < NUM_CITY; i++) /* produce and change */
	if (game.city[i].owner == COMP) {
	    is_lake = lake (game.city[i].loc);
	    if (game.city[i].work++ >= (long)piece_attr[(int)game.city[i].prod].build_time) {
		produce (&game.city[i]);
		comp_prod (&game.city[i], is_lake);
	    }
	    /* don't produce ships in lakes */
	    else if (game.city[i].prod > FIGHTER && game.city[i].prod != SATELLITE && is_lake)
		comp_prod (&game.city[i], is_lake);
	}
}
			
/*
Define ratios for numbers of cities we want producing each object.

Early in the game, we want to produce armies and transports for
rapid expansion.  After a while, we add fighters and pt boats
for exploration.  Later, we add ships of all kinds for control of
the sea.
*/
                                 /* A    F    P    S    D    T    C    B   Z*/
static int ratio1[NUM_OBJECTS] = { 60,   0,  10,   0,   0,  20,   0,   0,  0};
static int ratio2[NUM_OBJECTS] = { 90,  10,  10,  10,  10,  40,   0,   0,  0};
static int ratio3[NUM_OBJECTS] = {120,  20,  20,  10,  10,  60,  10,  10,  0};
static int ratio4[NUM_OBJECTS] = {150,  30,  30,  20,  20,  70,  10,  10,  0};
static int *ratio;

	
/*
Set city production if necessary.

The algorithm below contains three parts:

1)  Defend continents we own.

2)  Produce a TT and a Satellite.

3)  Meet the ratio requirements given above.
*/

void
comp_prod(city_info_t *cityp, bool is_lake)
{
    int city_count[NUM_OBJECTS]; /* # of cities producing each piece */
    int cont_map[MAP_SIZE];
    int total_cities;
    count_t i;
    int comp_ac;
    city_info_t *p;
    int need_count, interest;
    scan_counts_t counts;

    /* Make sure we have army producers for current continent. */
	
    /* map out city's continent */
    vmap_cont (cont_map, game.comp_map, cityp->loc, MAP_SEA);

    /* count items of interest on the continent */
    counts = vmap_cont_scan (cont_map, game.comp_map);
    comp_ac = 0; /* no army producing computer cities */
	
    for (i = 0; i < MAP_SIZE; i++)
	if (cont_map[i]) { /* for each cell of continent */
	    if (game.comp_map[i].contents == 'X') {
		p = find_city (i);
		ASSERT (p != NULL && p->owner == COMP);
		if (p->prod == ARMY) comp_ac += 1;
	    }
	}
    /* see if anything of interest is on continent */
    interest = (counts.unexplored || counts.user_cities
		|| counts.user_objects[ARMY]
		|| counts.unowned_cities);
	
    /* we want one more army producer than enemy has cities */
    /* and one more if anything of interest on cont */
    need_count = counts.user_cities - comp_ac + interest;
    if (counts.user_cities) need_count += 1;
	
    if (need_count > 0) { /* need an army producer? */
	comp_set_prod (cityp, ARMY);
	return;
    }
	
    /* Produce armies in new cities if there is a city to attack. */
    if (counts.user_cities && cityp->prod == NOPIECE) {
	comp_set_prod (cityp, ARMY);
	return;
    }

    /* Produce a TT and SAT if we don't have one. */
	
    /* count # of cities producing each piece */
    for (i = 0; i < NUM_OBJECTS; i++)
	city_count[i] = 0;
		
    total_cities = 0;
		
    for (i = 0; i < NUM_CITY; i++)
	if (game.city[i].owner == COMP && game.city[i].prod != NOPIECE) {
	    city_count[(int)game.city[i].prod] += 1;
	    total_cities += 1;
	}
    if (total_cities <= 10)
	ratio = ratio1;
    else if (total_cities <= 20)
	ratio = ratio2;
    else if (total_cities <= 30)
	ratio = ratio3;
    else ratio = ratio4;
		
    /* if we have one army producer, and this is it, return */
    if (city_count[ARMY] == 1 && cityp->prod == ARMY) return;
	
    /* first available non-lake becomes a tt producer */
    if (city_count[TRANSPORT] == 0) {
	if (!is_lake) {
	    comp_set_prod (cityp, TRANSPORT);
	    return;
	}
	/* if we have one army producer that is not on a lake, */
	/* produce armies here instead */
	if (city_count[ARMY] == 1) {
	    for (i = 0; i < NUM_CITY; i++)
		if (game.city[i].owner == COMP && game.city[i].prod == ARMY) break;
		
	    if (!lake (game.city[i].loc)) {
		comp_set_prod (cityp, ARMY);
		return;
	    }
	}
    }
#if 0
    /* Now we need a SATELLITE. */
    if (cityp->prod == NOPIECE && city_count[SATELLITE] == 0) {
	comp_set_prod (cityp, SATELLITE);
	return;
    }
    if (cityp->prod == SATELLITE) return;
    /* "The satellites are out tonight." -- Lori Anderson */
#endif
    /* don't change prod from armies if something on continent */
    if (cityp->prod == ARMY && interest) return;
			
    /* Produce armies in new cities if there is a city to attack. */
    if (counts.unowned_cities && cityp->prod == NOPIECE) {
	comp_set_prod (cityp, ARMY);
	return;
    }

    /* Set production to item most needed.  Continents with one
       city and nothing interesting may not produce armies.  We
       set production for unset cities, and change production for
       cities that produce objects for which we have many city producers.
       Ship producers on lakes also get there production changed. */
	
    interest = (counts.comp_cities != 1 || interest);
	
    if (cityp->prod == NOPIECE
	|| (cityp->prod == ARMY && counts.comp_cities == 1)
	|| overproduced (cityp, city_count)
	|| (cityp->prod > FIGHTER && is_lake) )
	comp_set_needed (cityp, city_count, interest, is_lake);
}
	
/*
Set production for a computer city to a given type.  Don't
reset production if it is already correct.
*/

void
comp_set_prod(city_info_t *cityp, int type)
{
    if (cityp->prod == type) return;
	
    pdebug ("Changing city prod at %d from %d to %d\n",loc_disp(cityp->loc), cityp->prod, type);
    cityp->prod = type;
    cityp->work = -(piece_attr[type].build_time / 5);
}

/*
See if a city is producing an object which is being overproduced.
*/

bool
overproduced(city_info_t *cityp, int *city_count)
{
    int i;

    for (i = 0; i < NUM_OBJECTS; i++) {
	/* return true if changing production would improve balance */
	if (i != cityp->prod
	    && ((city_count[(int)cityp->prod] - 1) * ratio[i]
		> (city_count[i] + 1) * ratio[(int)cityp->prod]))
	    return true;
    }
    return false;
}

/*
See if one type of production is needed more than another type.
Return the most-needed type of production.
*/

int
need_more(int *city_count, int prod1, int prod2)
{
	if (city_count[prod1] * ratio[prod2]
		 <= city_count[prod2] * ratio[prod1])
	return (prod1);

	else return (prod2);
}

/*
Figure out the most needed type of production.  We are passed
a flag telling us if armies are ok to produce.
*/

void
comp_set_needed(city_info_t *cityp, int *city_count, bool army_ok, bool is_lake)
{
    int best_prod;
    int prod;

    if (!army_ok) city_count[ARMY] = INFINITY;

    if (is_lake) { /* choose fighter or army */
	comp_set_prod (cityp, need_more (city_count, ARMY, FIGHTER));
	return;
    }
    /* don't choose fighter */
    city_count[FIGHTER] = INFINITY;
	
    best_prod = ARMY; /* default */
    for (prod = 0; prod < NUM_OBJECTS; prod++) {
	best_prod = need_more (city_count, best_prod, prod);
    }
    comp_set_prod (cityp, best_prod);
}

/*
See if a city is on a lake.  We define a lake to be a body of
water (where cities are considered to be water) that does not
touch either an attackable city or unexplored territory.

Be careful, because we use the 'emap'.  This predicts whether
unexplored territory will be land or water.  The prediction should
be helpful, because small bodies of water that enclose unexplored
territory will appear as solid water.  Big bodies of water should
have unexplored territory on the edges.
*/

bool
lake(loc_t loc)
{
    int cont_map[MAP_SIZE];
    scan_counts_t counts;

    vmap_cont (cont_map, emap, loc, MAP_LAND); /* game.real_map lake */
    counts = vmap_cont_scan (cont_map, emap);

    return !(counts.unowned_cities || counts.user_cities || counts.unexplored);
}

/*
Move all computer pieces.
*/

static view_map_t amap[MAP_SIZE]; /* temp view map */
static path_map_t path_map[MAP_SIZE];

void
do_pieces(void) 
{
    void cpiece_move(piece_info_t *);

    int i;
    piece_info_t *obj, *next_obj;

    for (i = 0; i < NUM_OBJECTS; i++) { /* loop through obj lists */
	for (obj = game.comp_obj[move_order[i]]; obj != NULL;
	     obj = next_obj) { /* loop through objs in list */
	    next_obj = obj->piece_link.next;
	    cpiece_move (obj); /* yup; move the object */
	}
    }
}

/*
Move a piece.  We loop until all the moves of a piece are made.  Within
the loop, we find a direction to move that will take us closer to an
objective.
*/

void
cpiece_move(piece_info_t *obj)
{
    void move1(piece_info_t *);

    bool changed_loc;
    int max_hits;

    if (obj->type == SATELLITE) {
	move_sat (obj);
	return;
    }
	
    obj->moved = 0; /* not moved yet */
    changed_loc = false; /* not changed yet */
    max_hits = piece_attr[obj->type].max_hits;

    if (obj->type == FIGHTER) { /* init fighter range */
	city_info_t *cityp = find_city (obj->loc);
	if (cityp != NULL) obj->range = piece_attr[FIGHTER].range;
    }
	
    while (obj->moved < obj_moves (obj)) {
	loc_t saved_loc;
	saved_loc = obj->loc; /* remember starting location */
	move1 (obj);
	if (saved_loc != obj->loc) changed_loc = true;
		
	if (obj->type == FIGHTER && obj->hits > 0) {
	    if (game.comp_map[obj->loc].contents == 'X')
		obj->moved = piece_attr[FIGHTER].speed;
	    else if (obj->range <= 0) {
		pdebug ("Fighter at %d crashed and burned\n", loc_disp(obj->loc));
		ksend ("Fighter at %d crashed and burned\n", loc_disp(obj->loc));
		kill_obj (obj, obj->loc); /* crash & burn */
	    }
	}
    }
    /* if a boat is in port, damaged, and never moved, fix some damage */
    if (obj->hits > 0 /* live piece? */
	&& !changed_loc /* object never changed location? */
	&& obj->type != ARMY && obj->type != FIGHTER /* it is a boat? */
	&& obj->hits != max_hits /* it is damaged? */
	&& game.comp_map[obj->loc].contents == 'X') /* it is in port? */
	obj->hits++; /* fix some damage */
}

/*
Move a piece one square.
*/

void
move1(piece_info_t *obj)
{
    void army_move(piece_info_t *), transport_move(piece_info_t *);
    void fighter_move(piece_info_t *), ship_move(piece_info_t *);

    switch (obj->type) {
    case ARMY: army_move (obj); break;
    case TRANSPORT: transport_move (obj); break;
    case FIGHTER: fighter_move (obj); break;
    default: ship_move (obj); break;
    }
}

/*
Move an army.

This is a multi-step algorithm:

1)  See if there is an object we can attack immediately.
If so, attack it.

2)  Look for the nearest land objective.

3)  If we find an objective reachable by land, figure out
how far away that objective is.  Based on the found objective,
also figure out how close a loadable tt must be to be of
interest.  If the objective is closer than the tt must be,
head towards the objective.

4)  Otherwise, look for the nearest loading tt (or tt producing
city).  If the nearest loading tt is farther than our land objective,
head towards the land objective.

5)  Otherwise, head for the tt.

6)  If we still have no destination and we are in a city,
attempt to leave the city.

7)  Once we have a destination, find the best move toward that
destination.  (If there is no destination, sit around and wait.)
*/

void
army_move(piece_info_t *obj)
{
    loc_t move_away(view_map_t *, loc_t, char *);
    loc_t find_attack(loc_t, char *, char *);
    void make_army_load_map(piece_info_t *, view_map_t *, view_map_t *);
    void make_unload_map(view_map_t *, view_map_t *);
    void make_tt_load_map(view_map_t *, view_map_t *);
    void board_ship(piece_info_t *, path_map_t *, loc_t);
	
    loc_t new_loc;
    path_map_t path_map2[MAP_SIZE];
    int cross_cost = 0; /* cost to enter water */
	
    obj->func = 0; /* army doesn't want a tt */
    if (vmap_at_sea (game.comp_map, obj->loc)) { /* army can't move? */
	(void) load_army (obj);
	obj->moved = piece_attr[ARMY].speed;
	if (!obj->ship) obj->func = 1; /* load army on ship */
	return;
    }
    if (obj->ship) /* is army on a transport? */
	new_loc = find_attack (obj->loc, army_attack, "+*");
    else new_loc = find_attack (obj->loc, army_attack, ".+*");
		
    if (new_loc != obj->loc) { /* something to attack? */
	attack (obj, new_loc); /* attack it */
	if (game.real_map[new_loc].contents == MAP_SEA /* moved to ocean? */
	    && obj->hits > 0) { /* object still alive? */
	    kill_obj (obj, new_loc);
	    scan (game.user_map, new_loc); /* rescan for user */
	}
	return;
    }
    if (obj->ship) {
	if (obj->ship->func == 0) {
	    if (!load_army (obj)) ABORT; /* load army on best ship */
	    return; /* armies stay on a loading ship */
	}
	make_unload_map (amap, game.comp_map);
	new_loc = vmap_find_wlobj (path_map, amap, obj->loc, &tt_unload);
	move_objective (obj, path_map, new_loc, " ");
	return;
    }

    new_loc = vmap_find_lobj (path_map, game.comp_map, obj->loc, &army_fight);
	
    if (new_loc != obj->loc) { /* something interesting on land? */
	switch (game.comp_map[new_loc].contents) {
	case 'A':
	case 'O':
	    cross_cost = 60; /* high cost if enemy present */
	    break;
	case MAP_CITY:
	    cross_cost = 30; /* medium cost for attackable city */
	    break;
	case ' ':
	    cross_cost = 14; /* low cost for exploring */
	    break;
	default:
	    ABORT;
	}
	cross_cost = path_map[new_loc].cost * 2 - cross_cost;
    }
    else cross_cost = INFINITY;
	
    if (new_loc == obj->loc || cross_cost > 0) {
	loc_t new_loc2;
	/* see if there is something interesting to load */
	make_army_load_map (obj, amap, game.comp_map);
	new_loc2 = vmap_find_lwobj (path_map2, amap, obj->loc, &army_load, cross_cost);
		
	if (new_loc2 != obj->loc) { /* found something? */
	    board_ship (obj, path_map2, new_loc2);
	    return;
	}
    }

    move_objective (obj, path_map, new_loc, " ");
}

/*
Remove pruned explore locs from a view map.
*/

void
unmark_explore_locs(view_map_t *xmap)
{
    count_t i;

    for (i = 0; i < MAP_SIZE; i++)
	if (game.real_map[i].on_board && xmap[i].contents == ' ')
	    xmap[i].contents = emap[i].contents;
}

/*
Make a load map.  We copy the view map and mark each loading
transport and tt producing city with a '$'.
*/

void
make_army_load_map(piece_info_t *obj, view_map_t *xmap, view_map_t *vmap)
{
    piece_info_t *p;
    int i;
	
    (void) memcpy (xmap, vmap, sizeof (view_map_t) * MAP_SIZE);

    /* mark loading transports or cities building transports */
    for (p = game.comp_obj[TRANSPORT]; p; p = p->piece_link.next)
	if (p->func == 0) /* loading tt? */
	    xmap[p->loc].contents = '$';
	
    for (i = 0; i < NUM_CITY; i++)
	if (game.city[i].owner == COMP && game.city[i].prod == TRANSPORT) {
	    if (nearby_load (obj, game.city[i].loc))
		xmap[game.city[i].loc].contents = 'x'; /* army is nearby so it can load */
	    else if (nearby_count (game.city[i].loc) < piece_attr[TRANSPORT].capacity)
		xmap[game.city[i].loc].contents = 'x'; /* city needs armies */
	}
	
    if (game.print_vmap == 'A') print_xzoom (xmap);
}

/* Return true if an army is considered near a location for loading. */

bool
nearby_load(piece_info_t *obj, loc_t loc)
{
	return obj->func == 1 && dist (obj->loc, loc) <= 2;
}
	
/* Return number of nearby armies. */

count_t
nearby_count(loc_t loc)
{
    piece_info_t *obj;
    int count;

    count = 0;
    for (obj = game.comp_obj[ARMY]; obj; obj = obj->piece_link.next) {
	if (nearby_load (obj, loc)) count += 1;
    }
    return count;
}

/* Make load map for a ship. */

void
make_tt_load_map(view_map_t *xmap, view_map_t *vmap)
{
    piece_info_t *p;
	
    (void) memcpy (xmap, vmap, sizeof (view_map_t) * MAP_SIZE);

    /* mark loading armies */
    for (p = game.comp_obj[ARMY]; p; p = p->piece_link.next)
	if (p->func == 1) /* loading army? */
	    xmap[p->loc].contents = '$';
	
    if (game.print_vmap == 'L')
	print_xzoom (xmap);
}
	
/*
Make an unload map.  We copy the view map.  We then create
a continent map.  For each of our cities, we mark out the continent
that city is on.  Then, for each city that we don't own and which
doesn't appear on our continent map, we set that square to a digit.

We want to assign weights to each attackable city.
Cities are more valuable if they are on a continent which
has lots of cities.  Cities are also valuable if either it
will be easy for us to take over the continent, or if we
need to defend that continent from an enemy.

To implement the above, we assign numbers to each city as follows:

a)  if unowned_cities > user_cities && comp_cities == 0
       set number to min (total_cities, 9)

b)  if comp_cities != 0 && user_cities != 0
       set number to min (total_cities, 9)
       
b)  if enemy_cities == 1 && total_cities == 1, set number to 2.
    (( taking the sole enemy city on a continent is as good as
       getting a two city continent ))
       
c)  Any other attackable city is marked with a '0'.
*/

static int owncont_map[MAP_SIZE];
static int tcont_map[MAP_SIZE];

void
make_unload_map(view_map_t *xmap, view_map_t *vmap)
{
    count_t i;
    scan_counts_t counts;

    (void) memcpy (xmap, vmap, sizeof (view_map_t) * MAP_SIZE);
    unmark_explore_locs (xmap);
	
    for (i = 0; i < MAP_SIZE; i++)
	owncont_map[i] = 0; /* nothing marked */

    for (i = 0; i < NUM_CITY; i++)
	if (game.city[i].owner == COMP)
	    vmap_mark_up_cont (owncont_map, xmap, game.city[i].loc, MAP_SEA);

    for (i = 0; i < MAP_SIZE; i++)
	if (strchr ("O*", vmap[i].contents)) {
	    int total_cities;
		
	    vmap_cont (tcont_map, xmap, i, MAP_SEA); /* game.real_map continent */
	    counts = vmap_cont_scan (tcont_map, xmap);
		
	    total_cities = counts.unowned_cities
		+ counts.user_cities
		+ counts.comp_cities;
			     
	    if (total_cities > 9) total_cities = 0;
		
	    if (counts.user_cities && counts.comp_cities)
		xmap[i].contents = '0' + total_cities;

	    else if (counts.unowned_cities > counts.user_cities
		     && counts.comp_cities == 0)
		xmap[i].contents = '0' + total_cities;

	    else if (counts.user_cities == 1 && counts.comp_cities == 0)
		xmap[i].contents = '2';
			
	    else xmap[i].contents = '0';
	}
    if (game.print_vmap == 'U') print_xzoom (xmap);
}

/*
Load an army onto a ship.  First look for an adjacent ship.
If that doesn't work, move to the objective, trying to be
close to the ocean.
*/

void
board_ship(piece_info_t *obj, path_map_t *pmap, loc_t dest)
{
    if (!load_army (obj)) {
	obj->func = 1; /* loading */
	move_objective (obj, pmap, dest, "t.");
    }
}

/*
Look for the most full, non-full transport at a location.
Prefer switching to staying.  If we switch, we force
one of the ships to become more full.
*/

piece_info_t *
find_best_tt(piece_info_t *best, loc_t loc)
{
    piece_info_t *p;

    for (p = game.real_map[loc].objp; p != NULL; p = p->loc_link.next)
	if (p->type == TRANSPORT && obj_capacity (p) > p->count) {
	    if (!best) best = p;
	    else if (p->count >= best->count) best = p;
	}
    return best;
}

/*
Load an army onto the most full non-full ship.
*/

bool
load_army(piece_info_t *obj)
{
    piece_info_t *p;
    int i;

    p = find_best_tt (obj->ship, obj->loc); /* look here first */

    for (i = 0; i < 8; i++) { /* try surrounding squares */
	loc_t x_loc = obj->loc + dir_offset[i];
	if (game.real_map[x_loc].on_board)
	    p = find_best_tt (p, x_loc);

    }
    if (!p) return false; /* no tt to be found */

    if (p->loc == obj->loc) { /* stay in same place */
	obj->moved = piece_attr[ARMY].speed;
    }
    else move_obj (obj, p->loc); /* move to square with ship */

    if (p->ship != obj->ship) { /* reload army to new ship */
	disembark (obj);
	embark (p, obj);
    }
    return true;
}

/*
Return the first location we find adjacent to the current location of
the correct terrain.
*/

loc_t
move_away(view_map_t *vmap, loc_t loc, char *terrain)
{
    int i;

    for (i = 0; i < 8; i++) {
	loc_t new_loc = loc + dir_offset[i];
	if (game.real_map[new_loc].on_board
	    && strchr (terrain, vmap[new_loc].contents))
	    return (new_loc);
    }
    return (loc);
}

/*
Look to see if there is an adjacent object to attack.  We are passed
a location and a list of items we attack sorted in order of most
valuable first.  We look at each surrounding on board location.
If there is an object we can attack, we return the location of the
best of these.
*/

loc_t
find_attack(loc_t loc, char *obj_list, char *terrain)
{
    loc_t best_loc;
    int i, best_val;
    char *p;

    best_loc = loc; /* nothing found yet */
    best_val = INFINITY;
    for (i = 0; i < 8; i++) {
	loc_t new_loc = loc + dir_offset[i];

	if (game.real_map[new_loc].on_board /* can we move here? */
	    && strchr (terrain, game.real_map[new_loc].contents)) {
	    p = strchr (obj_list, game.comp_map[new_loc].contents);
	    if (p != NULL && p - obj_list < best_val) {
		best_val = p - obj_list;
		best_loc = new_loc;
	    }
	}
    }
    return (best_loc);
}

/*
Move a transport.

There are two kinds of transports:  loading and unloading.

Loading transports move toward loading armies.  Unloading
transports move toward attackable cities on unowned continents.

An empty transport is willing to attack adjacent enemy transports.
Transports become 'loading' when empty, and 'unloading' when full.
*/

void
transport_move(piece_info_t *obj)
{
    loc_t new_loc;

    /* empty transports can attack */
    if (obj->count == 0) { /* empty? */
	obj->func = 0; /* transport is loading */
	new_loc = find_attack (obj->loc, tt_attack, ".");
	if (new_loc != obj->loc) { /* something to attack? */
	    attack (obj, new_loc); /* attack it */
	    return;
	}
    }

    if (obj->count == obj_capacity (obj)) /* full? */
	obj->func = 1; /* unloading */

    if (obj->func == 0) { /* loading? */
	make_tt_load_map (amap, game.comp_map);
	new_loc = vmap_find_wlobj (path_map, amap, obj->loc, &tt_load);
		
	if (new_loc == obj->loc) { /* nothing to load? */
	    (void) memcpy (amap, game.comp_map, MAP_SIZE * sizeof (view_map_t));
	    unmark_explore_locs (amap);
	    if (game.print_vmap == 'S') print_xzoom (amap);
	    new_loc = vmap_find_wobj (path_map, amap, obj->loc,&tt_explore);
	}
		
	move_objective (obj, path_map, new_loc, "a ");
    }
    else {
	make_unload_map (amap, game.comp_map);
	new_loc = vmap_find_wlobj (path_map, amap, obj->loc, &tt_unload);
	move_objective (obj, path_map, new_loc, " ");
    }
}

/*
Move a fighter.

1)  See if there is an object we can attack immediately.
If so, attack it.

2)  Otherwise, if fighter is low on fuel, move toward nearest city
if there is one in range.

3)  Otherwise, look for an objective.
*/

void
fighter_move(piece_info_t *obj)
{
    loc_t new_loc;

    new_loc = find_attack (obj->loc, fighter_attack, ".+");
    if (new_loc != obj->loc) { /* something to attack? */
	attack (obj, new_loc); /* attack it */
	return;
    }
    /* return to base if low on fuel */
    if (obj->range <= find_nearest_city (obj->loc, COMP, &new_loc) + 2) {
	if (new_loc != obj->loc)
	    new_loc = vmap_find_dest (path_map, game.comp_map, obj->loc,
				      new_loc, COMP, T_AIR);
    }
    else new_loc = obj->loc;
	
    if (new_loc == obj->loc) { /* no nearby city? */
	new_loc = vmap_find_aobj (path_map, game.comp_map, obj->loc,
				  &fighter_fight);
    }
    move_objective (obj, path_map, new_loc, " ");
}

/*
Move a ship.

Attack anything adjacent.  If nothing adjacent, explore or look for
something to attack.
*/

void
ship_move(piece_info_t *obj)
{
    loc_t new_loc;
    char *adj_list;

    if (obj->hits < piece_attr[obj->type].max_hits) { /* head to port */
	if (game.comp_map[obj->loc].contents == 'X') { /* stay in port */
	    obj->moved = piece_attr[obj->type].speed;
	    return;
	}
	new_loc = vmap_find_wobj (path_map, game.comp_map, obj->loc, &ship_repair);
	adj_list = ".";

    }
    else {
	new_loc = find_attack (obj->loc, ship_attack, ".");
	if (new_loc != obj->loc) { /* something to attack? */
	    attack (obj, new_loc); /* attack it */
	    return;
	}
	/* look for an objective */
	(void) memcpy (amap, game.comp_map, MAP_SIZE * sizeof (view_map_t));
	unmark_explore_locs (amap);
	if (game.print_vmap == 'S') print_xzoom (amap);
		
	new_loc = vmap_find_wobj (path_map, amap, obj->loc,&ship_fight);
	adj_list = ship_fight.objectives;
    }

    move_objective (obj, path_map, new_loc, adj_list);
}

/*
Move to an objective.
*/

void
move_objective(piece_info_t *obj, path_map_t pathmap[], 
		loc_t new_loc, char *adj_list)
{
    char *terrain;
    int d;
    bool reuse; /* true iff we should reuse old game.real_map */
    loc_t old_loc;
    loc_t old_dest;
	
    if (new_loc == obj->loc) {
	obj->moved = piece_attr[obj->type].speed;
	obj->range -= 1;
	pdebug ("No destination found for %d at %d; func=%d\n",	obj->type, loc_disp(obj->loc), obj->func);
	return;
    }
    old_loc = obj->loc; /* remember where we are */
    old_dest = new_loc; /* and where we're going */
	
    d = dist (new_loc, obj->loc);
    reuse = true; /* try to reuse unless we learn otherwise */
	
    if (game.comp_map[new_loc].contents == ' ' && d == 2) { /* are we exploring? */
	vmap_mark_adjacent (pathmap, obj->loc);
	reuse = false;
    }
    else vmap_mark_path (pathmap, game.comp_map, new_loc); /* find routes to destination */
	
    /* path terrain and move terrain may differ */
    switch (obj->type) {
    case ARMY: terrain = "+"; break;
    case FIGHTER: terrain = "+.X"; break;
    default: terrain = ".X"; break;
    }
	
    new_loc = vmap_find_dir (pathmap, game.comp_map, obj->loc,
			     terrain, adj_list);
	
    if (new_loc == obj->loc /* path is blocked? */
	&& (obj->type != ARMY || !obj->ship)) { /* don't unblock armies on a ship */
	vmap_mark_near_path (pathmap, obj->loc);
	reuse = false;
	new_loc = vmap_find_dir (pathmap, game.comp_map, obj->loc,
				 terrain, adj_list);
    }
	
    /* encourage army to leave city */
    if (new_loc == obj->loc && game.real_map[obj->loc].cityp != NULL
	&& obj->type == ARMY) {
	new_loc = move_away (game.comp_map, obj->loc, "+");
	reuse = false;
    }
    if (new_loc == obj->loc) {
	obj->moved = piece_attr[obj->type].speed;
		
	if (obj->type == ARMY && obj->ship) ;
	else pdebug ("Cannot move %d at %d toward objective; func=%d\n", obj->type, loc_disp(obj->loc), obj->func);
    }
    else move_obj (obj, new_loc);
	
    /* Try to make more moves using same path map. */
    if (reuse && obj->moved < obj_moves (obj) && obj->loc != old_dest) {
	char *attack_list;
	/* check for immediate attack */
	switch (obj->type) {
	case FIGHTER:
	    if (game.comp_map[old_dest].contents != 'X' /* watch fuel */
		&& obj->range <= piece_attr[FIGHTER].range / 2)
		return;
	    attack_list = fighter_attack;
	    terrain = "+.";
	    break;
	case ARMY:
	    attack_list = army_attack;
	    if (obj->ship) terrain = "+*";
	    else terrain = "+.*";
	    break;
	case TRANSPORT:
	    terrain = ".*";
	    if (obj->cargo) attack_list = tt_attack;
	    else attack_list = "*O"; /* causes tt to wake up */
	    break;
	default:
	    attack_list = ship_attack;
	    terrain = ".";
	    break;
	}
	if (find_attack (obj->loc, attack_list, terrain) != obj->loc)
	    return;
		
	/* clear old path */
	pathmap[old_loc].terrain = T_UNKNOWN;
	for (d = 0; d < 8; d++) {
	    new_loc = old_loc + dir_offset[d];
	    pathmap[new_loc].terrain = T_UNKNOWN;
	}
	/* pathmap is already marked, but this should work */
	move_objective (obj, pathmap, old_dest, adj_list);
    }
}

/*
Check to see if the game is over.  We count the number of cities
owned by each side.  If either side has no cities and no armies, then
the game is over.  If the computer has less than half as many cities
and armies as the user, then the computer will give up.
*/

void
check_endgame(void)
{
    int nuser_city, ncomp_city;
    int nuser_army, ncomp_army;
    piece_info_t *p;
    int i;
	
    game.date += 1; /* one more turn has passed */
    if (game.win != 0) return; /* we already know game is over */

    nuser_city = 0; /* nothing counted yet */
    ncomp_city = 0;
    nuser_army = 0;
    ncomp_army = 0;
	
    for (i = 0; i < NUM_CITY; i++) {
	if (game.city[i].owner == USER) nuser_city++;
	else if (game.city[i].owner == COMP) ncomp_city++;
    }
	
    for (p = game.user_obj[ARMY]; p != NULL; p = p->piece_link.next)
	nuser_army++;
	
    for (p = game.comp_obj[ARMY]; p != NULL; p = p->piece_link.next)
	ncomp_army++;
		
    if (ncomp_city < nuser_city/3 && ncomp_army < nuser_army/3) {
	clear_screen ();
	prompt ("The computer acknowledges defeat. Do");
	ksend ("The computer acknowledges defeat.");
	error ("you wish to smash the rest of the enemy?");

	if (get_chx() !=  'Y') empend ();
	announce ("\nThe enemy inadvertantly revealed its code used for");
	announce ("\nreceiving battle information. You can display what");
	announce ("\nthey've learned with the ''E'' command.");
	game.resigned = true;
	game.win = ratio_win;
	game.automove = false;
    }
    else if (ncomp_city == 0 && ncomp_army == 0) {
	clear_screen ();
	announce ("The enemy is incapable of defeating you.\n");
	announce ("You are free to rape the empire as you wish.\n");
	announce ("There may be, however, remnants of the enemy fleet\n");
	announce ("to be routed out and destroyed.\n");
	game.win = wipeout_win;
	game.automove = false;
    }
    else if (nuser_city == 0 && nuser_army == 0) {
	clear_screen ();
	announce ("You have been rendered incapable of\n");
	announce ("defeating the rampaging enemy fascists! The\n");
	announce ("empire is lost. If you have any ships left, you\n");
	announce ("may attempt to harass enemy shipping.");
	game.win = 1;
	game.automove = false;
    }
}

/* end */
