netsblox lesson: introduction to lists movie app lesson lists and movies.pdf · netsblox lesson:...

9
NetsBlox Lesson: Introduction to Lists Movie App We have seen how a variable can store some value, like a number or some text. However, a variable can also contain a list of values (or items, as we typically say). That is a very powerful feature that is used pretty widely in programming. The variables tab has several blocks related to lists: One important thing to remember is that we have to specify if we want a variable to contain a list. We cannot add an item to a variable if we did not make it a list first. This is what to do: and the variable stuff will look like this after executing the block: The arrow keys on the list block allows us to add or remove items. If we do not want to add items initially, we still need to make the variable a list. Simply eliminate all item placeholders from the list block by clicking the left arrow. This is what we should have:

Upload: others

Post on 03-Apr-2020

16 views

Category:

Documents


0 download

TRANSCRIPT

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