Logo Programming Book Preview
Logo Programming Book Preview
SectionI:BasicsofLogo ....................................................... 11
1. 2. 3. 4. 5. GettingStartedwithLogo .......................................................................... 13 DrawingwiththeLogoTurtle ................................................................... 23 InstructionsandProcedures....................................................................... 38 TeachingNewWords.................................................................................. 45 DesignswithRepeatingPatterns............................................................... 61
SectionII:PowerfulIdeas..................................................... 73
6. 7. 8. 9. ControlthroughInput................................................................................. 75 DrawingPolygonsandCircles .................................................................. 87 PaintingOurDesigns ................................................................................ 105 MirrorImages,Flowers,andotherDesigns........................................... 115
SectionIII:Appendices....................................................... 153
AppendixA:LogoPrimitives(BuiltinProcedures) .................................... 155 AppendixB:InstallingLogo ............................................................................ 160
Contents
SectionIV:AdvancedExploration........................................ 7
11. DrawingCurvyObjects ................................................................................ 9 12. PowerofPolygons ....................................................................................... 35 13. PerspectivesandConcentricShapes ......................................................... 57
SectionV:ProgrammingAdventures................................. 77
14. FooledbyRANDOM................................................................................... 79 15. AddingLifeIntroductiontoAnimation................................................. 91 16. TurtlesthatClimbTrees............................................................................ 105 17. LookingBackandFinalProject................................................................ 129
SectionVI:Appendices....................................................... 133
AppendixC:AdditionalLogoPrimitives(BuiltinProcedures) ................ 135
Preface
Theotherday,whileworkingonthisbook,oneoftheauthorswasstrugglingtoget afeatureinhiswordprocessortowork.His8yearoldsonwaswatchingcuriously from behind to see what his Dad was up to on his shining new laptop. When he noticedDadshesitation,heleapedoverhisDadsshoulders,clickedafewplaceson thescreenandexclaimed,Thereyougo,Dad!Isthatwhatyouwanted? Dad was naturally very pleased with his son, and also amazed at his sons knowledgeofthisnotsocommonfeature.
SeriesonLearningthroughComputerProgramming
FunwithLogoProgrammingPart1
References
1. Mindstorms:Children,Computers,andPowerfulIdeasbySeymourPapert, ProfessoratMIT.(Alsohttp://papert.org/:Papertswebsite) 2. ComputerScienceLogoStylebyBrianHarvey,ProfessoratUCBerkeley. 3. AppleLogoforTeachersbyEarlBabbie(WadsworthPublishers,1984) 4. http://www.cs.berkeley.edu/~bh/:ArticlesbyProf.BrianHarvey,UC Berkeley. 5. http://el.media.mit.edu/logo-foundation/:WebsiteofLogoFoundation 6. http://scratch.mit.edu:WebsiteoftheScratchproject
SeriesonLearningthroughComputerProgramming
Figure11
SeriesonLearningthroughComputerProgramming
13
FunwithLogoProgrammingPart1
YoucanalsoeasilydrawitusingdrawingsoftwarelikeMicrosoftPaint. So, whats the difference? Why should anyone bother to learn programming when readymadesoftwarecandothejob? Well,now,seethepicturebelow.BymodifyingyourLogoprogramjustalittleyou cancreatethisnewpicture. REPEAT 6 [ REPEAT 6 [FORWARD 50 RIGHT 60] RIGHT 60 ]
Figure12
Now,trydrawingthatusingMicrosoftPaint!! This is just one example of how Programming gives you a special power that no readymadesoftwarecan.Programminggivesyouadirecthotlinetothebrainofthe computer.Itallowsyoutotryoutyourcreativeideas.Andmostofall,itisalotof fun!
14
SeriesonLearningthroughComputerProgramming
Introduction
Inthepreviouschapter,wegotaglimpseofthepowerof Logoprogramming.We startedtalkingwiththecomputerusingwordslikePRINT. CanwegetLogotodrawthingsonthescreen,liketheonesshownbelow?
Figure21
TheanswerisYes!Wecancreatetheseandmanyotherexcitingdrawingswiththe helpoftheLogoTurtle!Letusgetintroducedtothisnewfriend.
SeriesonLearningthroughComputerProgramming
23
DrawingwiththeLogoTurtle
? RIGHT 90
Figure24
UsingthecommandRIGHT 90,wetoldtheTurtletoturnrightby90degrees. Now, we can askthe Turtle to move forward again by typing the following. ? FORWARD 100
Figure25
Thisisgettinginteresting,isntit!Canyoucompletethepictureanddrawasquare? Here is how we can draw the remaining sides of the square and bring the Turtle backtoitsoriginalposition. ? RIGHT 90 ? FORWARD 100 ? RIGHT 90 ? FORWARD 100 ? RIGHT 90
Figure26
SeriesonLearningthroughComputerProgramming
27
TeachingNewWords
Introduction
Wearenowabletocreateinterestingshapesanddesignsusingwords(procedures) thatLogoknows.TheseproceduresarecalledLogoprimitives. WouldntitbefunifwecouldteachLogonewwords? Forexample,itwouldbeniceifLogocoulddrawtheblocks(asshownbelow),when wesimplytypeblocks: ? blocks
Figure41
SeriesonLearningthroughComputerProgramming
45
TeachingNewWords
Play Time:
DefinethefollowingnewLogoprocedures.Verifythatthesenewprocedureswork asexpected. 1. A procedure called Myinfo that clears the screen and shows your full name, schoolname,andcity. 2. Proceduresforgeometricshapeslikerectangleandtriangle. 3. ProceduresforEnglishletters(stickorblock)likei,H,E,orA. 4. Procedureforrectanglewave.
Logo Challenge
CanyouwriteaLogoproceduretodraw thisdesign?
Figure46
SeriesonLearningthroughComputerProgramming
55
Introduction
Takealookatthefollowingdesign.Itappearslikeapowerfulmulticolorstar.
Figure51
Do we know enough of Logo to draw this star? Probably not. There is actually a powerfulnewwaytodrawthisstar(andmanyotherexcitingdesigns)quiteeasily. Readontolearnaboutit.
SeriesonLearningthroughComputerProgramming
61
DesignswithRepeatingPatterns
Howaboutdrawingarectanglewave?
Figure54
Doyouseearepeatingpatternineachofthese? Justlikethestaircase,thereisabasicpattern(thatisrepeated)ineachoftheabove pictures. If we can work out the Logo instructions for each basic pattern, we can simplytypetheseinstructionsanumberoftimestogetthefinalpicture. So,foreachofthesepicturesacertainsetofinstructionsneedstoberepeated. Fortunately, instead of us having to type these instructions repeatedly, we can simplyuseaprocedurethatLogoprovidestoperformtherepetitionforus.Canyou guessthenameofthatLogoprocedure? Yes!Youguessedcorrectly.ItiscalledREPEAT.
SeriesonLearningthroughComputerProgramming
63
DesignswithRepeatingPatterns
LetsseehowwewouldgoaboutdrawingsuchastarinLogo. Tosimplifytheproblem,letusfirsttrya starwithfewerrays. Thisstarhas8rays.Wewillassumethat the Turtle is initially at the center. After drawingeachray(FDandBK),theTurtle hastotakearightturn.Sincethereare8 equal turns, each of these turns (angles) mustbe45(360/8).
Figure510
SeriesonLearningthroughComputerProgramming
65
DesignswithRepeatingPatterns
Suggestions to Teachers/Parents
REPEATisanextremelypowerfulidea.Itwillhelptopracticeittoreallyappreciate itspowerandtounderstandhowbesttoutilizeit.Thinkofrepetitivepatternsand designswhichcanbedrawnusingthebasicTurtlecommands,andgivethemtothe childrenforpractice.
SeriesonLearningthroughComputerProgramming
69
Introduction
With the ideas we have learnt so far Turtle commands, creating new procedures, andtheREPEATcommandcanwedrawsomeofthedesignsshownbelow?
Figure61
Weprobablycan.WecanuseourPoint.Starproceduretodrawthestars.But,we willhavetoconstantlymodifytheproceduretodrawthevarietyshownabove.Logo offers an idea that allows a single star procedure to draw any and all of the stars above.Wontthatbeinteresting?So,readonthischaptertolearnthisnewidea.
SeriesonLearningthroughComputerProgramming
75
ControlthroughInput
Step4istoputthisnameattheendoftheTOlineasshownbelow.ThistellsLogo thatsizeistheinputofHexagon. TO Hexagon :size Step 5 (and the final step) is to put the new name wherever we refer to size of the hexagon. Aftermakingallthesechangesthisiswhatweget: ERASE "Hexagon TO Hexagon :size REPEAT 6 [FD :size RT 60] END Note: Dont forget the colon it tells Logo that the word that follows is an input. Without:Logowilltreatthewordasprocedurename. Bingo!OurhexagonprocedurewillnowtakeinputjustlikeFDorRT. ? Hexagon not enough inputs to hexagon Withinputsweget: Hexagon 100 Hexagon 50
Figure63 Figure64
SeriesonLearningthroughComputerProgramming
79
Introduction
Drawingfigures(outlines)usuallygoeshandinhandwithpainting,i.e.fillingareas withcolor.Andofcourse,colormakesourcreativeideasmorelivelyandexciting.
Figure81
SeriesonLearningthroughComputerProgramming
105
FunwithLogoProgrammingPart1
Andthenthejumpandpaintjob: PU RT 45 FD 10 PD SETPC 2 FILL Since the nearest closed shape for the Turtle (when FILL is called) is the space betweenthetwosquares,thatswhatgot painted.
Figure88
Play Time:
1. Write a procedure called fsquare that takes 2 inputs: size and color, and drawsapaintedsquare.Forexample,fsquare 100 2"willdrawasquareof size 100 painted green. fsquare 300 13" will draw a square of size 300 paintedpurple(Solutionexplainedinthefollowingsection). 2. Figure out how you can paint a triangle. Write a procedure ftriangle with sizeandcolorinputs.
108
SeriesonLearningthroughComputerProgramming
Introduction
Using a basic shape (such as a simple square), we can create a lot of entertaining designsbymovingitindifferentways.Imaginethatyouhavecutoutashapedrawn onpaper.Youcoulddrawitsoutlinebyplacingitanywhereonadrawingpaper.Or, you could flip it along an edge to get a mirror image. Or, you can hold one of its cornerswitharealpinandrotateitaroundthispin,whiledrawingoutlinesallalong togetaflowerypattern. WewilllearnhowtodothesecoolthingsusingsimpletechniquesinLogo.
Hopping Around
Thisisthesimplestofthepossiblemovements.Seebelow:
Figure91
SeriesonLearningthroughComputerProgramming
115
FunwithLogoProgrammingPart1
Play Time:
1. Write a procedure called sqflower (short for flower of squares) that takes 2 inputs:sizeandanumberN:sizeisforthesizeofeachsquare,andNspecifies thenumberofpetals.So,forexample: sqflower 100 5shoulddrawaflowerof5squareseachofsize100 sqflower 50 20shoulddrawaflowerof20squareseachofsize50 2. Replace the square with a triangle and draw various types of triangle flowers: dumbbell(2petals),fan(4petals),andsoon.
Figure914
Figure915
Figure916
3. Drawflowersofotherpolygonshapes:pentagon,hexagon,etc.
122
SeriesonLearningthroughComputerProgramming
FunwithLogoProgrammingPart1
Key Observations
REPEAT isnot justa handy little commandthat saves typing; amazing new possibilities open up that would be impossible without REPEAT. (Imagine drawingaflowerofcircleswithoutthehelpofREPEAT). Before using REPEAT, you must first figure out the repeated basic pattern, whichmayconsistofavisiblepattern(lines)andaninvisiblepattern(angles andgaps). Inordertofigureoutthebasicpatterninacomplicateddesign,simplytrace the motion of Turtle from the central point of the design and note all lines andturns.Remember,inaregularpolygon,alllinesandturnsmustbeequal. Programming allows infinite experimentation so dont be afraid to try out your ideas and hunches. If they turn out to be incorrect (weird stuff gets drawn on the screen), either pat yourself on the back for amazing new discoveries (if the weird stuff looks pretty) or go back to your notebook, makechanges,andtryagain. Donotforgettosolvetheprobleminyourmind(andnotebook)first,before writingLogoprograms.RememberthatLogoisnotgoingtohelpyousolve the problem; it will simply replicate all the mistakes that you have made yourselfinyourdesign. Thegeometryyoulearntinschooldoescomehandyindrawingdesigns.In turn, Logo programming will help you understand and appreciate your schoolgeometry. When you define a new Logo procedure, define it without any input first. Makesureitworksasexpected.Andthenaddinputsoneatatime,testing theprocedureateverystep.
126
SeriesonLearningthroughComputerProgramming
Introduction
Wehavebeenlearningalotoflittletricksofprogrammingsofarandapplyingthem to write lots of little programs. Now, we are ready to write some seriously cool programs.Seethecollagebelow.
Figure101
But,beforeyoustartchurningoutLogoprogramsforthesefancyobjects,letstakea couple of simple examples and understand the process of how to go about developingsuchprograms.
SeriesonLearningthroughComputerProgramming
133
FunwithLogoProgrammingPart1
Play Time:
Drawacollageofblockarrowsofdifferentsizes,pointingindifferentdirections,and ofdifferentcolorsandthickness.
House Example
Lets go through another interesting exampletomakesureweunderstandthe Divideandconquer method. We will attempt to draw the house as shown here. First,wetakeastepbackandtakeakeen look at the design and ask the standard question:
Figure108
What is this design made up of? Can we break it apart into meaningful reusable componentsorparts? Wecomeupwiththeanswer:Yes,weseethreeparts:awall,aroof,andawindow.
Figure109
138
SeriesonLearningthroughComputerProgramming
Introduction
With the exception of circles, we have so far only seen how to draw designs that containstraightlines.Wedontknowyethowtodrawnicecurvyobjectslikealotus flower,aflyingbird,orafish.Orabeautifulgardenasshownbelow:
Figure111
SeriesonLearningthroughComputerProgramming
DrawingCurvyObjects
Themedianofthepetalwouldbeathalftheangleoftherightturn(i.e.45).So,in ordertogetasymmetricpetalaroundtheTurtlespresentorientation,weshouldtilt theTurtletotheleftby45beforedrawingthepetal. ERASE "petal2 TO petal2 :size ; size is diameter (of the full circle) LT 45 REPEAT 2 [ q.dcircle :size RT 90 ] RT 45 END Petal2 150
Figure1111
Play Time:
1. Drawacandleasshownbelow.
Figure1112
SeriesonLearningthroughComputerProgramming
15
DrawingCurvyObjects
;Quarter circle anti-clockwise. Size is diameter. ERASE "Q.dcircleL TO Q.dcircleL :size REPEAT 90 [FD :size*3.14159/360 LT 1] END Usingacombinationofrightquartercircleandleftquartercirclewecancreateanice lookingwave: ERASE "waves TO waves :n :size REPEAT :n [ q.dcircle :size q.dcircleL :size ] END waves 3 40 Selfstudy:Makethewaveaboveappearhorizontal.
Figure1126
Logo Challenges
Chestnut leaves:
Thefigureshowstheleafpatternof a Chestnut tree. The amazing thing isthatallChestnutleavesappearin the exact same pattern as shown in Figure 1127: always in groups of 7 with one large leaf at the top, and remaining 6 appearing as mirror images. Hint: First write a procedure to draw an individual leaf (use a size inputtocontrolthesizeoftheleaf). Then,designthepatternabove.
Figure1127
SeriesonLearningthroughComputerProgramming
21
Introduction
Earlier,weusedourknowledgeofgeometrytodrawinterestingbutsimpledesigns usingregularpolygons.Wecanexplorethisideafurtheranddevelopsomeexpertise inthisveryexcitingfieldofGeometricDesigns. You must have seen patterns like the one shown here used for tiles, cutlery, architectures, and even paintings. All that we really need to know to create such designsispolygons,TurtleRoundTripprinciple,andtheLogocommandsthatwe alreadyknow.Areyouinterested?Then,readon.
Figure121
SeriesonLearningthroughComputerProgramming
35
FunwithLogoProgrammingPart2
Reversing Sides
Whatwillweneedtodotodrawafigureshownbelow? What if you were told that this figure is related to the next figure in some way? Clearly, the outside octagon has been madetohide. But,howdowegetthefollowingfigure inthefirstplace?
Figure129
Hereisthecodethatwillproducethedesign. REPEAT 8 [ ;Draw the inside triangle Polygon 100 3 ;Draw side of octagon FD 100 RT 360/8 ] Itsreallythesameideaasbefore,except this time, the triangle is drawn on the insideofthemainoctagon.
Figure1210
Youcouldgetridoftheoctagonintwoways:(1)avoiddrawingitinthefirstplace thiswillrequireyoutomodifythetriangleprocedure,or(2)UsePENERASEtoerase theOctagon.Thefollowingcodeshowsthesecondapproachtogetthestarshown above. PENERASE REPEAT 8 [FD 100 RT 360/8] PENPAINT
40
SeriesonLearningthroughComputerProgramming
Introduction
Doyoulikethedesignshownbelow?
Figure131
SeriesonLearningthroughComputerProgramming
57
FunwithLogoProgrammingPart2
Howaboutdrawingthisbeautifuldesignshownnext?
Figure132
CanyouguesshowthisdesigncanbedrawninLogo? If you look carefully, you will see a series of squares drawn around a point, with each square slightly bigger than the previous one. Once again, you could give a series of square commands and increase the size slightly every time. But, that wouldbehorriblytedious,wouldntit! Continuereadingthischapter,ifyouwouldliketolearnamuchmoreelegantand simplerwayofdrawingthissortofdesignsinwhichthereisrepetitionforsure,but thereisatwistaftereachrepetition.
Counting Repetitions
Imagine that you want to run around a tree, and your friend is watching you standingaside.Youcouldaskhimtocount1,2,3asyougoaroundthetree.So, youcouldaskhimanytime,Hey,whatroundamIdoingnow?Andhewouldtell you,Itsthe9thround,orsomethinglikethat.Inasense,yourfriendisyourcounter.
58
SeriesonLearningthroughComputerProgramming
Introduction
Oneofthemostexcitingideasinprogramming,andeveninreallife,istheideaof randomness. We often say things like, Oh, that person is so random! Philosophers often muse about the randomness of events. The industry of gambling is entirely basedontheideaofrandomoutcomes.Takealookatthepicturebelow:
Figure141
SeriesonLearningthroughComputerProgramming
79
FooledbyRANDOM
As you can see, we get this weird looking window. In fact, your window willmostlikelylookquitedifferent!Get it?ItstheRANDOMthing!
Figure144
Now,ifwesimplyputthisinaloopand run it a number of times, we get something that looks like a shattered window! REPEAT 50 [ REPEAT 4 [ square (RANDOM 150) RT 90 ] ] Figure145 Ifyouincreasetheouterloopcounttoareallylargenumber(like10000)youwilljust getalargepaintedsquare.Thatsbecause,whenrun10000times,RANDOMendsup givingpracticallyallpossiblenumbersintheavailablerange(0to100),andso,we get squares of all possible sizes drawn very close to each other giving the effect of FILL. Insight:Ifcalledalargenumberoftimes,RANDOMusuallyendsupgivingevery value in the given range although this is not guaranteed, nor is it predictable howoftenitwillgiveaparticularvalue. So,asyousee,theapplicationofRANDOMreallydependsonourcreativity.
SeriesonLearningthroughComputerProgramming
83
Introduction
Animationmeanslife.Animationmeansmotionandaction.Animationmeansfun! ThegoodnewsisthatwecandoanimationinLogo.Sofar,ourLogoprogramshave produced nicelooking graphics and images. We are now ready to make our Logo drawingscomealiveandperformactions.Asyoumightknowalready,animationis an illusion of motion (or action) created by persistence of vision and a successive displayofslowlychangingpictures. Foraquickdemoofanimation,justrunthefollowingprogramandwatchthescreen. PressCtrlQ(AltSinUCBLogo6.0)whenyouhaveseenenough! REPEAT FOREVER [ FD 100 BK 100 ; Draw a line WAIT 5 ; Wait for some time PENERASE ; Turn the Eraser mode on FD 100 BK 100 ; Erase the line drawn earlier PENPAINT ; Restore the Pen RT 5 ; Turn right by 5 degrees ] Isnt it interesting? Can you figure out how the program works by reading the comments in the code? (Note: REPEAT FOREVER is a special form of REPEAT in whichthingsgoon,well,forever!) ReadfurthertolearnhowtowriteanimationprogramsinLogo.
SeriesonLearningthroughComputerProgramming
91
FunwithLogoProgrammingPart2
ERASE "Bcwheel TO Bcwheel SETPENSIZE 5 REPEAT 100 [ FD 50 BK 50 RT 360/100 ] SETPENSIZE 20 REPEAT 10 [ PU FD 50 FD 20 PD FD 50 BK 50 PU BK 20 BK 50 PD RT 360/10 ] END CS SETBG 7 SETPC 0 Bcwheel
Figure157
Figure158
96
SeriesonLearningthroughComputerProgramming
Introduction
YouprobablynoticedtheFernbranchandTropicaltreedrawnontheveryfirstpage ofthisbook.Heretheyareoncemore:
Figure161
Believe it or not, these figures have been drawn using Logo programs programs containingnotmorethan15instructionseach!Theyarebasedonaninterestingidea calledRecursion. Continuereadingthischaptertolearnaboutrecursionandhowtodrawthesesortof designsinLogo.
SeriesonLearningthroughComputerProgramming
105
TurtlesthatClimbTrees
Logo Challenge
Thetreesshownnexthavethefollowingnewfeatures: - Thetreelooksdifferenteverytimeyoucalltheinstruction(evenifallinputsare thesame) - The tree shows fruit at some places. The fruit shows up at random places, and theamountoffruitiscontrolledthroughaninput. Hints:(1)Obviously,wehaveusedRANDOMtomakethingshappendifferentlyevery time.(2)Todrawthefruit,addcodejustbeforetheSTOPcommand,becausethats wherethebranchesend.
Figure1618
SeriesonLearningthroughComputerProgramming
121