This is most easily solved using a parametric representation of the line, which involves a letter vector mathematics. But don't worry, it'll be easy.
Let's say your line is well-specified by the following formula:
y=ax+b
where a
is the slope and b
is the y-intercept.
Then your line has a direction given by the vector <1,a>
which means that the line rises m
units for every 1
unit it runs horizontally.
We can normalize this vector by dividing by its magnitude.
The magnitude of a vector is given by
m=sqrt(a**2+b**2)
The normalized vector is given by v=<1/m,a/m>
.
Now, we can draw your line as follows:
for t in range(50):
xp=0+t*v[0]
yp=b+t*v[1]
plot_point(xp,yp,'-')
You see what I did there? I changed the variable we are looping over from x
to t
. That allows us to treat the x
and y
parts of the equation separately.
If my line had instead been specified by its end points, I could instead have written the equations as follows:
for t in range(0,1,0.01):
xp=x1+t*(x2-x1)
yp=y1+t*(y2-y1)
plot_point(xp,yp,'-')
Since x1
is the starting point of the x part of the line, and x2-x1
is the distance between the lines x points, as t
walks from 0
to 1
, it passes all the x-points of the line. y
works similarly.
Now, we can abstract our line drawing function so that it looks like this:
def draw_line(a,b,len,skip,sym):
m=sqrt(a**2+b**2)
v=(1/m,a/m)
for t in range(0,len,skip):
xp=0+t*v[0]
yp=b+t*v[1]
plot_point(xp,yp,sym)
Now, we draw your line by typing:
draw_line(a,b,50,1,'-')
And draw the gaps with
draw_line(a,b,50,3,'.')
Where 50
is the length of the line and 3
is the distance between gaps.
Had we used the start and end points of the line instead, our function would look like:
def draw_line(x1,y1,x2,y2,skip,sym):
dist=sqrt((x1-x2)**2)+(y1-y2)**2)
skip=skip/dist
for t in range(0,1,skip):
xp=x1+t*(x2-x1)
yp=y1+t*(y2-y1)
plot_point(xp,yp,sym)
This converts the distance you want to skip to a proportion of the line's total length. You would probably want to use a skip value of 1 or less for drawing the line and a larger skip value for taking out your equidistant points.
You will probably want to look into using Bresenham's Line Algorithm to do the drawing for you - it's a good way of figuring out the best way to approximate a line when you have a grid of pixels of characters.
And, if you are drawing characters to the screen, you'll probably be interested in ANSI escape codes, which can be used to move the cursor around, display colours, and clear the screen.