#include "coord.h"
#include "keyboard.h"

int MapCoord::maxX = 64, MapCoord::maxY = 64;

MapCoord::MapCoord(int X, int Y)
{
  x = X; y = Y;
  if (x < 0)
    x = -1*(-x%maxX);
  else
    x = x % maxX;
#ifdef NEWWORLD
  if (y < 0)
    y = 0;
  else if (y > maxY)
    y = maxY;
#else
  if (y < 0)
    y = -1*(-y%maxY);
  else
    y = y % maxY;
#endif
}

MapCoord
MapCoord::down(int n) const
{
  if (n >= 0)
    n = n % maxY;
  else
    n = -1*(-n % maxY);
#ifdef NEWWORLD
  return MapCoord(x, y+n);
#else
  return MapCoord(x, (y+n+maxY) % maxY);
#endif
}

MapCoord
MapCoord::right(int n) const
{
  if (n >= 0)
    n = n % maxX;
  else
    n = -1*(-n % maxX)+maxX;
  return MapCoord((x + n) % maxX, y);
}

int 
MapCoord::valid() const
{
#ifdef NEWWORLD
  return (y >= 0 && y < maxY);
#else
  return 1;
#endif
}

int
MapCoord::move(int key)
{
  x = (x+MoveXDir(key) + maxX) % maxX;
  y = (y+MoveYDir(key) + maxY) % maxY;
  return valid();
}

void
MapCoord::operator++()
{
  x++;
  if (x == maxX)
    {
      x = 0;
      y++;
    }
}

Offset
MapCoord::operator-(MapCoord c) const {
  int dx, dy;
  dx = (x-c.x+3*maxX/2)%maxX - maxX/2;
  dy = (y-c.y+3*maxY/2)%maxY - maxY/2;

  return Offset(dx,dy);
}
