#include "bnc.h"
   /* 
    * 1 porte-avions (6 cases)
    * 1 croiseur   (4 cases)
    * 1 contre-torpilleur (3 cases)
    * 1 sous-marin (3 cases)
    * 1 torpilleur (2 cases)
    */
char *code = ".X~#+o";
int force[NB] = { 2, 2, 3, 3, 4, 6 };

int trial = 0;

int ok(int i, int j)
{
    if (i < 0 || i >= DIM || j < 0 || j >= DIM)
	return 0;
    return 1;
}

int accept(int x, int y, int X, int Y, grille * p)
{
    int i, j;
    for (i = x; i <= X; i++)
	for (j = y; j <= Y; j++)
	    if ( ok( i, j) )
		if (p->num[i][j] != 0)
		    return 0;
    return 1;
}

void place(int n, int f, grille * g)
{
    int x, y, z;
    while (1) {
	x = random() % DIM;
	y = random() % DIM;
	if (random() & 1) {
	    // horizontal
	    if (y + f < DIM+1 && accept(x - 1, y - 1, x + 1, y + f, g)) {
		for (z = y; z < y + f; z++)
		    g->num[x][z] = n;
		return;
	    }
	} else {
	    // vertical
	    if (x + f < DIM+1 && accept(x - 1, y - 1, x + f, y + 1, g)) {
		for (z = x; z < x + f; z++)
		    g->num[z][y] = n;
		return;
	    }
	}
    }
}

void init(grille * x, char *nom)
{
    int i, j, n;
    strcpy(x->nom, nom);
    for (i = 0; i < DIM; i++)
	for (j = 0; j < DIM; j++) {
	    x->tir[i][j] = 0;
	    x->num[i][j] = 0;
	    x->adv[i][j] = NIL;
	}
    x->vie = 0;
    for (n = NB - 1; n >= 0; n--) {
	place(n + 1, force[n], x);
	x->val[n] = force[n];
	x->vie += force[n];
    }
}

void print(grille x)
{
    int i, j;
    int car;
    printf("\n\n%-8s : %d", x.nom, x.vie);
    
    printf("\n     ");
    for (j = 0; j < DIM; j++)
	printf(" %c ", j + 'A');
    printf("      ");
    for (j = 0; j < DIM; j++)
	printf(" %c ", j + 'A');
    for (i = 0; i < DIM; i++) {
	printf("\n| %d |", i);
	for (j = 0; j < DIM; j++) {
	    car = '.';
	    if (x.tir[i][j]) {
		if (x.num[i][j] != 0)
		    car = 'X';
		else
		    car = '+';
	    } else if (x.num[i][j] != 0)
		car = '0' + x.num[i][j];
	    printf(" %c ", car);
	}
	printf(" | %d |", i);
	for (j = 0; j < DIM; j++) {
	    car = code[x.adv[i][j]];
	    printf(" %c ", car);
	}
    }
}


int attaque(int i, int j, grille * y)
// resultat du tir en (i,j) sur y
{
    if ( y->tir[i][j] ) 
	return DEJAVU; 
    y->tir[i][j] = 1;
    if ( y->num[i][j] == 0 ) 
	return EAU;
    y->val[y->num[i][j] - 1]--;
    y->vie--;
    if (y->val[y->num[i][j] - 1] )
        return TOUCHE;
    return COULE;
}
