Drawing a line between 2 points in a console
Mar 13, 2009 at 5:36am UTC
Looking at a function helios remade here (
http://www.cplusplus.com/forum/beginner/8702/ ) I quickly threw this together and was wondering if it's possible in a console program to just draw '.' making a line between these two points. I know this is a basic question but I'm not to sure how to.
Thanks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <stdio.h>
#include <cmath>
double cal_distance(double d_x1, double d_x2, double d_y1, double d_y2)
{
return sqrt(pow(d_x2 - d_x1,2)+pow(d_y2 - d_y1,2));
}
struct Object
{
double y, x;
};
void main()
{
Object m_Object[2];
m_Object[0].x = 20;
m_Object[0].y = 5;
m_Object[1].x = 75;
m_Object[1].y = 17;
char map[20][79];
for (int i = 0; i < 20; ++i)
{
for (int j = 0; j < 79; ++j)
{
map[i][j] = ' ' ;
}
}
map[(int )m_Object[0].y][(int )m_Object[0].x] = 'A' ;
map[(int )m_Object[1].y][(int )m_Object[1].x] = 'B' ;
for (int i = 0; i < 20; ++i)
{
for (int j = 0; j < 79; ++j)
{
printf("%c" , map[i][j]);
}
printf("\n" );
}
double distance = 0;
distance = cal_distance( m_Object[0].x , m_Object[1].x , m_Object[0].y , m_Object[1].y );
printf("Distance Between The Points = %f\n" , distance);
}
Mar 13, 2009 at 8:12am UTC
Just got it working by using this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
int Sign(double x) {
if (x < 0)
{
return -1;
}
else
{
return 1;
}
}
void drawLine(double xPrev, double yPrev, double x, double y, char (&map)[20][79])
{
double x1 = xPrev;
double y1 = yPrev;
double x2 = x;
double y2 = y;
double dy = y2 - y1;
double dx = x2 - x1;
if (fabs(dy) > fabs(dx))
{
for ( y = y1; y != y2; y += Sign( dy ) )
{
x = x1 + ( y - y1 ) * dx / dy;
map[(int )y][(int )x] = '.' ;
}
}
else
{
for ( x = x1; x != x2; x += Sign( dx ) )
{
y = y1 + ( x - x1 ) * dy / dx;
map[(int )y][(int )x] = '.' ;
}
}
// draw the last point
map[(int )y2][(int )x2] = '.' ;
}
Anyone know of any simpler ways or?
Topic archived. No new replies allowed.