Wednesday, January 7, 2009

Turtle graphics - Lesson 5

Let's draw some graphics that we can use with our hypotenuse calculator. Let's draw one of those standard right triangles and then draw values for each side. To do this let's use turtle graphics (here's a Wikipedia entry for turtle graphics). The Run BASIC graphic object has a turtle which you can command by telling it to turn and go on the graphic area. As you command it to go and turn it draws lines showing where it's been.

Examine the drawRightTriangle subroutine to see how we draw the triangle, the little box at the 90 degree corner, and the lengths of each side.
'hypotenuse calculator
global a, b, c, #sideA, #sideB
call displayAll

sub displayAll
print "Hypotenuse Calculator"
print "Length of side A: ";
textbox #sideA, a
print "Length of side B: ";
textbox #sideB, b
button #go, "Go!", computeSideC
if c > 0 then
print "Length of side C: "; c
call drawRightTriangle a, b, c
end if
end sub

sub computeSideC key$
a = #sideA value()
b = #sideB value()
c = sqr(a^2+b^2)
call displayAll
end sub

sub drawRightTriangle a, b, c
graphic #rightTri, 240, 180
#rightTri place(210, 160)
#rightTri north()
#rightTri go(150)
#rightTri turn(-127)
#rightTri go(250)
#rightTri turn(-143)
#rightTri go(200)
#rightTri box(180, 130)
#rightTri place(215, 80)
#rightTri "\"; a
#rightTri place(100, 170)
#rightTri "\"; b
#rightTri place(90, 80)
#rightTri "\"; c
render #rightTri
end sub
Here's what the drawing looks like:

No comments: