#include "misc.hh"


bool operator < (const Position &a, const Position &b)
{
    if (a.x == b.x)
        return a.y < b.y;
    return a.x < b.x;
}

bool operator != (const Position &a, const Position &b)
{
    return a.x != b.x && a.y != b.y;
}

bool Valide(Position position)
{
    return (position.x >= 0 && position.x < TAILLE_TERRAIN)
        && (position.y >= 0 && position.y < TAILLE_TERRAIN);
}

//TODO: Réécrire une version itérée de cette merde
vector<Position> Alentours(Position centre, int rayon)
{
    Position a, b;
    vector<Position> retour;
    
    a = b = centre;
    a.x += rayon;
    b.y += rayon;
    for (; a != b; a.x--, a.y++)
        if (Valide(a))
            retour.push_back(a);
    
    a = b = centre;
    a.y += rayon;
    b.x -= rayon;
    for (; a != b; a.x--, a.y--)
        if (Valide(a))
            retour.push_back(a);

    a = b = centre;
    a.x -= rayon;
    b.y -= rayon;
    for (; a != b; a.x++, a.y--)
        if (Valide(a))
            retour.push_back(a);

    a = b = centre;
    a.y -= rayon;
    b.x += rayon;
    for (; a != b; a.x--, a.y++)
        if (Valide(a))
            retour.push_back(a);

    return retour;
}

//TODO: Rendre moins MOSH cette fonction
vector<Position> Voisins(Position position)
{
    Position delta[4] = {{ 0, 1}, {1,  0},
                         {-1, 0}, {0, -1}};
    vector<Position> retour;
    
    for (int index; index < 4; index++)
    {
        Position voisin = position;
        
        voisin.x += delta[index].x, voisin.y += delta[index].y;
        if (Valide(voisin))
            retour.push_back(voisin);
    }
    return retour;
}

int Distance_Carre(Position a, Position b)
{
    return (b.x - a.x) * (b.x - a.x)
         + (b.y - a.y) * (b.y - a.y);
}


Position Plus_Proche(vector<Position> positions, Position position)
{
    int debut = 0, fin = positions.size() - 1;
    
    while (debut < fin)
    {
        int index = (debut + fin + 1) / 2;
        
        if (position < positions[index])
            fin = index - 1;
        else
            debut = index;
    }
    return positions[debut];
}

