Microsoft Small Basic is an introduction to computer programming and the Small Basic programming language. It discusses key concepts like what a computer program is, how programming languages allow computers to understand programs, and how Small Basic aims to make programming easy for beginners. The document gives examples of simple Small Basic programs that demonstrate printing text, using variables to store and manipulate data, and using conditional statements like if/else. It introduces concepts like variables, operators, and control flow to allow programs to make decisions based on conditions.
2. Chapter1
An Introduction
Small Basic and Programming
ComputerProgrammingis definedasthe process of creatingcomputersoftware using programming
languages. Justlike we speakandunderstandEnglishorSpanishorFrench,computerscanunderstand
programswrittenincertainlanguages. These are calledprogramminglanguages. Inthe beginningthere
were justa fewprogramminglanguagesandtheywere reallyeasytolearnandcomprehend. Butas
computersandsoftware became more andmore sophisticated,programminglanguagesevolved fast,
gatheringmore complex concepts alongthe way. Asa resultmostmodernprogramminglanguagesand
theirconceptsare prettychallengingtograspby a beginner. Thisfacthasstarteddiscouragingpeople
fromlearningorattemptingcomputerprogramming.
Small Basicis a programminglanguage thatisdesignedtomake programmingextremelyeasy,
approachable andfunfor beginners. Small Basic’sintentionistobringdownthe barrierand serve asa
steppingstone tothe amazingworldof computerprogramming.
The Small Basic Environment
Let usstart witha quickintroductionto the Small BasicEnvironment. When youfirstlaunch
SmallBasic.exe, youwill seeawindowthatlookslike the followingfigure.
3. Figure 1 - The Small Basic Environment
Thisis the Small BasicEnvironment,wherewe’ll writeandrunour Small Basicprograms. This
environmenthasseveral distinct elementswhichare identifiedbynumbers.
The Editor, identifiedby[1] iswhere we will writeourSmall Basicprograms. Whenyouopena sample
program or a previouslysavedprogram, itwillshow uponthiseditor. Youcan thenmodifyitandsave if
for lateruse.
You can alsoopenand workwithmore than one program at one time. Each program youare working
withwill be displayedinaseparate editor. The editorthatcontainsthe programyouare currently
workingwithiscalledthe activeeditor.
The Toolbar, identifiedby[2] isusedto issue commands eithertothe active editoror the environment.
We’ll learnaboutthe variouscommandsinthe toolbaras we go.
The Surface, identifiedby[3] isthe place where all the editorwindowsgo.
Our First Program
Nowthat youare familiarwiththe Small BasicEnvironment, we will goaheadandstart programmingin
it. Like we justnotedabove,the editoristhe place where we write ourprograms. Solet’sgoaheadand
type the followingline inthe editor.
TextWindow.WriteLine("Hello World")
4. Thisis our firstSmall Basicprogram. And if youhave typeditcorrectly, youshouldsee something
similartothe figure below.
Figure 2 - First Program
Nowthat we have typed ournewprogram, let’sgoaheadand run itto see whathappens. We can run
our program eitherbyclickingonthe Run buttonon the toolbaror by usingthe shortcutkey,F5 on the
keyboard. If everythinggoeswell,ourprogram should runwiththe resultasshown below.
Figure 3 - First Program Output
Congratulations! You have justwrittenand run
the firstSmall Basicprogram. A verysmall and
simple program,butneverthelessabigstep
towardsbecomingareal computerprogrammer!
Now,there’sjustone more detail tocoverbefore
we go on to create biggerprograms. We have to
understandwhatjusthappened –whatexactly
didwe tell the computerandhowdid the
computerknowwhatto do? In the nextchapter,
we’ll analyze the programwe justwrote,sowe
can gain thatunderstanding.
As you typed yourfirstprogram,you might
havenoticed that a popup appeared witha list
of items (Figure 4). This is called “intellisense”
and it helpsyou typeyourprogramfaster. You
can traversethatlist by pressing the Up/Down
arrow keys,and when you find something you
want,you can hit the Enter key to insert the
selected item in yourprogram.
5. Figure 4 - Intellisense
Saving our program
If you wantto close Small Basicand come back later to work onthe programyou justtyped,youcan
save the program. It isin fact a goodpractice to save programsfromtime to time,sothat youdon’tlose
informationinthe eventof anaccidental shutdownorapowerfailure. Youcan save the current
program byeitherclickingonthe “save”iconon the toolbaror by usingthe shortcut“Ctrl+S” (pressthe
S keywhile holdingdownthe Ctrl key).
6. Chapter2
Understanding Our First Program
What really is a computer program?
A programis a set of instructionsforthe computer. These instructionstell the computer precisely what
to do,and the computeralwaysfollowstheseinstructions. Justlike people,computerscanonlyfollow
instructionsif specifiedinalanguage theycanunderstand. These are calledprogramminglanguages.
There are verymanylanguagesthatthe computercan understandand Small Basic isone.
Imagine aconversationhappeningbetweenyouandyourfriend. Youand yourfriendswoulduse words,
organized assentencestoconveyinformationbackandforth. Similarly,programminglanguages contain
collectionsof wordsthatcan be organizedintosentencesthatconveyinformationtothe computer.
Andprograms are basicallysetsof sentences(sometimesjustafew andsometimesmanythousands)
that togethermake sense toboththe
programmerand the computeralike.
Small Basic Programs
A typical Small Basicprogramconsistsof a bunch
of statements. Everyline of the program
representsastatementandeverystatementisan
instructionforthe computer. Whenwe askthe computertoexecute aSmall Basicprogram, ittakesthe
program andreads the first statement. Itunderstandswhat we’re tryingtosayandthenexecutes our
instruction. Once it’sdone executingourfirst statement,itcomesbackto the program andreads and
executesthe secondline. Itcontinuestodosountil itreachesthe endof the program. That iswhenour
program finishes.
There are many languagesthatthecomputer
can understand. Java,C++,Python,VB,etc.are
all powerfulmodern computerlanguagesthat
are used to develop simple to complex software
programs.
7. Back to Our First Program
Here is the firstprogram we wrote:
TextWindow.WriteLine("Hello World")
Thisis a verysimple programthatconsistsof one statement. That statementtellsthe computertowrite
a line of textwhichis HelloWorld,intothe TextWindow.
It literallytranslatesinthe computer’smindto:
Write Hello World
You mighthave already noticed thatthe statementcaninturn be splitinto smallersegments muchlike
sentencescanbe splitintowords. Inthe firststatementwe have 3 distinctsegments:
a) TextWindow
b) WriteLine
c) “HelloWorld”
The dot, parenthesesandthe quotesare all punctuationsthathave tobe placedat appropriate
positionsinthe statement,forthe computertounderstandourintent.
You mightrememberthe blackwindowthatappearedwhenwe ranour firstprogram. That black
windowiscalledthe TextWindow orsometimesreferredtoasthe Console. Thatiswhere the resultof
thisprogram goes. TextWindow,inourprogram, is called anobject. There are a numberof such
objectsavailable forustouse inour programs. We can performseveral different operations onthese
objects. We’ve alreadyused theWriteLineoperation inourprogram. You mightalsohave noticedthat
the WriteLine operationisfollowedby Hello
Worldinside quotes. Thistextispassedasinput
to the WriteLine operation, whichitthenprints
out to the user. Thisis calledan inputto the
operation. Some operationstake one ormore
inputswhile othersdon’ttake any.
Our SecondProgram
Nowthat youhave understood ourfirstprogram, let’sgoaheadand make it fancierby addingsome
colors.
TextWindow.ForegroundColor = "Yellow"
TextWindow.WriteLine("Hello World")
Punctuationssuch asquotes,spacesand
parenthesisarevery importantin a computer
program. Based on their position and count,
they can changethemeaning of whatis being
expressed.
8. Figure 5 - Adding Colors
Whenyourun the above program,you’ll notice thatitprintsoutthe same “HelloWorld”phrase inside
TextWindow,butthistime itprintsitoutinyellow insteadof the graythat it didearlier.
Figure 6 - Hello World in Yellow
Notice the newstatementwe addedtoouroriginal program. It usesa new word, ForegroundColor
whichwe equatedtoa value of “Yellow.” Thismeanswe’ve assigned “Yellow”toForegroundColor.
Now, the difference betweenForegroundColorandthe operationWriteLine isthatForegroundColordid
not take any inputsnordidit needany parenthesis. Insteaditwasfollowedbyan equalsto symbol and
a word. We define ForegroundColorasa Property of TextWindow. Here isa listof valuesthatare valid
for the ForegroundColorproperty. Try replacing“Yellow”with one of these andsee the results –don’t
forgetthe quotes,theyare requiredpunctuations.
Black
Blue
Cyan
Gray
Green
Magenta
Red
White
10. Chapter3
Introducing Variables
Using Variables in our program
Wouldn’titbe nice if our program can actuallysay“Hello”withthe usersname insteadof sayingthe
generic“Hello World?” Inorderto do that we mustfirstask the userfor his/hername andthenstore it
somewhere andthenprintout“Hello”withthe user’sname. Let’ssee how we cando that:
TextWindow.Write("Enter your Name: ")
name = TextWindow.Read()
TextWindow.WriteLine("Hello " + name)
Whenyoutype and execute thisprogram, you’ll seeanoutputlike the following:
Figure 7 - Ask the user's name
Andwhenyoutype inyour name and hitENTER, you’ll see the followingoutput:
Figure 8 - A Warm Hello
11. Now,if yourun the program again,you’ll be askedthe same questionagain. Youcantype in a different
name and the computerwill sayHellowiththatname.
Analysis of the program
In the program youjustran, the line thatmighthave caught yourattentionisthis:
name = TextWindow.Read()
Read() looksjustlike WriteLine(),butwithnoinputs. Itisan operationandbasicallyittellsthe computer
to waitfor the userto type insomethingandhitthe ENTER key. Once the userhitsthe ENTER key,it
takeswhatthe userhas typedandreturnsit to the program. The interestingpointisthatwhateverthe
userhad typedis now storedin a variablecalledname. A variableis definedasaplace where youcan
store valuestemporarilyanduse themlater. Inthe line above, name wasusedtostore the name of the
user.
The nextline isalsointeresting:
TextWindow.WriteLine("Hello " + name)
Thisis the place where we use the value storedin
our variable, name. We take the value inname
and appenditto “Hello”andwrite itto the
TextWindow.
Once a variable isset,youcanreuse it any
numberof times. Forexample,youcando the
following:
TextWindow.Write("Enter your Name: ")
name = TextWindow.Read()
TextWindow.Write("Hello " + name + ". ")
TextWindow.WriteLine("How are you doing " + name + "?")
Andyou’ll see the followingoutput:
Write,justlike WriteLine isanotheroperation
on ConsoleWindow. Writeallows you to write
something to the ConsoleWindow butallows
succeeding textto be on the sameline asthe
currenttext.
12. Figure 9 - Reusing a Variable
Rules for naming Variables
[TODO]
Playing with Numbers
We’ve justseenhowyoucan use variablesto store the name of the user. In the nextfew programs,
we’ll see howwe canstore and manipulate numbersinvariables. Let’sstartwithareallysimple
program:
number1 = 10
number2 = 20
number3 = number1 + number2
TextWindow.WriteLine(number3)
Whenyourun thisprogram you’ll getthe followingasoutput:
Figure 10 - Adding Two Numbers
In the firstline of the program,you’re assigningthe variablenumber1witha value of 10. Andinthe
secondline,you’re assigningthe variable
number2 witha value of 20. In the thirdline,
you’re addingnumber1and number2 and then
assigningthe resultof thatto number3. So,in
thiscase, number3 will have avalue of 30. And
that iswhat we printedoutto the TextWindow.
Now,let’smodifythatprogramslightlyandsee the results:
number1 = 10
number2 = 20
Notice thatthe numbersdon’thavequotes
around them. Fornumbers,quotesarenot
necessary. You need quotesonly when you’re
using text.
13. number3 = number1 * number2
TextWindow.WriteLine(number3)
The program above will multiply number1withnumber2andstore the resultin number3. And youcan
see inthe resultof that program below:
Figure 11 - Multiplying Two Numbers
Similarly,youcansubtractor divide numbers. Here isthe subtraction:
number3 = number1 - number2
Andthe symbol fordivisionis‘/’. The progamwill looklike:
number3 = number1 / number2
Andthe resultof this divisionwouldbe:
Figure 12 - Dividing Two Numbers
A Simple Temperature Converter
For the nextprogramwe’ll use the formula ℃ =
5(℉−32)
9
toconvertFahrenheittemperaturestoCelsius
temperatures.
First,we’ll getthe temperatureinFahrenheitfromthe userandstore itin a variable. There’saspecial
operationthatletsusread numbersfromthe userand thatis TextWindow.ReadNumber.
TextWindow.Write("Enter temperature in Fahrenheit: ")
fahr = TextWindow.ReadNumber()
Once we have the Fahrenheit temperaturestoredinavariable,we canconvertitto Celsiuslike this:
14. celsius = 5 * (fahr - 32) / 9
The parenthesestell the computertocalculate the fahr – 32 part firstand thenprocessthe rest. Now
all we have to do isprintthe resultoutto the user. Puttingitall together,we getthisprogram:
TextWindow.Write("Enter temperature in Fahrenheit: ")
fahr = TextWindow.ReadNumber()
celsius = 5 * (fahr - 32) / 9
TextWindow.WriteLine("Temperature in Celsius is " + celsius)
Andthe resultof this programwouldbe:
Figure 13 - Temperature Conversion
15. Chapter4
Conditions and Branching
Goingback to our firstprogram,wouldn’titbe cool that insteadof sayingthe general Hello World, we
couldsay Good Morning World, or Good Evening World dependingonthe time of the day? For our next
program,we’ll make the computersay Good Morning World if the time isearlierthan12PM; and Good
Evening if the time islater than12PM.
If (Clock.Hour < 12) Then
TextWindow.WriteLine("Good Morning World")
EndIf
If (Clock.Hour >= 12) Then
TextWindow.WriteLine("Good Evening World")
EndIf
Dependingonwhenyourunthe program you’ll see eitherof the followingoutputs:
Figure 14 - Good Morning World
16. Figure 15 - Good Evening World
Let’sanalyze the firstthree linesof the program. You’dhave alreadyfigured outthatthisline tellsthe
computerthat if the Clock.Hourislesserthan12,
printout “Good MorningWorld.” The words If,
Then andEndIf are special wordsthatare
understoodbythe computerwhenthe programis
run. The word If isalwaysfollowedby acondition,
whichinthiscase is(Clock.Hour < 12). Remember
that the parenthesesare necessaryforthe
computerto understandyourintentions. The
conditionisfollowedby thenandthe actual operationtoexecute. Andafterthe operationcomes EndIf.
Thistellsthe computerthatthe conditional executionisover.
Betweenthe thenandthe EndIf, there couldbe more thanone operationandthe computerwill execute
themall if the conditionisvalid. Forexample,youcouldwrite somethinglikethis:
If (Clock.Hour < 12) Then
TextWindow.Write("Good Morning. ")
TextWindow.WriteLine("How was breakfast?")
EndIf
Else
In the program at the start of thischapter,you mighthave noticedthatthe secondconditioniskindof
redundant. The Clock.Hour value couldeitherbe lessthan12 or not. We didn’treallyhave todo the
secondcheck. At timeslike this,we canshortenthe two if..then..endif statementstobe justone by
usinga newword, else.
If we were torewrite thatprogram using else,thisishow itwill look:
If (Clock.Hour < 12) Then
TextWindow.WriteLine("Good Morning World")
Else
TextWindow.WriteLine("Good Evening World")
EndIf
In SmallBasic, you can usethe Clockobjectto
accessthe current dateand time. It also
providesyou a bunch of propertiesthat allow
you to get thecurrent Day,Month,Year,Hour,
Minutes,Secondsseparately.
17. Andthisprogram will doexactlythe same asthe other one,whichbringsusto a veryimportantlesson
incomputerprogramming:
In programming,thereusually aremany waysof doing thesamething. Sometimesoneway
makesmoresense than theother way. The choice is left to the programmer. Asyou writemore
programsand getmoreexperienced,you’llstartto notice thesedifferenttechniquesand their
advantagesand disadvantages.
Indentation
In all the examplesyoucansee howthe statementsbetween If,Elseand EndIf are indented. This
indentationisnotnecessary. The computerwill understandthe programjustfine withoutthem.
However,theyhelpussee andunderstandthe structure of the programeasier. Hence,it’susually
consideredasa goodpractice to indent the statementsbetweensuchblocks.
Even or Odd
Nowthat we have the If..Then..Else..EndIf statementinourbag of tricks,let’swrite outa program that,
givena number,will sayif it’sevenorodd.
TextWindow.Write("Enter a number: ")
num = TextWindow.ReadNumber()
remainder = Math.Remainder(num, 2)
If (remainder = 0) Then
TextWindow.WriteLine("The number is Even")
Else
TextWindow.WriteLine("The number is Odd")
EndIf
Andwhenyourun thisprogram,you’ll see anoutputlike:
Figure 16 - Even or Odd
In thisprogram,we’ve introduced anothernew useful operation, Math.Remainder. Andyes,asyou
alreadymighthave figuredout, Math.Remainderwill divide the firstnumberbythe secondnumberand
thengive backthe remainder.
“
18. Branching
Remember,inthe secondchapteryoulearnedthatthe computerprocessesaprogramone statementat
a time,inorderfrom the top to bottom. However,there’saspecial statementthatcan make the
computerjumpto anotherstatementoutof order. Let’stake a lookat the nextprogram.
i = 1
start:
TextWindow.WriteLine(i)
i = i + 1
If (i < 25) Then
Goto start
EndIf
Figure 17 - Using Goto
In the program above,we assignedavalue of 1 to the variable i. Andthenwe addeda new statement
whichendsina colon(:)
start:
Thisis calledalabel. Labelsare like bookmarksthatthe computerunderstands. Youcan name the
bookmarkanythingandyoucan add as many labelsasyouwant inyourprogram, as longas theyare all
uniquelynamed.
Anotherinterestingstatementhere is:
i = i + 1
19. Thisjusttellsthe computertoadd 1 to the variable i and assignitback to i. So if the value of i was 1
before thisstatement,itwill be 2afterthisstatementisrun.
Andfinally,
If (i < 25) Then
Goto start
EndIf
Thisis the part that tellsthe computerthatif the value of i islessthan 25, start executingstatements
fromthe bookmark start.
Endless execution
Usingthe Gotostatementyoucan make the computerrepeatsomethinganynumberof times. For
example,youcantake the Evenor Odd programand modifyitlike below,andthe programwill runfor
ever. You can stopthe programby clickingonthe Close (X) buttononthe top rightcorner of the
window.
begin:
TextWindow.Write("Enter a number: ")
num = TextWindow.ReadNumber()
remainder = Math.Remainder(num, 2)
If (remainder = 0) Then
TextWindow.WriteLine("The number is Even")
Else
TextWindow.WriteLine("The number is Odd")
EndIf
Goto begin
Figure 18 - Even or Odd running endlessly
20. Chapter5
Loops
For Loop
Let’stake a programwe wrote in the previouschapter.
i = 1
start:
TextWindow.WriteLine(i)
i = i + 1
If (i < 25) Then
Goto start
EndIf
Thisprogram printsoutnumbersfrom1 to 24 inorder. This processof incrementingavariable isvery
commonin programmingthatprogramminglanguagesusuallyprovide aneasiermethodof doingthis.
The above program isequivalenttothe program below:
For i = 1 To 24
TextWindow.WriteLine(i)
EndFor
21. Andthe outputis:
Figure 19 - Using the For Loop
Notice thatwe’ve reducedthe 8line programto a 4 line program, andit still doesexactlythe same as
the 8 line program! Rememberearlierwe saidthatthere are usuallyseveralwaysof doingthe same
thing? Thisis a great example.
For..EndFor is,inprogrammingterms,calleda loop. It allowsyouto take a variable,give itaninitial and
an endvalue andletthe computerincrement the variable foryou. Everytime the computerincrements
the variable,itrunsthe statementsbetween ForandEndFor.
But if youwantedthe variable tobe incrementedby2insteadof 1 – like say,youwantedto printout all
the odd numbersbetween1and 24, you can use the loopto do that too.
For i = 1 To 24 Step 2
TextWindow.WriteLine(i)
EndFor
Figure 20 - Just the Odd Numbers
22. The Step 2 part of the For statementtellsthe computertoincrementthe value of i by2 insteadof the
usual 1. By usingStepyoucan specifyanyincrementthatyouwant. Youcan evenspecifyanegative
value forthe stepand make the computercount backwards,like inthe example below:
For i = 10 To 1 Step -1
TextWindow.WriteLine(i)
EndFor
Figure 21 - Counting Backwards
While Loop
The While loopisyetanotherloopingmethod,thatisuseful especiallywhenthe loopcountisnot
knownaheadof time. Whereasa For looprunsfor a pre-definednumberof times,the Whileloopruns
until a given conditionistrue. Inthe example below,we’rehalvinganumberuntil the resultisgreater
than 1.
number = 100
While (number > 1)
TextWindow.WriteLine(number)
number = number / 2
EndWhile
Figure 22 - Halving Loop
In the program above,we assignthe value 100 to numberandrun the while loopaslongasnumberis
greaterthan 1. Inside the loop,we printoutthe numberand thenwe divide itbytwo,effectively
halvingit. Andas expected,the outputof the program isnumbersthatare progressivelygettinghalved
one afteranother.
23. It’ll be reallyhardto write thisprogramusinga For loop,because we don’tknow how manytimesthe
loopwill run. Witha while loopit’seasytocheckfor a conditionandaskthe computertoeither
continue the looporquit.
It’ll be interestingtonote thateverywhile loopcanbe unwrappedintoanIf..Thenstatement. For
instance,the programabove can be rewrittenasfollows,withoutaffectingthe endresult.
number = 100
startLabel:
TextWindow.WriteLine(number)
number = number / 2
If (number > 1) Then
Goto startLabel
EndIf
In fact,thecomputerinternally rewritesevery
While loop into statementsthatuseIf..Then
along with one or moreGoto statements.
24. Chapter6
Beginning Graphics
So far inall our examples,we’veusedthe TextWindowtoexplainthe fundamentalsof the Small Basic
language. However,Small Basiccomeswithapowerful setof Graphicscapabilitiesthatwe’ll start
exploringinthischapter.
Introducing GraphicsWindow
Justlike we had TextWindowthatallowedustoworkwithText andNumbers,Small Basicalsoprovides
a GraphicsWindowthatwe can use to draw things. Let’sbeginbydisplayingthe GraphicsWindow.
GraphicsWindow.Show()
Whenyourun thisprogram, you’ll notice thatinsteadof the usual blacktextwindow,yougetawhite
Windowlike the one shownbelow. There’snothingmuchtodoon thiswindow yet. Butthiswill be the
base windowonwhichwe’ll workoninthischapter. You can close thiswindow byclickingonthe ‘X’
buttonon the top rightcorner.
25. Figure 23 - An empty Graphics Window
Setting up the Graphics Window
The graphics windowallowsyoutocustomize itsappearance toyourdesire. Youcan change the title,
the backgroundand itssize. Let’sgo aheadand modifyita bit,justto getfamiliarwiththe window.
GraphicsWindow.BackgroundColor = "SteelBlue"
GraphicsWindow.Title = "My Graphics Window"
GraphicsWindow.Width = 320
GraphicsWindow.Height = 200
GraphicsWindow.Show()
26. Here’showthe customizedgraphicswindow looks. Youcan change the backgroundcolorto one of the
manyvalueslisted inAppendixB. Playwiththese propertiestosee how youcanmodifythe window’s
appearance.
Figure 24 - A Custom Graphics Window
Drawing Lines
Once we have the GraphicsWindowup,we candraw shapes,textandevenpicturesonit. Let’sstartby
drawingsome simple shapes. Here’saprogramthat drawsa couple linesonthe GraphicsWindow.
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.DrawLine(10, 10, 100, 100)
GraphicsWindow.DrawLine(10, 100, 100, 10)
Figure 25 – CrissCross
The firsttwo linesof the programsetupthe
windowandthe nexttwolinesdrawthe crisscross
lines. The firsttwonumbersthatfollow DrawLine
specifythe startingx andy co-ordinatesandthe
othertwo specifythe endingx andy co-ordinates.
The interestingthingwithcomputergraphicsis
Instead of using namesforcolors you can use
the web color notation (#RRGGBB). For
example,#FF0000 denotesRed,#FFFF00 for
Yellow, and so on. We’ll learn more about
colors in [TODOColorschapter]
27. that the co-ordinates(0, 0) start at the top leftcornerof the window. Ineffect,inthe co-ordinate space
the windowisconsideredtobe onthe 2nd
quadrant.
[TODO:Insertpicture of quadrant]
Figure 26 - The co-ordinate map
If we go backto the line program,it’sinterestingtonote thatSmall Basicallowsyoutomodifythe
propertiesof the line,suchasthe colorand its thickness. First,let’smodifythe colorof the linesas
showninthe program below.
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.PenColor = "Green"
GraphicsWindow.DrawLine(10, 10, 100, 100)
GraphicsWindow.PenColor = "Gold"
GraphicsWindow.DrawLine(10, 100, 100, 10)
Figure 27 - Changing Line Color
Now,let’smodifythe size too. Inthe programbelow,we change the line widthtobe 10, insteadof the
defaultwhichis1.
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
GraphicsWindow.PenWidth = 10
28. GraphicsWindow.PenColor = "Green"
GraphicsWindow.DrawLine(10, 10, 100, 100)
GraphicsWindow.PenColor = "Gold"
GraphicsWindow.DrawLine(10, 100, 100, 10)
Figure 28 - Thick Colorful Lines
PenWidth and PenColormodifythe penwithwhichtheselinesare drawn. Theynotonlyaffectlinesbut
alsoany shape that isdrawnafter the propertiesare updated.
By usingthe loopingstatementswe learnedinthe previouschapters,we caneasilywrite aprogramthat
drawsmultiple lineswithincreasingpenthickness.
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 160
GraphicsWindow.PenColor = "Blue"
For i = 1 To 10
GraphicsWindow.PenWidth = i
GraphicsWindow.DrawLine(20, i * 15, 180, i * 15)
endfor
Figure 29 - Multiple Pen Widths
29. The interestingpartof thisprogramis the loop,where we increase the PenWidth everytime the loopis
run and thendrawa newline under the oldone.
Drawing and Filling Shapes
Whenit comesto drawingshapes,there are usuallytwotypesof operationsforeveryshape. Theyare
Draw operationsand Fill operations. Draw operationsdraw the outline of the shape usingapen,and Fill
operationspaintthe shape usingabrush. For example inthe programbelow,there are tworectangles,
one that isdrawn usingthe Redpenand one that’sfilledusingthe GreenBrush.
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawRectangle(20, 20, 300, 60)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillRectangle(60, 100, 300, 60)
Figure 30 Drawing and Filling
To draw or fill arectangle,youneedfournumbers. The firsttwonumbersrepresentthe XandY co-
ordinatesforthe top leftcornerof the rectangle. The thirdnumberspecifiesthe widthof the rectangle
while the fourthspecifiesitsheight. Infact,the same appliesfordrawingandfillingellipses,asshownin
the program below.
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
30. GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawEllipse(20, 20, 300, 60)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillEllipse(60, 100, 300, 60)
Figure 31 - Drawing and Filling Ellipses
Ellipsesare justageneral case of circles. If youwant to draw circles,youwouldhave tospecifythe same
widthandheight.
GraphicsWindow.Width = 400
GraphicsWindow.Height = 300
GraphicsWindow.PenColor = "Red"
GraphicsWindow.DrawEllipse(20, 20, 100, 100)
GraphicsWindow.BrushColor = "Green"
GraphicsWindow.FillEllipse(100, 100, 100, 100)
32. Chapter7
Fun with Shapes
We’re goingto have some funinthischapterwithwhateverwe’ve learnedsofar. Thischaptercontains
samplesthatshowsome interestingwaysof combiningall thatyou’ve learnedsofartocreate some
cool lookingprograms.
Rectangalore
Here we draw multiple rectanglesina loop,withincreasingsize.
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightBlue"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
For i = 1 To 100 Step 5
GraphicsWindow.DrawRectangle(100 - i, 100 - i, i * 2, i * 2)
EndFor
33. Figure 33 - Rectangalore
Circtacular
A variantof the previousprogram,drawscirclesinsteadof squares.
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightGreen"
GraphicsWindow.Width = 200
GraphicsWindow.Height = 200
For i = 1 To 100 Step 5
GraphicsWindow.DrawEllipse(100 - i, 100 - i, i * 2, i * 2)
EndFor
Figure 34 – Circtacular
Randomize
Thisprogram usesthe operationGraphicsWindow.GetRandomColortosetrandomcolorsfor the brush
and thenusesMath.GetRandomNumbertosetthe x and y co-ordinatesforthe circles. These two
operationscanbe combinedininterestingwaystocreate interestingprogramsthatgive different
resultseachtime theyare run.
34. GraphicsWindow.BackgroundColor = "Black"
For i = 1 To 1000
GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor()
x = Math.GetRandomNumber(640)
y = Math.GetRandomNumber(480)
GraphicsWindow.FillEllipse(x, y, 10, 10)
EndFor
Figure 35 – Randomize
Fractals
The followingprogramdrawsasimple triangle fractal usingrandomnumbers. A fractal isa geometric
shape that can be subdividedintoparts,eachof whichresemblesthe parentshape accurately. Inthis
case,the program draws hundredsof triangleseachof whichresemblesitsparenttriangle. Andsince
the program runsfor a fewseconds,youcan actuallysee the trianglesformingslowlyfrommere dots.
The logicitself issomewhathardtodescribe andI’ll leave itasan exercise foryoutoexplore.
GraphicsWindow.BackgroundColor = "Black"
x = 100
y = 100
For i = 1 To 100000
r = Math.GetRandomNumber(3)
35. ux = 150
uy = 30
If (r = 1) then
ux = 30
uy = 1000
EndIf
If (r = 2) Then
ux = 1000
uy = 1000
EndIf
x = (x + ux) / 2
y = (y + uy) / 2
GraphicsWindow.SetPixel(x, y, "LightGreen")
EndFor
Figure 36 - Triangle Fractal
If you wantto reallysee the dotsslowlyformingthe fractal,youcanintroduce adelayinthe loopby
usingthe Program.Delay operation. Thisoperation takesinanumberthatspecifiesinmilliseconds,how
longto delay. Here’sthe modifiedprogram, withthe modifiedline inbold.
36. GraphicsWindow.BackgroundColor = "Black"
x = 100
y = 100
For i = 1 To 100000
r = Math.GetRandomNumber(3)
ux = 150
uy = 30
If (r = 1) then
ux = 30
uy = 1000
EndIf
If (r = 2) Then
ux = 1000
uy = 1000
EndIf
x = (x + ux) / 2
y = (y + uy) / 2
GraphicsWindow.SetPixel(x, y, "LightGreen")
Program.Delay(2)
EndFor
Increasingthe delaywill make the programslower. Experimentwiththe numberstosee what’sbestfor
your taste.
Anothermodificationyoucanmake to thisprogramis to replace the followingline:
GraphicsWindow.SetPixel(x, y, "LightGreen")
with
color = GraphicsWindow.GetRandomColor()
GraphicsWindow.SetPixel(x, y, color)
Thischange will make the programdraw the pixelsof the triangle usingrandomcolors.
37. Chapter8
Turtle Graphics
Logo
In the 1970s, there was a verysimple butpowerfulprogramminglanguage,calledLogothatwasusedby
a fewresearchers. Thiswasuntil someone addedwhatiscalled“Turtle Graphics”tothe language and
made available a“Turtle”that wasvisible onthe screenandrespondedtocommandslike Move
Forward,Turn Right,Turn Left, etc. Usingthe Turtle,people were able todraw interestingshapesonthe
screen. Thismade the language immediatelyaccessible andappealingtopeopleof all ages,andwas
largely responsibleforitswildpopularityinthe 1980s.
Small Basiccomeswitha Turtle objectwithmanycommandsthat can be calledfromwithinSmall Basic
programs. In thischapter,we’ll use the Turtle todraw graphics onthe screen.
The Turtle
To beginwith,we needtomake the Turtle visibleonthe screen. Thiscan be achievedbya simple one
line program.
Turtle.Show()
Whenyourun thisprogram you’ll notice awhite window,justlike the one we saw inthe previous
chapter,exceptthisone hasa Turtle in the center. It isthisTurtle that isgoingto follow ourinstructions
and drawwhateverwe askit to.
38. Figure 37 - Turtle is visible
Moving and Drawing
One of the instructionsthatthe Turtle understandsis Move. Thisoperation takesanumberasinput.
Thisnumbertellsthe Turtle howfarto move. Say,in the example below,we’ll askthe Turtle tomove
100 pixels.
Turtle.Move(100)
Whenyourun thisprogram, youcan actuallysee
the turtle move slowlya100 pixelsupwards. Asit
moves,you’ll alsonotice itdrawingaline behind
it. Whenthe Turtle has finished moving,the
resultwill looksomethinglike the figure below.
When using operationson theTurtle, it is not
necessary to call Show(). TheTurtle will be
automatically madevisiblewheneverany
Turtle operation is performed.
39. Figure 38 - Move a hundred pixels
Drawing a Square
A square has foursides,twovertical andtwohorizontal. Inordertodraw a square we needtobe able
to make the Turtle draw a line,turnrightand draw anotherline andcontinue thisuntil all foursidesare
finished. If we translatedthistoa program, here’show itwouldlook.
Turtle.Move(100)
Turtle.TurnRight()
Turtle.Move(100)
Turtle.TurnRight()
Turtle.Move(100)
Turtle.TurnRight()
Turtle.Move(100)
Turtle.TurnRight()
Whenyourun thisprogram, youcan see the Turtle drawinga square,one line ata time,and the result
lookslike the figure below.
40. Figure 39 - Turtle drawing a square
It will be interestingtonote thatwe’re issuingthe same twoinstructionsoverandover – fourtimes
precisely. Andwe’ve alreadylearntthatsuchrepetitive commandscanbe executedusingloops. So,if
we take the programabove and modifyittouse the For..EndForloop,we’ll endupwithamuch simpler
program.
For i = 1 To 4
Turtle.Move(100)
Turtle.TurnRight()
EndFor
Changing Colors
The Turtle draws on the exactsame GraphicsWindow thatwe saw inthe previouschapter. Thismeans
that all the operationsthatwe learnedinthe previouschapterare still validhere. Forinstance,the
followingprogramwill drawthe square witheachside inadifferentcolor.
For i = 1 To 4
GraphicsWindow.PenColor = GraphicsWindow.GetRandomColor()
Turtle.Move(100)
Turtle.TurnRight()
EndFor
41. Figure 40 - Changing Colors
Drawing more complex shapes
The Turtle,inadditiontothe TurnRight and TurnLeftoperations,hasa Turn operation. This operation
takesone inputwhichspecifiesthe angle of rotation. Usingthis operation,itispossibletodraw any
sidedpolygon. The followingprogram drawsa hexagon(asix-sidedpolygon).
For i = 1 To 6
Turtle.Move(100)
Turtle.Turn(60)
EndFor
Try thisprogram out to see if itreallydrawsa hexagon. Observe thatsince the angle betweenthe sides
is60 degrees,we use Turn(60). For sucha polygon,whose sidesare all equal,the angle betweenthe
sidescanbe easilyobtainedbydividing360 bythe numberof sides. Armedwiththisinformationand
usingvariables,we canwrite aprettygenericprogramthat can draw any sidedpolygon.
sides = 12
length = 400 / sides
angle = 360 / sides
For i = 1 To sides
42. Turtle.Move(length)
Turtle.Turn(angle)
EndFor
Usingthis program,youcan draw any polygonbyjustmodifyingthe sidesvariable. Putting4here
wouldgive usthe Square we startedwith. Puttinga sufficientlylarge value,say50 wouldmake the
resultindistinguishable fromacircle.
Figure 41 - Drawing a 12 sided polygon
Usingthe technique we justlearned,we canmake the Turtle draw multiple circleseachtime withalittle
shiftresultinginaninterestingoutput.
sides = 50
length = 400 / sides
angle = 360 / sides
Turtle.Speed = 9
For j = 1 To 20
For i = 1 To sides
Turtle.Move(length)
Turtle.Turn(angle)
EndFor
Turtle.Turn(18)
43. EndFor
The programabove has two For..EndFor loops,one withinthe other. The innerloop (i= 1 to sides) is
similartothe polygonprogramand isresponsiblefordrawingacircle. The outerloop(j = 1 to 20) is
responsible forturningthe Turtle bya small bitforeverycircle thatis drawn. Thistellsthe Turtle to
draw 20 circles. Whenputtogether,thisprogram
resultsina veryinterestingpattern,likethe one
shownbelow.
Figure 42 - Going in circles
Moving Around
You can make the turtle not drawby callingthe PenUpoperation. Thisallowsyou tomove the turtle to
anywhere onthe screenwithoutdrawingaline. Calling PenDownwill make the turtle draw again. This
can be usedtoget some interestingeffects,like say,dottedlines. Here’saprogramthat usesthisto
draw a dottedline polygon.
sides = 6
length = 400 / sides
angle = 360 / sides
For i = 1 To sides
In theprogramabove,wehavemadetheTurtle
go fasterby setting the Speed to 9. You can set
this property to any valuebetween 1 and 10 to
makethe Turtle go asfastas you want.
44. For j = 1 To 6
Turtle.Move(length / 12)
Turtle.PenUp()
Turtle.Move(length / 12)
Turtle.PenDown()
EndFor
Turtle.Turn(angle)
EndFor
Again,thisprogramhas twoloops. The innerloopdrawsa single dottedline,whilethe outerloop
specifieshowmanylinestodraw. Inour example,we used6forthe sidesvariable andhence we gota
dottedline hexagon,asbelow.
Figure 43 - Using PenUp and PenDown
45. Chapter9
Subroutines
Veryoftenwhile writingprogramswe’ll runintocaseswhere we’ll have toexecutethe same setof
steps,overandoveragain. Inthose cases,it probablywouldn’tmake sense torewrite the same
statementsmultipletimes. That’swhen Subroutines come inhandy.
A subroutine isaportionof code withina largerprogramthat usuallydoessomethingveryspecific,and
that can be calledfromanywhere inthe program. Subroutinesare identifiedbyaname thatfollowsthe
Sub keywordandare terminatedbythe EndSubkeyword. Forexample,the followingsnippet
representsasubroutine whosename is PrintTime,andit doesthe jobof printingthe currenttime tothe
TextWindow.
Sub PrintTime
TextWindow.WriteLine(Clock.Time)
EndSub
Belowisa program that includesthe subroutine andcallsitfromvariousplaces.
PrintTime()
TextWindow.Write("Enter your name: ")
name = TextWindow.Read()
TextWindow.Write(name + ", the time now is: ")
PrintTime()
Sub PrintTime
TextWindow.WriteLine(Clock.Time)
46. EndSub
Figure 44 - Calling a simple Subroutine
You execute asubroutine bycalling SubroutineName(). Asusual,the punctuators“()”are necessaryto
tell the computerthatyou wantto execute asubroutine.
Advantages ofusing Subroutines
As we justsawabove,subroutineshelpreduce the amountof code youhave totype in. Once youhave
the PrintTime subroutine written,youcancall it fromanywhere inyourprogramand it’ll printthe
currenttime.
In addition,subroutinescanhelpdecompose
complex problemsintosimplerpieces. Sayyou
had a complex equationtosolve,youcanwrite
several subroutinesthatsolvedsmallerpiecesof
the complex equation. Thenyoucan putthe
resultstogethertogetthe solutiontothe original complex equation.
Subroutinescanalsoaidinimprovingthe readabilityof aprogram. Inotherwords,if you have well
namedsubroutinesforcommonlyrunportionsof yourprogram, yourprogrambecomes easytoread
and comprehend. Thisisveryimportantif youwantto understandsomeone else’sprogramorif you
wantyour program to be understoodbyothers. Sometimes,itishelpful evenwhenyouwant toread
your ownprogram,say a weekafteryouwrote it.
Using variables
You can access anduse anyvariable thatyouhave in a program fromwithinasubroutine. Asan
example,the followingprogramacceptstwonumbersandprintsout the largerof the two. Notice that
the variable max isusedbothinside andoutside of the subroutine.
TextWindow.Write("Enter first number: ")
num1 = TextWindow.ReadNumber()
TextWindow.Write("Enter second number: ")
num2 = TextWindow.ReadNumber()
FindMax()
Remember,you can only call a SmallBasic
subroutinefromwithin thesame program. You
cannotcall a subroutinefromwithin another
program.
47. TextWindow.WriteLine("Maximum number is: " + max)
Sub FindMax
If (num1 > num2) Then
max = num1
Else
max = num2
EndIf
EndSub
Andthe outputof thisprogram lookslike this.
Figure 45 - Max of two numbers using Subroutine
Let’slookat anotherexample thatwill illustrate the usage of Subroutines. Thistime we’lluse agraphics
program that computesvariouspointswhichitwillstore invariables x andy. Thenit callsa subroutine
DrawCircleUsingCenterwhichisresponsible fordrawingacircle using x andy as the center.
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightBlue"
GraphicsWindow.Width = 480
For i = 0 To 6.4 Step 0.17
x = Math.Sin(i) * 100 + 200
y = Math.Cos(i) * 100 + 200
DrawCircleUsingCenter()
EndFor
Sub DrawCircleUsingCenter
startX = x - 40
startY = y - 40
GraphicsWindow.DrawEllipse(startX, startY, 120, 120)
EndSub
48. Figure 46 - Graphics Example for Subroutines
Calling Subroutines inside Loops
Sometimessubroutinesgetcalledfrominside aloop,duringwhichtime theyexecute the same setof
statementsbutwithdifferentvaluesinone ormore of the variables. Forinstance,sayif youhave a
subroutine named PrimeCheck andthissubroutinedetermines if anumberisprime ornot. You can
write a program thatlets the userto entera value and youcan thensay if it is prime or not,usingthis
subroutine. The programbelowillustratesthat.
TextWindow.Write("Enter a number: ")
i = TextWindow.ReadNumber()
isPrime = "True"
PrimeCheck()
If (isPrime = "True") Then
TextWindow.WriteLine(i + " is a prime number")
Else
TextWindow.WriteLine(i + " is not a prime number")
EndIf
Sub PrimeCheck
For j = 2 To Math.SquareRoot(i)
If (Math.Remainder(i, j) = 0) Then
isPrime = "False"
Goto EndLoop
49. EndIf
Endfor
EndLoop:
EndSub
The PrimeChecksubroutine takesthe valueof i andtriesto divide itbysmallernumbers. If anumber
divides iand leavesnoremainder,then iisnot a prime number. Atthat pointthe subroutine setsthe
value of isPrime to “False”andexits. If the numberwas indivisible bysmallernumbersthenthe value of
isPrime remainsas“True.”
Figure 47 - Prime Check
Now that youhave a subroutine thatcando the Prime testforus, youmightwant to use thisto listout
all the prime numbersbelow,say,100. It isreallyeasytomodifythe above programand make the call
to PrimeCheck frominside aloop. Thisgivesthe subroutine adifferentvalue tocompute eachtime the
loopisrun. Let’ssee howthisis done withthe example below.
For i = 3 To 100
isPrime = "True"
PrimeCheck()
If (isPrime = "True") Then
TextWindow.WriteLine(i)
EndIf
EndFor
Sub PrimeCheck
For j = 2 To Math.SquareRoot(i)
If (Math.Remainder(i, j) = 0) Then
isPrime = "False"
Goto EndLoop
EndIf
Endfor
EndLoop:
EndSub
In the program above,the value of i isupdatedeverytime the loopisrun. Inside the loop,acall to the
subroutine PrimeCheck ismade. The subroutine PrimeCheck thentakesthe value of iand computes
whetherornot i is a prime number. Thisresultisstoredinthe variable isPrimewhichisthenaccessed
50. by the loopoutside of the subroutine. The value of i isthenprintedif itturns outto be a prime number.
Andsince the loopstarts from3 and goesupto 100, we geta listof all the prime numbersthatare
between3and 100. Belowisthe resultof the program.
Figure 48 - Prime Numbers
51. Chapter10
Events and Interactivity
In the firsttwochapters,we introducedobjectsthathave Properties andOperations. Inadditionto
propertiesandoperations,some objectshave whatare called Events. Eventsare like signalsthatare
raised,forexample,inresponse touseractions,like movingthe mouse orclickingit. Insome sense
eventsare the opposite of operations. Inthe case of operation,youasa programmercall it to make the
computerdo something;whereasinthe case of events,the computerletsyouknow whensomething
interestinghashappened.
Howare events useful?
Eventsare central tointroducinginteractivityinaprogram. If youwant to allow auser to interactwith
your program, eventsare whatyou’ll use. Say,you’re writingaTic-Tac-Toe game. You’ll wanttoallow
the userto choose his/herplay,right? That’swhere eventscome in - youreceive userinputfromwithin
your programusingevents. If thisseemshardtograsp, don’tworry,we’ll take alookat a verysimple
example thatwill helpyouunderstandwhateventsare andhow theycan be used.
Belowisa verysimple programthathas justone statementandone subroutine. The subroutine uses
the ShowMessageoperationonthe GraphicsWindow objecttodisplayamessage box tothe user.
GraphicsWindow.MouseDown = OnMouseDown
Sub OnMouseDown
GraphicsWindow.ShowMessage("You Clicked.", "Hello")
EndSub
52. The interestingparttonote in the programabove is the line where we assignthe subroutine name to
the MouseDowneventof GraphicsWindow object. You’ll notice thatMouseDownlooksverymuchlike
a property – exceptthatinsteadof assigningsome value,we’re assigningthe subroutine OnMouseDown
to it. That’swhat isspecial aboutevents –whenthe eventhappens,the subroutineiscalled
automatically. Inthiscase,the subroutine OnMouseDowniscalledeverytime the userclicksusingthe
mouse,onthe GraphicsWindow. Goahead,run the program andtry it out. Anytime youclickonthe
GraphicsWindowwithyourmouse,you’ll seeamessage box justlike the one showninthe picture
below.
Figure 49 - Response to an event
Thiskindof eventhandlingisverypowerfulandallowsforverycreative andinterestingprograms.
Programswritteninthisfashionare oftencalledevent-drivenprograms.
You can modifythe OnMouseDown subroutinetodootherthingsthanpopupa message box. For
instance,like inthe programbelow,youcandraw bigblue dotswhere the userclicksthe mouse.
GraphicsWindow.BrushColor = "Blue"
GraphicsWindow.MouseDown = OnMouseDown
Sub OnMouseDown
x = GraphicsWindow.MouseX - 10
y = GraphicsWindow.MouseY - 10
GraphicsWindow.FillEllipse(x, y, 20, 20)
EndSub
53. Figure 50 - Handling Mouse Down Event
Notice thatin the programabove,we used MouseX andMouseYto getthe mouse co-ordinates. We
thenuse thisto draw a circle usingthe mouse co-ordinatesasthe centerof the circle.
Handling multiple events
There are reallynolimitstohowmanyeventsyouwantto handle. Youcan evenhave one subroutine
handle multiple events. However,youcanhandle aneventonlyonce. If you try to assigntwo
subroutinestothe same event,the secondone wins.
To illustrate this,let’stake the previousexample andaddasubroutine thathandleskeypresses. Also,
let’smake thisnewsubroutine change the colorof the brush,sothat whenyouclickyourmouse,you’ll
geta differentcoloreddot.
GraphicsWindow.BrushColor = "Blue"
GraphicsWindow.MouseDown = OnMouseDown
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor()
EndSub
Sub OnMouseDown
x = GraphicsWindow.MouseX - 10
54. y = GraphicsWindow.MouseY - 10
GraphicsWindow.FillEllipse(x, y, 20, 20)
EndSub
Figure 51 - Handling multiple events
If you ran thisprogram and clickedonthe window,you’ll getablue dot. Now,if youpressany keyonce
and clickagain,you’ll geta differentcoloreddot. What’shappeningwhenyoupressakeyisthat the
subroutine OnKeyDown getsexecutedwhichchangesthe brushcolorto a randomcolor. Afterthat
whenyouclickthe mouse,a circle isdrawn usingthe newlysetcolor – givingthe randomcolordots.
A paint program
Armedwitheventsandsubroutines,we cannow write aprogram that letsusersdraw on the window.
It’ssurprisinglyeasytowrite sucha program, providedwe breakdownthe problemintosmallerbits. As
a firststep,let’swrite aprogram that will allow userstomove the mouse anywhere onthe graphics
window,leavingatrail wherevertheymove the mouse.
GraphicsWindow.MouseMove = OnMouseMove
Sub OnMouseMove
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
GraphicsWindow.DrawLine(prevX, prevY, x, y)
55. prevX = x
prevY = y
EndSub
However,whenyourunthisprogram,the firstline alwaysstartsfromthe top leftedge of the window
(0, 0). We can fix thisproblembyhandlingthe MouseDown eventandcapture the prevX and prevY
valueswhenthateventcomes.
Also,we reallyonlyneedthe trail whenthe user hasthe mouse buttondown. Othertimes,we
shouldn’tdrawthe line. Inorderto getthisbehavior,we’ll use the IsLeftButtonDown propertyonthe
Mouse object. Thispropertytellswhetherthe Leftbuttonisbeinghelddownornot. If this value is
true,thenwe’ll drawthe line,if notwe’llskipthe line.
GraphicsWindow.MouseMove = OnMouseMove
GraphicsWindow.MouseDown = OnMouseDown
Sub OnMouseDown
prevX = GraphicsWindow.MouseX
prevY = GraphicsWindow.MouseY
EndSub
Sub OnMouseMove
x = GraphicsWindow.MouseX
y = GraphicsWindow.MouseY
If (Mouse.IsLeftButtonDown) Then
GraphicsWindow.DrawLine(prevX, prevY, x, y)
EndIf
prevX = x
prevY = y
EndSub
(Pendingcompletion)