treewars/graph.cpp

111 lines
2.1 KiB
C++
Raw Normal View History

#include "graph.h"
#include "debug.h"
#include <cmath>
using std::abs;
Graph::Graph()
{
current_vertex = NULL;
}
Graph::~Graph()
{
for (list<Vertex*>::iterator cursor = vertices.begin();
cursor != vertices.end(); cursor++)
{
Vertex* v = *cursor;
delete v;
}
}
bool Graph::vertex_present(int x, int y, int size)
{
int delta = size / 2;
int x_min = x - delta;
int x_max = x + delta;
int y_min = y - delta;
int y_max = y + delta;
for (list<Vertex*>::iterator cursor = vertices.begin();
cursor != vertices.end(); cursor++)
{
Vertex v = *(*cursor);
if (((x_min >= v.x_min && x_min <= v.x_max) &&
((y_min >= v.y_min && y_min <= v.y_max) ||
(y_max >= v.y_min && y_max <= v.y_max))) ||
((x_max >= v.x_min && x_max <= v.x_max) &&
((y_min >= v.y_min && y_min <= v.y_max) ||
(y_max >= v.y_min && y_max <= v.y_max))))
{
#ifdef DEBUG
cerr << "debug: Graph::vertex_present(): vertex present at x=" << v.x << ", y=" << v.y << "\n";
#endif
return true;
}
}
return false;
}
void Graph::do_vertex(int x, int y, int size)
{
if (vertex_present(x, y, size)) select_vertex(x, y);
else add_vertex(x, y, size);
}
void Graph::select_vertex(int x, int y)
{
for (list<Vertex*>::iterator cursor = vertices.begin();
cursor != vertices.end(); cursor++)
{
Vertex* v = *cursor;
if (x >= v->x_min && x <= v->x_max && y >= v->y_min && y <= v->y_max)
{
current_vertex = v;
return;
}
}
}
void Graph::add_vertex(int x, int y, int size)
{
Vertex* v = new Vertex();
v->x = x;
v->y = y;
v->x_min = x - size/2;
v->x_max = x + size/2;
v->y_min = y - size/2;
v->y_max = y + size/2;
if (vertex_present(v->x, v->y, 25)) return;
vertices.push_back(v);
if (current_vertex == NULL)
{
current_vertex = v;
return;
}
Edge e;
e.a = current_vertex;
e.b = v;
edges.push_back(e);
current_vertex = v;
}
float Vertex::distance(Vertex a, Vertex b)
{
float dy = abs(static_cast<float>(b.y) - a.y);
float dx = abs(static_cast<float>(b.x) - a.x);
return sqrt(dy*dy + dx*dx);
}