Module Module1
Const PICWIDTH As Integer = 40
Const PICHEIGHT As Integer = 40
Sub fillPic(ByVal pic As Char(,), ByVal penColor As Char)
For y As Integer = 0 To PICHEIGHT
For x As Integer = 0 To PICWIDTH
pic(x, y) = penColor
Next
Next
End Sub
Sub displayPic(ByVal pic As Char(,))
For y As Integer = 0 To PICHEIGHT
For x As Integer = 0 To PICWIDTH
Console.Write(pic(x, y))
Next
Console.WriteLine()
Next
Console.ReadLine()
End Sub
Sub drawLine(ByVal pic As Char(,), ByVal penColor As Char, ByVal p1 As Point, ByVal p2 As Point)
Dim x, y As Integer
If p1.x = p2.x Then ' Vertical Line
' We need to have a special case for a vertical line.
' The reason we need to treat a vertical line differently
' is that the slope of a vertical line is undefined since you
' would have to divide by zero when calculating the slope.
' In mathematics (and in computer programming) it is
' an ERROR to divide by zero.
For y = p1.y To p2.y
pic(p1.x, y) = penColor
Next
ElseIf p1.y = p2.y Then 'Horizontal Line
' The following is a special case for a horizontal line.
'
' In a strict mathematical sense we don't need to treat
' horizontal lines as a special case. However, our algorithm
' below will cause a division by zero error for horizontal
' lines too.
For x = p1.x To p2.x
pic(x, p1.y) = penColor
Next
Else ' diagonal line
' Calculate the slope
Dim m As Double = (p2.y - p1.y) / (p2.x - p1.x)
' For every x value on the line calculate the appropriate
' y value and display it on the line
For x = p1.x To p2.x
' The following comes from reorganizing the
' "point-slope" equation for a line, y-p1.y=m(x-p1.x),
' where p1.x,p1.y is a SPECIFIC point, x is a "free variable" -
' i.e. x can take on any value and y is the value that
' is calculated from the specific value for x that
' is chosen
y = Math.Round(m * (x - p2.x) + p2.y)
pic(x, y) = penColor
Next
' For every y value on the line calculate the appropriate
' x value and display it on the line.
For y = p1.y To p2.y
x = Math.Round((y - p2.y + m * p2.x) / m)
pic(x, y) = penColor
Next
End If
End Sub
Sub Main()
Dim pic1 As Char(,) = New Char(PICHEIGHT, PICWIDTH) {}
Dim pic2 As Char(,) = New Char(PICHEIGHT, PICWIDTH) {}
Dim pic3 As Char(,) = New Char(PICHEIGHT, PICWIDTH) {}
Dim pic4 As Char(,) = New Char(PICHEIGHT, PICWIDTH) {}
fillPic(pic1, ".")
Dim origin As Point
origin = New Point(0, 0)
drawLine(pic1, "1", origin, New Point(PICWIDTH, 0))
drawLine(pic1, "2", origin, New Point(PICWIDTH, 3))
drawLine(pic1, "3", origin, New Point(PICWIDTH, 10))
drawLine(pic1, "4", origin, New Point(PICWIDTH, 20))
drawLine(pic1, "5", origin, New Point(PICWIDTH, 30))
drawLine(pic1, "6", origin, New Point(PICWIDTH, PICHEIGHT))
drawLine(pic1, "7", origin, New Point(30, PICHEIGHT))
drawLine(pic1, "8", origin, New Point(20, PICHEIGHT))
drawLine(pic1, "9", origin, New Point(10, PICHEIGHT))
drawLine(pic1, "A", origin, New Point(5, PICHEIGHT))
drawLine(pic1, "B", origin, New Point(0, PICHEIGHT))
displayPic(pic1)
End Sub
End Module