Upload
others
View
21
Download
0
Embed Size (px)
Citation preview
NetsBloxLesson:IntroductiontoListsMovieApp
Wehaveseenhowavariablecanstoresomevalue,likeanumberorsometext.However,avariablecanalsocontainalistofvalues(oritems,aswetypicallysay).Thatisaverypowerfulfeaturethatisusedprettywidelyinprogramming.Thevariablestabhasseveralblocksrelatedtolists:
Oneimportantthingtorememberisthatwehavetospecifyifwewantavariabletocontainalist.Wecannotaddanitemtoavariableifwedidnotmakeitalistfirst.Thisiswhattodo:
andthevariablestuffwilllooklikethisafterexecutingtheblock:
Thearrowkeysonthelistblockallowsustoaddorremoveitems.Ifwedonotwanttoadditemsinitially,westillneedtomakethevariablealist.Simplyeliminateallitemplaceholdersfromthelistblockbyclickingtheleftarrow.Thisiswhatweshouldhave:
Ifweforgettomakethevariablealistandtrytoaddanelementtoit,wegetasomewhatcrypticerrormessage:
Noticetheredhighlightaroundtheblocksto.Ifyouseethis,rememberthatthevariableneedstobealistbeforewecanaddanitemtoit.Asyouseeabove,toaddanelementtotheendofalist,simplyusetheaddblock.Toaccessindividualelements,wehavetousetheindexconcept.Youcansimplythinkoflistsasiftheirelementsarenumbered.Atthebeginningofthelististhefirstelementoritem#1,thencomesthesecondoritem#2etc.Thenwecansimplyaccesselementswiththeitemblock:
YoushouldseeCandthenEafterasecond.Toseehowlongalistis,thatis,howmanyelementsithas,usethelengthblock.Thatisusefulwhenwewanttoiteratethroughallelementsofalistaswe’llseelater.Theotherlistblocksarefairlyself-explanatory,sofeelfreetotrythemoutonyourown.Ourfirstexerciseistocreatealistof10randomnumbers:
Notmuchexplanationisneeded,right?Andthissimpleprogramillustratesthepowerofloopsandlists:bysimplychangingthe10toamillion,wecancreatealistofonemillionrandomnumberswithfourblocksofcode.Asamorecomplicatedtask,let’swriteaprogramthatfindsthelargestiteminthelist.Nowweneedtostarttothinkfirstandcomeupwithanalgorithmbeforewestartcoding.Thinkwhetheryoucanfigureitout,beforegoingtothenextpage…
Hereisthebasicidea:gothroughthelistonebyoneandcomparethecurrentitemtothemaxwefoundsofar.Ifitislargerthanthecurrentmax,wereplacethecurrentmaxwiththecurrentelement,otherwisewedonothing.Thisworksquitewell,butthereisonemoreimportantconsideration:whatshouldbethevalueofthecurrentlyfoundmaximumwhenwestart?Ifweknowthatallthenumberinthelistarepositive,forexample,wecansetthatvaluetozero.Thatensuresthatwewillfindagreatervalueatleastonceandhence,findthecorrectmax.Butwhatifthereisnolowerlimit?Howcanwemakesurethatwewillpickanelementfromthelistwhenwedothecomparison?Forexample,ifthelistcanhavenegativevaluestoo,zerowouldbeabadchoice.Why?Whatifalltheelementsarenegative,thenzeroisgreaterthanallofthem,soouralgorithmwillfindthewrongvalue,zero.Thesolutionistopickoneitemofthelistastheinitialmax.Typically,youwanttousethefirstitem,butitdoesnotreallymatterwhichone.Ifyoudothis,thentherearetwocases:1)eitherthisitemisthemaxandthenwe’llfindthecorrectvaluesincethealgorithmwillneverchangeitor2)thereisatleastonegreaterelementandthenouralgorithmwillfindit.Now,wearereadytoturnouralgorithmintocode:
Thereareafewobservationsworthmaking:
- Weusethelengthblocktodeterminehowmanytimestherepeatloopshouldrunsincewewanttolookateveryitem.
- Weneedtheindexvariabletobeabletogothroughallpossibleindexvalues.Westartat1andwedoneedtoincrementitsvalueateveryiteration.Itisacommonmistaketoforgetit:ifwedo,wewilllookatthefirstelementmanytimesbutnotconsideranyotherelement!
Fortunately,thereisaloopthatwasspecificallydesignedforlists.Togetit,weneedtoImportToolsusingtheFileorDocumentmenu.Oncewedothat,we’llgetabunchofextracustomblocksinthecustomtab.Thereisaforloopthatbasicallydoeswhatarepeatloopdoesbutwithabuilt-inindexvariablecalledibydefault.Dotryitout!Butthereisanevenbetterchoice,thefor eachloop.Hereishowwecansimplifyourmaximumfindingprogramwithit:
Thefor eachloopeliminatestheneedforanindexvariable.Thisloopsimplyiteratesthroughtheelementsofalist:thevariableitemwilltakeoneachitemonebyone.Thealgorithmisthesameasbefore,butthecodeismuchsimplerandcleaner.Feelfreetoexperimentwiththisprogrambycreatingalistoftensofthousandsofrandomnumbersandseehowourprogramfindsthemaximumquickly.Ifyoudothat,however,remembertoturnonTurboMode(settings/cogwheelmenu).Otherwise,theprogrammaytakeawhiletocomplete.Now,wearereadytoputlistsintopracticalusebycreatingaMovieApp.
TheMovieDBserviceTheMovieDBserviceprovidesfunctionalitysimilartothatofIMDb.IthasquiteafewRPCs:
Onsmallerscreens,youmaynotbeabletoseeallofthem.Fortunately,mostservicescomewithseveralpredefinedcustomblocks.IntheFileMenuselectServicesandthenfromthelistthatpopsupclickMoviedatabase.Afterafewseconds,thecustomtabwillhaveseveralnewblocks:
MostofthesearesimplywrappersaroundRPCcalls.Forexample,ifyourightclickonthemovies matchingblockandselectEdit,thisiswhatyou’llsee:
ItisuptoyouwhetheryoupreferthesecustomblocksorcallingtheRPCsdirectly.
Let’sseewhathappenswhenweactuallyuseoneofthese:
Whatisthislistofnumbers?EachmovieinthedatabaseisassociatedwithauniqueIDandthatiswhatyouseehere.TheRPCreturnstheIDsofallthemovieswhosetitlecontainsthewordWolverine(tobemoreprecise,thefirst20iftherearemorethan20).Tomakeuseofit,let’sseewhatthetitleofthefirstmovieonthatlist:
Firstwecallthemovies matchingcustomblock(that,inturn,callstheappropriateRPC),thenwetakethefirstitemofthereportedlistandthenusethatmovieIDasaninputtothemovieTitleRPCwhichreturnsthetitle,Logan.TheMovieAppNowwearereadytowriteanactualprogramaboutmovies:Let’scyclethrewalltheWolverinemoviesandshowtheirposters:
First,wegetallthemoviesinalistandthenweusethefor eachloopthatisthebesttovisitallitemsinalist(youneedtousetheFilemenuImportToolstogetthefor eachloopundertheCustomtab.).TherearetwonewRPCsweusehere:themoviePosterPathwillreturnaURLthatidentifiestheimagefileinthedatabase.SoweuseitasaninputtothegetImageRPCtogettheactualimageandswitchthecostumetoit.Sincesomemoviesdonothaveposters,wedisplaythemovietitlesalso.Hereisalinktotheprogram(withsomeminordifferences,seewhetheryoucanspotthem…):https://editor.netsblox.org/?action=present&Username=ledeczi&ProjectName=MoviePostersAslightlymorecomplicatedprogramdisplaysallthephotosofthethreeleadingcastmembersofamovie.Ithasthreesprites;eachisresponsiblefordisplayingphotosofonecastmember.Herearethescriptsofthefirstone:
Whenthegreenflagisclicked,wegetthefirstitemofthelistofmoviesmatching“HiddenFigures.”ThenweusethemovieCastPersonIDsRPCtogetalistofcastmemberIDs.Thenwebroadcastaneweventsignalingthatwearereadytocyclethroughallthephotos.Wealsosetthepositionandsizeofthesprite.TheCyclePhotoscustomblockisshownbelow:
IttakesapersonIDasaninput(actorvariableinsidetheblock).ThenweusethepersonImageFilePathswhichwillreturnalistofURLstoallavailablephotosofthegivenpersoninthedatabase.Thenwe’llcyclethroughallthepictures,leavingeachupfor2seconds.Sincewedothisinaforeverloop,thiswillgoonuntilwepresstheredstopsign.Theothertwospritesareverysimilar,butevensimpler.Thesecondoneisinthecenter,soitspositionissetto00.
Whentheshoweventoccurs,itsimplycallstheCyclePhotoscustomblockwiththesecondelementofthecastlist.Checkbackonthepreviouspageandseehowthefirstspriteusedthefirstelementofthecast.Similarly,thethirdsprite(notshown)hasadifferentpositionandusesthethirditemformthecastlist.Thisisaperfectillustrationwhycustomblocksareveryuseful:weusedthesameoneinthethreesprites;eachtimewithadifferentcastmember.Hereistheprogram:https://editor.netsblox.org/?action=present&Username=ledeczi&ProjectName=CastShowForafunmovieguessinggame,trythisproject:https://editor.netsblox.org/?action=example&ProjectName=Movies