# How to create a line in a grid using Bresenham's line algorithm

I want to create a line using Bresenham’s algorithm , but the only line that works is a horizontal line from left to right, lines pointing upwards do not work at all and lines drawn diagonally downwards appear in the wrong places, the more vertical the line, the more the distance between the mouse position changes and the drawn line up to a maximum of 3 cells. This is the link to all relevant code . Main code is this:

``````void lineDrawing()
{
int deltaX = mouseNewCordX - mouseOldCordX, deltaY = mouseNewCordY - mouseOldCordY;

if (abs(deltaY) < abs(deltaX))
{
if (mouseOldCordX > mouseNewCordX)
{
plotLineLow(mouseOldCordX, mouseOldCordY, deltaX, deltaY, gradient, error);
} else
{
plotLineLow(mouseNewCordX, mouseNewCordY, deltaX, deltaY, gradient, error);
}
} else
{
if (mouseOldCordY > mouseNewCordY)
{
plotLineHigh(mouseOldCordX, mouseOldCordY, deltaX, deltaY, gradient, error);
} else
{
plotLineHigh(mouseNewCordX, mouseNewCordY, deltaX, deltaY, gradient, error);
}
}
}

void plotLineLow(int x0, int y0, int deltaX, int deltaY, int gradient, int error)
{
int yIncrease = 1;

if (deltaY < 0)
{
yIncrease = -1;
deltaY = -deltaY;
}

for (int x = mouseOldCordX; x <= mouseNewCordX; x += 1)
{

world[x][y0].state = selectedState;

if (error >= 0)
{
y0 += yIncrease;
error -= (deltaX + deltaX);
}
}
}

void plotLineHigh(int x0, int y0, int deltaX, int deltaY, int gradient, int error)
{
int xIncrease = 1;

if (deltaX < 0)
{
xIncrease = -1;
deltaX = -deltaX;
}

for (int y = mouseOldCordY; y <= mouseNewCordY; y += 1)
{

world[x0][y].state = selectedState;

if (error >= 0)
{
x0 += xIncrease;
error -= (deltaY + deltaY);
}
}
}
``````

I was able to use wikipedia to create a code that works:

``````    void lineDrawing()
{
int xIncrease = mouseOldCordX < mouseNewCordX ? 1 : -1;
int yIncrease = mouseOldCordY < mouseNewCordY ? 1 : -1;
int deltaX =  abs(mouseNewCordX - mouseOldCordX);
int deltaY = -abs(mouseNewCordY - mouseOldCordY);
int error = deltaX + deltaY;

while (true)
{
world[mouseOldCordX][mouseOldCordY].state = selectedState;

if ((mouseOldCordX == mouseNewCordX) && (mouseOldCordY == mouseNewCordY)) break;

int doubleError = 2 * error;

if (doubleError >= deltaY)
{
error += deltaY;
mouseOldCordX += xIncrease;
}

if (doubleError <= deltaX)
{
error += deltaX;
mouseOldCordY += yIncrease;
}
}
}
``````