Anda di halaman 1dari 37

Contents

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

10. ProblemsolvingusingDivideandConquer ......................................... 133

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.

The truth is: Children have a natural fascination for computers.


Weseeyoungchildrensomeofthembarelyoutofpreschoolhandlingwithease computers and gadgets such as videogame consoles and mobile devices. They browsetheInternet,connectwithfriendsusingsocialnetworks,playgames,oruse readymadesoftwarelikewordprocessors. Ourschoolshavesurelybeguntorealizethepromisesofthedigitalrevolution.Yet, thebestattemptsinmanyschoolstointroducethecomputertotheirstudentsdonot gobeyondtreatingitasaproductivitytool,i.e.asanassistantforroutinework. Whatreallyneedstohappenisthatourchildrentakethedriversseat,feelthereal power of computers, do creative work, and learn in the process. This book demonstratesanovelideathatcanachievethisexactgoal.

The new idea is to use Programming as a medium for learning.


Programmingmeanstappingintothecomputersimmensepowerbytalkingwithit directly.Throughprogramming,childrenusethecomputersterrificpowertodraw graphics, design animation, solve mathematical or word puzzles, and even build robots. ThisideawasfirstproposedinthefamousbookMindstormsbySeymourPapert and has subsequently been appreciated and praised by educators and parents all overtheworld.

SeriesonLearningthroughComputerProgramming

FunwithLogoProgrammingPart1

Children see the computer as a powerful assistant.


Through programming, students discover that the computer is a powerful and flexible tool. Using interesting ideas embedded in programming environments, students solve problems in their favorite subjects, and also develop interest in difficultsubjectslikeMathandPhysics.

Children learn through programming.


Childrenbecomeactivelearners,becausetheyexploreideasthroughahands onactivity. Theylearntothinkaboutandanalyzetheirownthinking,becausethatisthe onlywaytoprogramcomputers. They learn the technique of dealing with complex problems by breaking themintosmallersubproblems. Theylearnanewwayofthinking(calledcomputationalthinking). Intheworldofprogramming,answersarenotsimplyrightorwrong;this prepareschildrensmindsetforreallifeproblems. Childrensoveralllearningprocesstransformsfromacquiringfactstocreative andanalyticalthinking.

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

1. Getting Started with Logo

Why Learn Logo Programming?


Computer programming is one of the most exciting and powerful ways to use a computer.AndLogoisafascinatingprogramminglanguagethatpracticallyanyone childrenandadultsalikecanlearntoexploretheartofcomputerprogramming. Youmayask:whatissospecialaboutprogramming? Letuslookatthepicturebelow.

Figure11

ThefollowingLogoprogramdrawsthisfigure: REPEAT 6 [FORWARD 100 RIGHT 60]

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

2. Drawing with the Logo Turtle

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

Whatifwewantedtoeraseeverythingonthescreenandstartallover?Simple!We havedoneitoncealready.Type: ? CLEARSCREEN

SeriesonLearningthroughComputerProgramming

27

TeachingNewWords

4. Teaching New Words

Introduction
Wearenowabletocreateinterestingshapesanddesignsusingwords(procedures) thatLogoknows.TheseproceduresarecalledLogoprimitives. WouldntitbefunifwecouldteachLogonewwords? Forexample,itwouldbeniceifLogocoulddrawtheblocks(asshownbelow),when wesimplytypeblocks: ? blocks

Figure41

Inthischapter,wewillseehowwecanteachLogosuchnewwords. Rightnow,ofcourse,Logowilljustgiveustheerrormessage:I dont know how to blocks.

SeriesonLearningthroughComputerProgramming

45

TeachingNewWords

The Concept Called Abstraction (Just FYI)


Abstraction means capturing an idea into a word (or phrase). The new procedure Square is an abstraction of the idea of drawing a shape consisting of 4 sides. Defininganewwordthathasaspecificmeaningiscalledabstraction.Nobigdeal!

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

New words and old words:


Once defined, a new procedure is treated (by Logo) just like any other procedure that Logo already knows. There is no special treatment for new procedures. For example,ifyouwanttodefineyetanothernewprocedure,youcanmakeuseofboth old(primitives)andnewprocedures.

SeriesonLearningthroughComputerProgramming

55

5. Designs with Repeating Patterns

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.

How to Use the REPEAT Procedure


AskLogotosayIamanidiot4times! ? REPEAT 4 [PRINT [I am an idiot]] I am an idiot I am an idiot I am an idiot I am an idiot ThebasicformatofREPEATprocedureisasfollows: REPEAT N [List of Instructions] N is the number of times you want some actions to be repeated, and List of Instructionsgivestheactionsthatyouwanttoberepeated.

SeriesonLearningthroughComputerProgramming

63

DesignswithRepeatingPatterns

Drawing a star using REPEAT:


Ok, you think that REPEAT saves typing effort. And you are right. But, REPEAT is muchmoreinterestingthanjustbeingatypingassistant.Drawingastar(asbelow) givesusaperfectopportunitytoglimpsethepowerofREPEAT. Lets say we want to draw the point starasshownhere. It is basically a bunch of rays (line segments) coming out of a point. Right? Thisparticularstarhas20rays.Andthe gap(angle)betweeneachadjacentpairof raysisconstant.
Figure59

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

What We Learnt in this Chapter


1. Whenwedrawdesignsthathavearepeatingpattern,itgetstedioustotypethe sameinstructionsagainandagain.REPEATcomestorescue. 2. IntroductiontoREPEAT: a. REPEATisalaborsavingideanotforthecomputer,butforus. b. Itisalsoapowerfulideasomethingthatopensupnewpossibilities. 3. Webegintoseethevalueofusingatexteditor(likeNotepad)itkeepsarecord ofprogramsANDhelpsindebugging(troubleshooting). 4. ThekeysequenceCNTL-Qhelpsyougetthe?prompt(ALT-SonUCBLogo 6.0)ifyouwanttoterminateaprogram,orifyoudontseethe?promptfor anyreason. 5. It is important to first figure out (in your mind or notebook) what exactly is gettingrepeatedbeforeusingREPEAT.

Suggestions to Teachers/Parents
REPEATisanextremelypowerfulidea.Itwillhelptopracticeittoreallyappreciate itspowerandtounderstandhowbesttoutilizeit.Thinkofrepetitivepatternsand designswhichcanbedrawnusingthebasicTurtlecommands,andgivethemtothe childrenforpractice.

SeriesonLearningthroughComputerProgramming

69

6. Control through Input

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

8. Painting Our Designs

Introduction
Drawingfigures(outlines)usuallygoeshandinhandwithpainting,i.e.fillingareas withcolor.Andofcourse,colormakesourcreativeideasmorelivelyandexciting.

Figure81

Inthischapter,wewilllearnhowtopaintshapesinLogo,i.e.howtofillcolorinour designstomakethemlookbeautiful.Anditisquitestraightforward.Youcanthen drawprettydesignsasshownabove.

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.

The FSQUARE Procedure


Weknowthatthefollowingsetofinstructionsdrawsasquareofsize100andpaints itwiththeredcolor. ; Draw a square REPEAT 4 [FD 100 RT 90] ; Jump inside PU RT 45 FD 50 PD ; Set color to red and paint SETPC 4 FILL Tofinishthejob,weshouldgettheTurtlebacktoitsoriginalposition. ; Jump back outside PU BK 50 LT 45 PD WecanputalltheseinstructionsintoaprocedurecalledFSQUAREasbelow:

108

SeriesonLearningthroughComputerProgramming

9. Mirror Images, Flowers, and other Designs

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

Nested REPEAT (Just FYI):


Instead of using the square procedure, if wehad simplyused Logo instructions, ourprogramtodrawaflowerof18squareswouldlookasfollows: REPEAT 18 [ REPEAT 4 [FD 100 RT 90] RT 20 ] We have used a REPEAT inside another REPEAT. In programming lingo, this is callednestedREPEAT.Justforyourinformation! Sincewearecallingourdesignsasflowers,wewillcalleachofitssquaresasapetal.

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

10. Problem-solving Using Divide and Conquer

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

thatthereisverylittleroomformakingmistakes,andthecomponentscanbeused forotherdesignsalso. Selfstudy:Usingtheaboveprocedure,howwillyoudrawblockarrowspointing inotherdirections,suchas,NorthorSouth?

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

11. Drawing Curvy Objects

Introduction
With the exception of circles, we have so far only seen how to draw designs that containstraightlines.Wedontknowyethowtodrawnicecurvyobjectslikealotus flower,aflyingbird,orafish.Orabeautifulgardenasshownbelow:

Figure111

Inthischapter,wewilldiscoverthatwecandrawcurveswithoutneedingtolearn anythingnew;notevennewLogocommands.Wewillseethatitsalljustthemagic ofsimplegeometry.

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

12. Power of Polygons

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

13. Perspectives and Concentric Shapes

Introduction
Doyoulikethedesignshownbelow?

Figure131

CanyouguesshowitcanbedrawninLogo? Yes!Youcangiveaseriesofcirclecommandsandincreasethesizeslightlyevery time.But,thatwouldbetedious,wontit?

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

14. Fooled by RANDOM

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

15. Adding Life - Introduction to Animation

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

Shapes with Wings and Legs


Well, we dont mean literally, but in the sense that our stationary shapes will start movingaroundthescreenasiftheywerelivingormotorizedobjects. Inapreviouschapter,wewroteaproceduretodrawablockarrowasshownbelow. Now,wewillseehowwecanmakeitmovearoundthescreen.

Figure158

Tocreatethemovingarroweffect,wecouldtrythefollowingsteps: 1. Drawablockarrow. 2. Waitforashorttime. 3. Clearthescreen.

96

SeriesonLearningthroughComputerProgramming

16. Turtles that Climb Trees

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

Hint:ThefollowinginstructionswilldrawasinglecurvedlineandreturntheTurtle toitsbase(thiscodewouldactuallybelevel1oftherecursion): REPEAT 10 [FD 25 RT 5] REPEAT 10 [LT 5 BK 25] Youjusthavetorecursivelyimplantthesamecurvedlineatanumberofplaceson bothsides.

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

Anda mungkin juga menyukai