SlideShare a Scribd company logo
1 of 62
Microsoft Small Basic
An introduction to Programming
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.
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")
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.
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).
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.
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.
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
Yellow
DarkBlue
DarkCyan
DarkGray
DarkGreen
DarkMagenta
DarkRed
DarkYellow
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
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.
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.
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:
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
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
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.
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.
“
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
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
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
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
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.
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.
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.
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()
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]
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
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
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
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)
Figure 32 – Circles
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
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.
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)
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.
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.
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.
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.
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.
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
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
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)
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.
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
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)
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.
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
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
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
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
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
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
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
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)
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)
AppendixA
Fun Samples
Turtle Fractal
Figure 52 - Turtle drawing a tree fractal
angle = 30
delta = 10
distance = 60
Turtle.Speed = 9
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.PenColor = "LightGreen"
DrawTree()
Sub DrawTree
If (distance > 0) Then
Turtle.Move(distance)
Turtle.Turn(angle)
Stack.PushValue("distance", distance)
distance = distance - delta
DrawTree()
Turtle.Turn(-angle * 2)
DrawTree()
Turtle.Turn(angle)
distance = Stack.PopValue("distance")
Turtle.Move(-distance)
EndIf
EndSub
Photos from Flickr
Figure 53 - Retrieving pictures from Flickr
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.MouseDown = OnMouseDown
Sub OnMouseDown
pic = Flickr.GetRandomPicture("mountains, river")
GraphicsWindow.DrawResizedImage(pic, 0, 0, 640, 480)
EndSub
Dynamic DesktopWallpaper
For i = 1 To 10
pic = Flickr.GetRandomPicture("mountains")
Desktop.SetWallPaper(pic)
Program.Delay(10000)
EndFor
Paddle Game
Figure 54 - Paddle Game
GraphicsWindow.BackgroundColor = "DarkBlue"
paddle = Shapes.AddRectangle(120, 12)
ball = Shapes.AddEllipse(16, 16)
GraphicsWindow.MouseMove = OnMouseMove
x = 0
y = 0
deltaX = 1
deltaY = 1
RunLoop:
x = x + deltaX
y = y + deltaY
gw = GraphicsWindow.Width
gh = GraphicsWindow.Height
If (x >= gw - 16 or x <= 0) Then
deltaX = -deltaX
EndIf
If (y <= 0) Then
deltaY = -deltaY
EndIf
padX = Shapes.GetLeft (paddle)
If (y = gh - 28 and x >= padX and x <= padX + 120) Then
deltaY = -deltaY
EndIf
Shapes.Move(ball, x, y)
Program.Delay(5)
If (y < gh) Then
Goto RunLoop
EndIf
GraphicsWindow.ShowMessage("You Lose", "Paddle")
Sub OnMouseMove
paddleX = GraphicsWindow.MouseX
Shapes.Move(paddle, paddleX - 60, GraphicsWindow.Height - 12)
EndSub
AppendixB
Colors
TODO: Describe colors+ hex
Here’sa listof namedcolorssupportedbySmall Basic,categorizedbytheirbase hue.
Red Colors
IndianRed #CD5C5C
LightCoral #F08080
Salmon #FA8072
DarkSalmon #E9967A
LightSalmon #FFA07A
Crimson #DC143C
Red #FF0000
FireBrick #B22222
DarkRed #8B0000
Pink Colors
Pink #FFC0CB
LightPink #FFB6C1
HotPink #FF69B4
DeepPink #FF1493
MediumVioletRed #C71585
PaleVioletRed #DB7093
Orange Colors
LightSalmon #FFA07A
Coral #FF7F50
Tomato #FF6347
OrangeRed #FF4500
DarkOrange #FF8C00
Orange #FFA500
Yellow Colors
Gold #FFD700
Yellow #FFFF00
LightYellow #FFFFE0
LemonChiffon #FFFACD
LightGoldenrodYellow #FAFAD2
PapayaWhip #FFEFD5
Moccasin #FFE4B5
PeachPuff #FFDAB9
PaleGoldenrod #EEE8AA
Khaki #F0E68C
DarkKhaki #BDB76B
Purple Colors
Lavender #E6E6FA
Thistle #D8BFD8
Plum #DDA0DD
Violet #EE82EE
Orchid #DA70D6
Fuchsia #FF00FF
Magenta #FF00FF
MediumOrchid #BA55D3
MediumPurple #9370DB
BlueViolet #8A2BE2
DarkViolet #9400D3
DarkOrchid #9932CC
DarkMagenta #8B008B
Purple #800080
Indigo #4B0082
SlateBlue #6A5ACD
DarkSlateBlue #483D8B
MediumSlateBlue #7B68EE
Green Colors
GreenYellow #ADFF2F
Chartreuse #7FFF00
LawnGreen #7CFC00
Lime #00FF00
LimeGreen #32CD32
PaleGreen #98FB98
LightGreen #90EE90
MediumSpringGreen #00FA9A
SpringGreen #00FF7F
MediumSeaGreen #3CB371
SeaGreen #2E8B57
ForestGreen #228B22
Green #008000
DarkGreen #006400
YellowGreen #9ACD32
OliveDrab #6B8E23
Olive #808000
DarkOliveGreen #556B2F
MediumAquamarine #66CDAA
DarkSeaGreen #8FBC8F
LightSeaGreen #20B2AA
DarkCyan #008B8B
Teal #008080
Blue Colors
Aqua #00FFFF
Cyan #00FFFF
LightCyan #E0FFFF
PaleTurquoise #AFEEEE
Aquamarine #7FFFD4
Turquoise #40E0D0
MediumTurquoise #48D1CC
DarkTurquoise #00CED1
CadetBlue #5F9EA0
SteelBlue #4682B4
LightSteelBlue #B0C4DE
PowderBlue #B0E0E6
LightBlue #ADD8E6
SkyBlue #87CEEB
LightSkyBlue #87CEFA
DeepSkyBlue #00BFFF
DodgerBlue #1E90FF
CornflowerBlue #6495ED
MediumSlateBlue #7B68EE
RoyalBlue #4169E1
Blue #0000FF
MediumBlue #0000CD
DarkBlue #00008B
Navy #000080
MidnightBlue #191970
Brown Colors
Cornsilk #FFF8DC
BlanchedAlmond #FFEBCD
Bisque #FFE4C4
NavajoWhite #FFDEAD
Wheat #F5DEB3
BurlyWood #DEB887
Tan #D2B48C
RosyBrown #BC8F8F
SandyBrown #F4A460
Goldenrod #DAA520
DarkGoldenrod #B8860B
Peru #CD853F
Chocolate #D2691E
SaddleBrown #8B4513
Sienna #A0522D
Brown #A52A2A
Maroon #800000
White Colors
White #FFFFFF
Snow #FFFAFA
Honeydew #F0FFF0
MintCream #F5FFFA
Azure #F0FFFF
AliceBlue #F0F8FF
GhostWhite #F8F8FF
WhiteSmoke #F5F5F5
Seashell #FFF5EE
Beige #F5F5DC
OldLace #FDF5E6
FloralWhite #FFFAF0
Ivory #FFFFF0
AntiqueWhite #FAEBD7
Linen #FAF0E6
LavenderBlush #FFF0F5
MistyRose #FFE4E1
Gray Colors
Gainsboro #DCDCDC
LightGray #D3D3D3
Silver #C0C0C0
DarkGray #A9A9A9
Gray #808080
DimGray #696969
LightSlateGray #778899
SlateGray #708090
DarkSlateGray #2F4F4F
Black #000000

More Related Content

What's hot

Jetpack compose
Jetpack composeJetpack compose
Jetpack composeLutasLin
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferencesAjay Panchal
 
Coding vs programming
Coding vs programmingCoding vs programming
Coding vs programmingAman Kumar
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.jsSmile Gupta
 
Presentation on java (8)
Presentation on java (8)Presentation on java (8)
Presentation on java (8)Shwetakant1
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Edureka!
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
Spring Security 5.5 From Taxi to Takeoff
Spring Security 5.5 From Taxi to TakeoffSpring Security 5.5 From Taxi to Takeoff
Spring Security 5.5 From Taxi to TakeoffVMware Tanzu
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Edureka!
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleMarian Wamsiedel
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to heroDiego Lemos
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java SlidesVinit Vyas
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...Philip Schwarz
 

What's hot (20)

Jetpack compose
Jetpack composeJetpack compose
Jetpack compose
 
Android share preferences
Android share preferencesAndroid share preferences
Android share preferences
 
Coding vs programming
Coding vs programmingCoding vs programming
Coding vs programming
 
Getting Started with React.js
Getting Started with React.jsGetting Started with React.js
Getting Started with React.js
 
Presentation on java (8)
Presentation on java (8)Presentation on java (8)
Presentation on java (8)
 
JS Event Loop
JS Event LoopJS Event Loop
JS Event Loop
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
Java API
Java APIJava API
Java API
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
Spring Security 5.5 From Taxi to Takeoff
Spring Security 5.5 From Taxi to TakeoffSpring Security 5.5 From Taxi to Takeoff
Spring Security 5.5 From Taxi to Takeoff
 
Spring batch overivew
Spring batch overivewSpring batch overivew
Spring batch overivew
 
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Begin...
 
Design functional solutions in Java, a practical example
Design functional solutions in Java, a practical exampleDesign functional solutions in Java, a practical example
Design functional solutions in Java, a practical example
 
Ruby from zero to hero
Ruby from zero to heroRuby from zero to hero
Ruby from zero to hero
 
Kotlin
KotlinKotlin
Kotlin
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java Slides
 
spring-boot-fr.pdf
spring-boot-fr.pdfspring-boot-fr.pdf
spring-boot-fr.pdf
 
Left and Right Folds - Comparison of a mathematical definition and a programm...
Left and Right Folds- Comparison of a mathematical definition and a programm...Left and Right Folds- Comparison of a mathematical definition and a programm...
Left and Right Folds - Comparison of a mathematical definition and a programm...
 

Similar to Learn programming with Microsoft Small Basic

Introducing small basic
Introducing small basicIntroducing small basic
Introducing small basicSara Samol
 
1. Introduction Original - To Print
1. Introduction Original - To Print1. Introduction Original - To Print
1. Introduction Original - To PrintChinthaka Fernando
 
Specification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaSpecification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaKim Moore
 
Struktur Level Program
Struktur Level ProgramStruktur Level Program
Struktur Level ProgramDimara Hakim
 
Using Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) EnvironmentUsing Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) EnvironmentMahmoud Samir Fayed
 
C plus plus for hackers it security
C plus plus for hackers it securityC plus plus for hackers it security
C plus plus for hackers it securityCESAR A. RUIZ C
 
Demystifying dot NET reverse engineering - Part1
Demystifying  dot NET reverse engineering - Part1Demystifying  dot NET reverse engineering - Part1
Demystifying dot NET reverse engineering - Part1Soufiane Tahiri
 
notes on Programming fundamentals
notes on Programming fundamentals notes on Programming fundamentals
notes on Programming fundamentals ArghodeepPaul
 
Java And Community Support
Java And Community SupportJava And Community Support
Java And Community SupportWilliam Grosso
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...Sławomir Zborowski
 
Introduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleIntroduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleSandeep Hijam
 
Comso c++
Comso c++Comso c++
Comso c++Mi L
 
Contents Pre-requisites Approximate .docx
   Contents Pre-requisites  Approximate .docx   Contents Pre-requisites  Approximate .docx
Contents Pre-requisites Approximate .docxShiraPrater50
 
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docxLabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docxDIPESH30
 

Similar to Learn programming with Microsoft Small Basic (20)

Introducing Small Basic.pdf
Introducing Small Basic.pdfIntroducing Small Basic.pdf
Introducing Small Basic.pdf
 
Introducing small basic
Introducing small basicIntroducing small basic
Introducing small basic
 
Moreno Xec
Moreno XecMoreno Xec
Moreno Xec
 
Small basic
Small basicSmall basic
Small basic
 
1. Introduction Original - To Print
1. Introduction Original - To Print1. Introduction Original - To Print
1. Introduction Original - To Print
 
Specification Of The Programming Language Of Java
Specification Of The Programming Language Of JavaSpecification Of The Programming Language Of Java
Specification Of The Programming Language Of Java
 
Struktur Level Program
Struktur Level ProgramStruktur Level Program
Struktur Level Program
 
Java script hello world
Java script hello worldJava script hello world
Java script hello world
 
Using Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) EnvironmentUsing Python inside Programming Without Coding Technology (PWCT) Environment
Using Python inside Programming Without Coding Technology (PWCT) Environment
 
C plus plus for hackers it security
C plus plus for hackers it securityC plus plus for hackers it security
C plus plus for hackers it security
 
Demystifying dot NET reverse engineering - Part1
Demystifying  dot NET reverse engineering - Part1Demystifying  dot NET reverse engineering - Part1
Demystifying dot NET reverse engineering - Part1
 
notes on Programming fundamentals
notes on Programming fundamentals notes on Programming fundamentals
notes on Programming fundamentals
 
Java And Community Support
Java And Community SupportJava And Community Support
Java And Community Support
 
What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...What every C++ programmer should know about modern compilers (w/ comments, AC...
What every C++ programmer should know about modern compilers (w/ comments, AC...
 
PROBLEM SOLVING
PROBLEM SOLVINGPROBLEM SOLVING
PROBLEM SOLVING
 
Introduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning SimpleIntroduction to Docker and Containers- Learning Simple
Introduction to Docker and Containers- Learning Simple
 
Comso c++
Comso c++Comso c++
Comso c++
 
Contents Pre-requisites Approximate .docx
   Contents Pre-requisites  Approximate .docx   Contents Pre-requisites  Approximate .docx
Contents Pre-requisites Approximate .docx
 
Programming in C++
Programming in C++Programming in C++
Programming in C++
 
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docxLabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
LabsLab8.htmlLab 8 Im Thinking of a NumberBefore yo.docx
 

More from som_nangia

Puppet barcampexercises.jzt
Puppet barcampexercises.jztPuppet barcampexercises.jzt
Puppet barcampexercises.jztsom_nangia
 
Testspeakernotes 090715053843 Phpapp02
Testspeakernotes 090715053843 Phpapp02Testspeakernotes 090715053843 Phpapp02
Testspeakernotes 090715053843 Phpapp02som_nangia
 
How Stupid Can We Get
How Stupid Can We GetHow Stupid Can We Get
How Stupid Can We Getsom_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmsom_nangia
 
Audio one_in_each_slide
Audio one_in_each_slideAudio one_in_each_slide
Audio one_in_each_slidesom_nangia
 
Animation test_notes
Animation test_notesAnimation test_notes
Animation test_notessom_nangia
 
Animation test
Animation testAnimation test
Animation testsom_nangia
 
Animation test
Animation testAnimation test
Animation testsom_nangia
 
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01som_nangia
 
Pwnotes 1234179558850871-1
Pwnotes 1234179558850871-1Pwnotes 1234179558850871-1
Pwnotes 1234179558850871-1som_nangia
 

More from som_nangia (20)

Puppet barcampexercises.jzt
Puppet barcampexercises.jztPuppet barcampexercises.jzt
Puppet barcampexercises.jzt
 
Linktest
LinktestLinktest
Linktest
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Escape Test
Escape TestEscape Test
Escape Test
 
Testspeakernotes 090715053843 Phpapp02
Testspeakernotes 090715053843 Phpapp02Testspeakernotes 090715053843 Phpapp02
Testspeakernotes 090715053843 Phpapp02
 
How Stupid Can We Get
How Stupid Can We GetHow Stupid Can We Get
How Stupid Can We Get
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Audio one_in_each_slide
Audio one_in_each_slideAudio one_in_each_slide
Audio one_in_each_slide
 
Animation test_notes
Animation test_notesAnimation test_notes
Animation test_notes
 
Animation test
Animation testAnimation test
Animation test
 
Animation test
Animation testAnimation test
Animation test
 
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01
Futureoftheinternetciscocarriergradeipv6solutioncgv6 091110191821 Phpapp01
 
Pwnotes 1234179558850871-1
Pwnotes 1234179558850871-1Pwnotes 1234179558850871-1
Pwnotes 1234179558850871-1
 

Recently uploaded

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 

Recently uploaded (20)

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 

Learn programming with Microsoft Small Basic

  • 1. Microsoft Small Basic An introduction to Programming
  • 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)
  • 31. Figure 32 – Circles
  • 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)
  • 56. AppendixA Fun Samples Turtle Fractal Figure 52 - Turtle drawing a tree fractal angle = 30 delta = 10 distance = 60 Turtle.Speed = 9
  • 57. GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.PenColor = "LightGreen" DrawTree() Sub DrawTree If (distance > 0) Then Turtle.Move(distance) Turtle.Turn(angle) Stack.PushValue("distance", distance) distance = distance - delta DrawTree() Turtle.Turn(-angle * 2) DrawTree() Turtle.Turn(angle) distance = Stack.PopValue("distance") Turtle.Move(-distance) EndIf EndSub Photos from Flickr Figure 53 - Retrieving pictures from Flickr
  • 58. GraphicsWindow.BackgroundColor = "Black" GraphicsWindow.MouseDown = OnMouseDown Sub OnMouseDown pic = Flickr.GetRandomPicture("mountains, river") GraphicsWindow.DrawResizedImage(pic, 0, 0, 640, 480) EndSub Dynamic DesktopWallpaper For i = 1 To 10 pic = Flickr.GetRandomPicture("mountains") Desktop.SetWallPaper(pic) Program.Delay(10000) EndFor Paddle Game Figure 54 - Paddle Game GraphicsWindow.BackgroundColor = "DarkBlue" paddle = Shapes.AddRectangle(120, 12) ball = Shapes.AddEllipse(16, 16)
  • 59. GraphicsWindow.MouseMove = OnMouseMove x = 0 y = 0 deltaX = 1 deltaY = 1 RunLoop: x = x + deltaX y = y + deltaY gw = GraphicsWindow.Width gh = GraphicsWindow.Height If (x >= gw - 16 or x <= 0) Then deltaX = -deltaX EndIf If (y <= 0) Then deltaY = -deltaY EndIf padX = Shapes.GetLeft (paddle) If (y = gh - 28 and x >= padX and x <= padX + 120) Then deltaY = -deltaY EndIf Shapes.Move(ball, x, y) Program.Delay(5) If (y < gh) Then Goto RunLoop EndIf GraphicsWindow.ShowMessage("You Lose", "Paddle") Sub OnMouseMove paddleX = GraphicsWindow.MouseX Shapes.Move(paddle, paddleX - 60, GraphicsWindow.Height - 12) EndSub
  • 60. AppendixB Colors TODO: Describe colors+ hex Here’sa listof namedcolorssupportedbySmall Basic,categorizedbytheirbase hue. Red Colors IndianRed #CD5C5C LightCoral #F08080 Salmon #FA8072 DarkSalmon #E9967A LightSalmon #FFA07A Crimson #DC143C Red #FF0000 FireBrick #B22222 DarkRed #8B0000 Pink Colors Pink #FFC0CB LightPink #FFB6C1 HotPink #FF69B4 DeepPink #FF1493 MediumVioletRed #C71585 PaleVioletRed #DB7093 Orange Colors LightSalmon #FFA07A Coral #FF7F50 Tomato #FF6347 OrangeRed #FF4500 DarkOrange #FF8C00 Orange #FFA500 Yellow Colors Gold #FFD700 Yellow #FFFF00 LightYellow #FFFFE0 LemonChiffon #FFFACD LightGoldenrodYellow #FAFAD2 PapayaWhip #FFEFD5
  • 61. Moccasin #FFE4B5 PeachPuff #FFDAB9 PaleGoldenrod #EEE8AA Khaki #F0E68C DarkKhaki #BDB76B Purple Colors Lavender #E6E6FA Thistle #D8BFD8 Plum #DDA0DD Violet #EE82EE Orchid #DA70D6 Fuchsia #FF00FF Magenta #FF00FF MediumOrchid #BA55D3 MediumPurple #9370DB BlueViolet #8A2BE2 DarkViolet #9400D3 DarkOrchid #9932CC DarkMagenta #8B008B Purple #800080 Indigo #4B0082 SlateBlue #6A5ACD DarkSlateBlue #483D8B MediumSlateBlue #7B68EE Green Colors GreenYellow #ADFF2F Chartreuse #7FFF00 LawnGreen #7CFC00 Lime #00FF00 LimeGreen #32CD32 PaleGreen #98FB98 LightGreen #90EE90 MediumSpringGreen #00FA9A SpringGreen #00FF7F MediumSeaGreen #3CB371 SeaGreen #2E8B57 ForestGreen #228B22 Green #008000 DarkGreen #006400 YellowGreen #9ACD32 OliveDrab #6B8E23 Olive #808000 DarkOliveGreen #556B2F MediumAquamarine #66CDAA DarkSeaGreen #8FBC8F LightSeaGreen #20B2AA DarkCyan #008B8B Teal #008080 Blue Colors Aqua #00FFFF Cyan #00FFFF LightCyan #E0FFFF PaleTurquoise #AFEEEE Aquamarine #7FFFD4 Turquoise #40E0D0 MediumTurquoise #48D1CC DarkTurquoise #00CED1 CadetBlue #5F9EA0 SteelBlue #4682B4 LightSteelBlue #B0C4DE PowderBlue #B0E0E6
  • 62. LightBlue #ADD8E6 SkyBlue #87CEEB LightSkyBlue #87CEFA DeepSkyBlue #00BFFF DodgerBlue #1E90FF CornflowerBlue #6495ED MediumSlateBlue #7B68EE RoyalBlue #4169E1 Blue #0000FF MediumBlue #0000CD DarkBlue #00008B Navy #000080 MidnightBlue #191970 Brown Colors Cornsilk #FFF8DC BlanchedAlmond #FFEBCD Bisque #FFE4C4 NavajoWhite #FFDEAD Wheat #F5DEB3 BurlyWood #DEB887 Tan #D2B48C RosyBrown #BC8F8F SandyBrown #F4A460 Goldenrod #DAA520 DarkGoldenrod #B8860B Peru #CD853F Chocolate #D2691E SaddleBrown #8B4513 Sienna #A0522D Brown #A52A2A Maroon #800000 White Colors White #FFFFFF Snow #FFFAFA Honeydew #F0FFF0 MintCream #F5FFFA Azure #F0FFFF AliceBlue #F0F8FF GhostWhite #F8F8FF WhiteSmoke #F5F5F5 Seashell #FFF5EE Beige #F5F5DC OldLace #FDF5E6 FloralWhite #FFFAF0 Ivory #FFFFF0 AntiqueWhite #FAEBD7 Linen #FAF0E6 LavenderBlush #FFF0F5 MistyRose #FFE4E1 Gray Colors Gainsboro #DCDCDC LightGray #D3D3D3 Silver #C0C0C0 DarkGray #A9A9A9 Gray #808080 DimGray #696969 LightSlateGray #778899 SlateGray #708090 DarkSlateGray #2F4F4F Black #000000