Code:
#include <stdio.h>
#include <math.h>
#define MAX_RING 6
#define DEG_TO_RAD 0.0174532925
enum {DOWN, DOWN_LEFT, UP_LEFT, UP, UP_RIGHT, DOWN_RIGHT} adjacent;
// Gets the current ring
int GetRing(int pos)
{
static const int rings[MAX_RING] = { 1, 7, 19, 37, 61, 91 };
for(int i=0; i<MAX_RING; i++)
if(pos <= rings[i])
return i;
return -1;
}
void SpiralTo2D(int pos, int *x, int *y)
{
static const int ring_offset[MAX_RING+1]= { 0, 1, 7, 19, 37, 61, 91 };
static const int ring_size[MAX_RING] = { 1, 6, 12, 18, 24, 30 };
int ring = GetRing(pos);
int step = pos - ring_offset[ring];
int sector_size = 360 / ring_size[ring];
int deg = (sector_size * step) - 240;
*x = (int)(sin(deg*DEG_TO_RAD) * ring *10);
*y = (int)(cos(deg*DEG_TO_RAD) * ring *10);
//printf("%2d> x:%lf y:%lf", pos, x, y);
//printf(" ring:%d, step:%d, sector:%d deg:%d\n", ring, step ,sector_size, deg);
}
int GetTile(int pos, const int move)
{
int ring = GetRing(pos);
switch(move)
{
case UP: break;
case DOWN: break;
case DOWN_LEFT: break;
case DOWN_RIGHT: break;
case UP_LEFT: break;
case UP_RIGHT: break;
}
return 1;
}
// Gets next step
int GetNextTile(int location, int target)
{
int l_x, l_y, t_x, t_y; // Location and target co-ords
SpiralTo2D(location, &l_x, &l_y);
SpiralTo2D(target, &t_x, &t_y);
printf("Loaction: %d %d\n", l_x, l_y);
printf("Target: %d %d\n", t_x, t_y);
if(l_x == t_x) // Move up or down only
if(l_y == t_y)
return -1; // Target found!
else if(l_y < t_y)
return GetTile(location, UP); // Tile above
else
return GetTile(location, DOWN); // Tile below
else if(l_x > t_x)// Move left
if(l_y > t_y)
return GetTile(location, DOWN_LEFT);
else
return GetTile(location, UP_LEFT);
else //Move Right
if(l_y > t_y)
return GetTile(location, DOWN_RIGHT);
else
return GetTile(location, UP_RIGHT);
}
int main()
{
int pos = 34;
int target = 2;
GetNextTile(pos, target);
getchar();
return 0;
}