Computer Science in Algebra
Transcript of Computer Science in Algebra
Computer Sciencein Algebra
Instructor Handbook
2015-2016
Powered by
Bootstrap
UUNPLUGGED
VideoGamesandCoordinatePlanesLessontime:30-60Minutes
LESSONOVERVIEWStudentsdiscussthecomponentsoftheirfavoritevideogamesanddiscoverthattheycanbereducedtoaseriesofcoordinates.TheythenexplorecoordinatesinCartesianspace,identifyingthecoordinatesforthecharactersinagameatvariouspointsintime.Oncetheyarecomfortablewithcoordinates,theybrainstormtheirowngamesandcreatesamplecoordinatelistsfordifferentpointsintimeintheirowngame.
LESSONOBJECTIVESStudentswill:
Createadatamodelthatdescribesasimplevideogame.Describethemovementsofvideogamecharactersbytheirchangeincoordinates.
ANCHORSTANDARDCommonCoreMathStandards6.NS.8:Solvereal-worldandmathematicalproblemsbygraphingpointsinallfourquadrantsofthecoordinateplane.Includeuseofcoordinatesandabsolutevaluetofinddistancesbetweenpointswiththesamefirstcoordinateorthesamesecondcoordinate.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)LearningaLanguage
Activity:VideoGamesandtheCoordinatePlane3)ReverseEngineeraDemo4)CoordinatePlanes
Wrap-up5)BrainstormingaGame
TEACHINGGUIDE 1
MATERIALS,RESOURCES,ANDPREPFortheStudent
ReverseEngineeringTable(inthestudentworkbook)VideogameDesignTemplate(inthestudentworkbook)
FortheTeacherLessonslidedeckExampleGamePrintedcutoutsoftheNinja,Dragon,andUnicorn
GETTINGSTARTED1)VocabularyThislessonhasthreenewandimportantwords:Apply-useagivenfunctiononsomeinputsReverseEngineer-toextractknowledgeordesigninformationfromanexistingproductSprite-agraphiccharacteronthescreen.Sometimescalledabitmaporanimage.
2)LearningaLanguageWelcometoCode.orgCSinAlgebra!Inthiscourseyou’llbelearninganewprogramminglanguage-awaytotellcomputersexactlywhatyouwantthemtodo.JustlikeEnglish,SpanishorFrench,aprogramminglanguagehasitsownvocabularyandgrammarthatyou’llhavetolearn.Fortunately,thelanguageyou’llbeusingherehasalotincommonwiththesimplemaththatyoualreadyknow!Connectthismaterialwiththingsstudentsalreadyknow:
Whatmakesalanguage?Doesanyonespeakasecond(orthird)language?Doyouspeakadifferentlanguagethanyourparents/grandparents?Aretherelanguagesthatsharefeatures,suchasacommonroot(Romance,Germanic)orasimilaralphabet(Latin,Cyrillic,Arabic,Kanji)?Aretherelanguagesthataredesignedforspecificpurposesorwithincertainconstraints(signlanguage,Esperanto)?Mathisalanguage,justlikeEnglish,Spanish,oranyotherlanguage!
Weusenouns,like"bread","tomato","mustard"and"cheese"todescribephysicalobjects.Mathhasvalues,likethenumbers1,2or3,todescribequantities.Wealsouseverbslike"toast","slice","spread"and"melt"todescribeoperationsonthesenouns.Mathematicshasfunctionslikeadditionandsubtraction,whichareoperationsperformedonnumbers.Justasyoucan"slicepieceofbread",apersoncanalso"addfourandfive".
Amathematicalexpressionislikeasentence:it’saninstructionfordoingsomething.Theexpression4+5tellsustoadd4and5.Toevaluateanexpression,wefollowtheinstructionsintheexpression.Theexpression4+5evaluatesto9.
ACTIVITIES:3)ReverseEngineeraDemoLet’sbeginbyexploringasimplevideogame,andthenfiguringouthowitworks.Openthislinktoplaythegame,andspendaminuteortwoexploringit.Youcanusethearrowkeystomovetheupanddown-trytocatchtheunicornandavoidthedragon!Thisgameismadeupofcharacters,eachofwhichhasitsownbehavior.Theunicornmovesfromthelefttotheright,whilethedragonmovesintheoppositedirection.Theninjaonlymoveswhenyouhitthearrowkeys,andcanmoveupanddown.Wecanfigureouthowthegameworksbyfirstunderstandinghoweachcharacterworks.
2
Directions:1)Dividestudentsintogroupsof2-4.2)Provideeachstudentwithacopyofthereverse-engineeringtable.3)Asstudentsdemothegame,askthemtofillinthe"Thinginthegame..."columnwitheveryobjecttheyseeinthegame.4)Discusswiththewholegroupwhichthingstheycameupwith.Characters?Background?Score?5)Next,foreachofthethingsinthegame,fillinthecolumndescribingwhatchanges.Size?Movement?Value?6)Askstudentstosharebackwiththewholegroup.Notehowstudentsdescribedchanges-howdetailedwerethey?Whatwordsdidtheyusetodescribemovement?
4)CoordinatePlanesComputersusenumberstorepresentacharacter’spositiononscreen,usingnumberlinesasrulerstomeasurethedistancefromthebottom-leftcornerofthescreen.Forourvideogame,wewillplacethenumberlinesothatthescreenrunsfrom0(ontheleft)to400(ontheright).WecantaketheimageoftheDragon,stickitanywhereontheline,andmeasurethedistancebacktothelefthandedge.AnyoneelsewhoknowsaboutournumberlinewillbeabletoduplicatetheexactpositionoftheDragon,knowingonlythenumber.WhatisthecoordinateoftheDragonontherighthandsideofthescreen?Thecenter?WhatcoordinatewouldplacetheDragonbeyondthelefthandedgeofthescreen?
Byaddingasecondnumberline,wecanlocateacharacteranywhereonthescreenineitherdimension.Thefirstlineiscalledthex-axis,whichrunsfromlefttoright.Thesecondline,whichrunsupanddown,iscalledthey-axis.A2-dimensionalcoordinateconsistsofboththex-andy-locationsontheaxes.SupposewewantedtolocatetheNinja’spositiononthescreen.Wecanfindthex-coordinatebydroppingalinedownfromtheNinjaandreadthepositiononthenumberline.They-coordinateisfoundbyrunningalinetothey-axis.Acoordinaterepresentsasinglepoint,andanimageis(bydefinition)manypoints.Somestudentswillaskwhetheracharacter’scoordinatereferstothecenterofthe
image,oroneofthecorners.Inthisparticularprogram,thecenterservesasthecoordinate-butotherprogramsmayuseanotherlocation.Theimportantpointindiscussionwithstudentsisthatthereisflexibilityhere,aslongastheconventionisusedconsistently.Whenwewritedownthesecoordinates,wealwaysputthexbeforethey(justlikeinthealphabet!).Mostofthetime,you’llseecoordinateswrittenlikethis:(200,50)meaningthatthex-coordinateis200andthey-coordinateis50.Dependingonhowacharactermoves,theirpositionmightchangeonlyalongthex-axis,onlyalongthey-axis,orboth.Lookbacktothetableyoumade.CantheNinjamoveupanddowninthegame?Canhemoveleftandright?Sowhat’schanging:hisx-coordinate,hisy-coordinate,orboth?Whatabouttheclouds?Dotheymoveupanddown?Leftandright?Both?
LESSONTIP Thekeypointforstudentshereisprecisionandobjectivity.Therearemanypossiblecorrectanswers,butstudentsshouldunderstandwhyanysolutionshouldbeaccurateandunambiguous.Thisrequiresstudentstoproposesolutionsthatshareacommon"zero"(thestartingpointoftheirnumberline)anddirection(literally,thedirectionfromwhichacharacter’spositionismeasured).
3
Derivedfrom
OPTIONALACTIVITY:Dependingontimingandthebackgroundofyourstudents,havingonestudentplaceacharacteronalargegraphandanotherstudentstatingthecoordinatesisexcellentpractice.Studentsoftenneedextrapracticerememberingwhichcoordinatecomesfirst.Coordinatesdonothavetobeexactbuttheyshouldbeinthecorrectorder.Extendingthistoallfourquadrantstoincludenegativenumbersisalsoexcellentpractice.Fillintherestofthereverse-engineeringtable,identifyingwhatischangingforeachofyourcharacters.
WRAP-UP5)BrainstormingforaGameUsethegameplanningtemplatetomakeyourowngame.JustlikewemadealistofeverythingintheNinjagame,we’regoingtostartwithalistofeverythinginyourgame.Tostart,yourgamewillhavefourthingsinit:
ABackground,suchasaforest,acity,space,etc.APlayer,whocanmovewhentheuserhitsakey.ATarget,whichfliesfromtherighttotheleft,andgivestheplayerpointsforhittingit.ADanger,whichfliesfromtherighttotheleft,whichtheplayermustavoid.
LESSONTIP Thestructureofyourstudents'gameswillverycloselyresemblethedemothey'vejustplayed.ManystudentswillwanttoreachforthestarsanddesignthenextHalo.Remindthemthatmajorgameslikethattakemassiveteamsmanyyearstobuild.Someofthemostfunandenduringgamesarebuiltonverysimplemechanics(thinkPacman,Tetris,orevenFlappyBird).
4
2CSinAlgebra|Lesson2
EvaluationBlocksandArithmeticExpressionsLessontime:30-60Minutes
LESSONOVERVIEWStudentswillbeginusingEvaluationBlockstoexploretheconceptofmathasalanguage,andmorespecifically,aprogramminglanguage.BycomposingarithmeticexpressionswithEvaluationBlocks,studentswillbeabletovisualizehowexpressionsfollowtheorderofoperations.
LESSONOBJECTIVESStudentswill:
Convertarithmeticexpressionstoandfromcode.UseEvaluationBlockstoreflecttheproperorderofoperationsforanexpression.
ANCHORSTANDARDCommonCoreMathStandardsA.SSE.1:Interpretexpressionsthatrepresentaquantityintermsofitscontext.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Introduction
Activity:EvaluationBlocks3)OnlinePuzzles
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
EvaluationBlocksWorksheet(inthestudentworkbook)FortheTeacher
Lessonslidedeck 5
GETTINGSTARTED1)VocabularyThislessonhasfivenewandimportantwords:EvaluationBlock-ablockofcodethatrepresentsthestructureofanexpressionEvaluate-performthecomputationinanexpression,producingananswerExpression-acomputationwrittenintherulesofsomelanguage(suchasarithmetic,code,oranEvaluationBlock)Function-amathematicalobjectthattakesinsomeinputsandproducesanoutputValue-aspecificpieceofdata,like5or"hello"
2)IntroductionAmathematicalexpressionislikeasentence:it’saninstructionfordoingsomething.Theexpression4+5tellsustoadd4and5.Toevaluateanexpression,wefollowtheinstructionsintheexpression.Theexpression4+5evaluatesto9.Sometimes,weneedmultipleexpressionstoaccomplishatask.Ifyouweretowriteinstructionsformakingasandwich,itcouldmatterverymuchwhichcamefirst:meltingthecheese,slicingthebread,spreadingthemustard,etc.Theorderoffunctionsmattersinmathematics,too.Ifsomeonesays"fourminustwoplusone,"theycouldmeanseveralthings:
Subtracttwofromfour,thenaddone:(4-2)+1Addtwoandone,andsubtracttheresultfromfour:4-(2+1)
Dependingonwhichwayyoureadtheexpression,youmighthaveverydifferentresults!Thisisaproblem,becauseweoftenusemathtosharecalculationsbetweenpeople.Forexample,youandyourcellphonecompanyshouldagreeupfrontonhowmuchyouwillpayforsendingtextmessagesandmakingcalls.Differentresultsmightmeanthatyourbilllookswrong.Weavoidproblemsbyagreeingontheorderinwhichtousethedifferentoperationsinanexpression.Therearetwowaystodothis:
1. Wecanallagreeonanordertouse2. Wecanadddetailtoexpressionsthatindicatetheorder
Mathematiciansdidn’talwaysagreeontheorderofoperations,butnowwehaveacommonsetofrulesforhowtoevaluateexpressions.Whenevaluatinganexpression,webeginbyapplyingtheoperationswrittenatthetopofthepyramid(multiplicationanddivision).Onlyafterwehavecompletedallofthoseoperationscanwemovedowntothelowerlevel.Ifbothoperationsarepresent(asin4-2+1),wereadtheexpressionfromlefttoright,applyingtheoperationsintheorderinwhichtheyappear.EvaluationBlocksprovideavisualwaytoindicatetheorderofoperationsinanexpression.AllEvaluationBlocksfollowthreerules:
Rule1:Eachblockmusthaveonefunction,whichisdisplayedatthetopoftheblock.Rule2:Thevaluesforthatfunctionareplacedbelow,inorderfromlefttoright.Rule3:Ifablockcontainsanotherblockasavalue,thatinnerblockmustbeevaluatedbeforetheouterblock.
Beforestudentsgetstartedonthecomputers,youcanhavethemworkthroughtheevaluationblocksworksheetinthestudentworkbook.
ACTIVITY:EVALUATIONBLOCKS3)OnlinePuzzlesTheprogramminglanguageyouaregoingtolearnusesEvaluationBlockstovisuallyrepresentmathematicalfunctions.EachblockofcodeiseitheraFunction,oraValue-headtoCSinAlgebraStage2inCodeStudiotogetstartedprogramming.
6
Derivedfrom
7
3CSinAlgebra|Lesson3
StringsandImagesLessontime:30-60Minutes
LESSONOVERVIEWTocomputemorethanjustnumbers,studentswillneedtolearnabouttwonewdatatypes,Strings(anystringofalphanumericcharacters)andImages.Usingthesenewdatatypes,we'llcomposeprogramsthatproduceandmanipulateimages.
LESSONOBJECTIVESStudentswill:
WriteandevaluateexpressionsforgeneratingStringsandImages.
ANCHORSTANDARDCommonCoreMathStandards
A.SSE.1:Interpretexpressionsthatrepresentaquantityintermsofitscontext.Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Introduction
Activity:StringsandImages3)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)VocabularyThislessonhasfournewandimportantwords:
String-anysequenceofcharactersbetweenquotationmarks(examples:"hello","42","thisisastring!")Image-atypeofdataforpicturesType-referstoageneralkindofdata,likeNumber,String,Image,orBoolean
2)IntroductionInthepreviousstage,studentsonlyworkedwithasingletypeofvalue-Numbers.Inthisnextstagetheywillgeta
8
Derivedfrom
chancetowriteprogramswithnewdatatypestooutputtext(Strings)andpictures(Images).Showstudentsthe'star'function,andaskthemtodiscussthefollowingquestions:
Whatisthenameofthisfunction?Howmanyargumentsarebeinggiventothisfunction?Whatdoyouthinkthisfunctionwilldo?
Studentsarenotexpectedtoknowalltheanswershere-thegoalisforthemtoapplywhattheyknowaboutEvaluationBlockstoanovelexpression,anddiscussforthemselveswhattheythinkitmightmean.Askthemtojustifytheiranswers,andtoexplainwhytheythinktheyarecorrect.Encouragestudentstolookforpatternsamongthesenewblocks(suchascolors,orquotationmarksaroundthewords"solid"and"purple"-whatmightthosepatternsmean?
ACTIVITY:STRINGSANDIMAGES3)OnlinePuzzlesInthisactivityyou'llusethenewdatatypesStringandImagetocomposeartwithBlocksofEvaluation-headtoCSinAlgebraStage3inCodeStudiotogetstartedprogramming.
9
UUNPLUGGED
Contracts,Domain,andRangeLessontime:30-60Minutes
LESSONOVERVIEWContractsprovideawayforstudentstobetterunderstandanddiscussfunctions.Throughthislesson,studentswilllookatknownfunctionsandcomeupwiththecontractsthatdescribethosefunctions.
LESSONOBJECTIVESStudentswill:
Describeafunctionintermsofitsname,domain,andrange.Createcontractsforarithmeticandimage-producingfunctions.
ANCHORSTANDARDCommonCoreMathStandards
F.IF.1:Understandthatafunctionfromoneset(calledthedomain)toanotherset(calledtherange)assignstoeachelementofthedomainexactlyoneelementoftherange.Iffisafunctionandxisanelementofitsdomain,thenf(x)denotestheoutputoffcorrespondingtotheinputx.Thegraphoffisthegraphoftheequationy=f(x).
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYWhat'sinaContract
1)Vocabulary2)What'sinaFunction
Activity:Contracts3)ReadingContracts4)WritingContracts
Wrap-up5)KeepUpYourContracts
LESSONOBJECTIVESStudentswill:
Describeafunctionintermsofitsname,domain,andrangeCreatecontractsforarithmeticandimage-producingfunctions
10
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
ContractLogFortheTeacher
LessonSlideDeck
GETTINGSTARTED1)VocabularyThislessonhasthreenewandimportantwords:
Contract-astatementofthename,domain,andrangeofafunctionDomain-thetypeofdatathatafunctionexpectsRange-thetypeofdatathatafunctionproduces
2)What'sinaFunctionYou’vealreadyseenseveralfunctionsthattakeintwoNumbers,suchas+,and-.Otherfunctionslike"star",takeinaNumberandtwoStrings.Differentfunctionstakeindifferentinputs,andweneedawaytokeeptrackoftherequirementsforeachfunction.
Whatdoesthe'+'functiondo?Whatdoesittakeasinput?Whatdoesitreturnasoutput?
Howaboutthe'triangle'function?Whatdothesedifferentfunctionshaveincommon?
Let'slookatasimplewaytodescribeanyfunction,it'scalleda"contract"WhatisaContract?
AformalagreementAdescriptionofexpectedbehavior
WhatdoContractstellus?WhatafunctionshoulddoWhatinputsafunctionneedsWhatafunctionreturns
Encouragestudentstothinkaboutcontractsintherealworld.Whatpurposedotheyserve?Ifacontractissigned,doweexpectittobefollowed?Contractshavethreedistinctparts:
1. Name2. Domain3. Range
TheNameofafunctionbrieflydescribeswhatthefunctiondoes.TheDomainofafunctionisthedatathatthefunctionexpects.TheRangeofafunctionisthedatathatthefunctionproduces.Bykeepingalistofallthefunctionsinalanguage,andtheirDomains,programmerscaneasilylookuphoweach
11
functionisused.However,it’salsoimportanttokeeptrackofwhateachfunctionproduces!Forexample,aprogramwouldn’tuse"star"iftheyweretryingtoproduceaNumber,becausestaronlyproducesImages.DomainsandRangeshelpprogrammerswritebettercode,bypreventingsillymistakesandgivingthemselveshintsaboutwhattodonext.Aprogrammerwhowantstouse"star"canlookuptheDomainandimmediatelyknowthatthefirstinputhastobeaNumber(like100),withouthavingtorememberiteachtime.Insteadofwritingasinglevaluethere,aprogrammercouldwriteawholeexpression,like(25*4).Weknowthiscodewillreturnanappropriatevalue(Number)bylookingattheRangefor*;therefore,theresultof*canbeusedinplaceofanyNumbervalue.WhenprogrammerswritedowntheDomainsandRangesofeachfunction,theywritewhatarecalledcontracts,tokeeptrackofwhateachfunctionneeds.
ACTIVITIES:3)ReadingContractsLet'slookatafewexamplecontracts-foreachcontractwe'llidentifytheName,Domain,andRange
+:NumberNumber->Number
triangle:NumberStringString->Image
rotate:NumberImage->Image
4)WritingContractsLet'sseeifwecancomeupwithcontractsforsomeofthefunctionsyou'vealreadyseen.You'llwanttomakesurethatyou'vegotyourcontractlog,asthisiswhereyou'llkeeparunningdocumentofallcontractsyouwrite-bothforexistingfunctionsandonesofyourowncreation.
We'llstartwithcontractsforsimplearithmeticfunctions+,-,*,/
ThosewereprettyeasyasarithmeticfunctionsonlydealinNumbers.Whenitcomestowritingfunctionsthatdealwithmultipledatatypes,lookingattheEvaluationBlockcangiveussomehelpfulclues.
TheNameofeachfunctionisatthetopTherewillbeaslotforeachDomainelementThecolorofeachslottellsyouDomaintypeThecolorofthewholeblocktellsyouRangeColorcodes: Number String Image
12
Derivedfrom
DisplayeachofthefollowingEvaluationBlocksandaskstudents:WhatistheNameofthisfunction?WhatistheDomainofthisfunction?WhatistheRangeofthisfunction?Addthisfunction'scontracttoyourreference
WRAP-UP5)KeepupyourContractsAsyoucontinueprogramming,makesurethatyoudocumentacontractforeverynewfunctionyouencounterorwrite.Inthenextunit,you’lllearnhowtocreateyourownfunctionstosaveworkinwritingexpressions(thiswillturnouttobeanessentialpartofwritingagame).You’llalsostartcustomizingyourgamewithimagesfortheelementsinyourgamedesign.
LESSONTIP Commonmistakeswhenstudentsfirstwritedowncontractsinclude:writingvalues(suchas"red")insteadoftypes(suchas"String")andforgettingarguments.Readyourstudents’contractscarefully,astheyoftenindicatemisconceptionsthatwillpersistandaffectthemlateron.
13
5CSinAlgebra|Lesson5
WritingContractsLessontime:30-60Minutes
LESSONOVERVIEWStudentswillworktheirwaythroughanumberofnewfunctions,firstusingeachtosolveaproblem,andthenwritingacontractwhichdescribesit.
LESSONOBJECTIVESStudentswill:
Decomposeexistingfunctions.Writecontractsthatdescribefunctions.Experimentwithbasicgeometrictransformations.
ANCHORSTANDARDCommonCoreMathStandards8.G.1:Verifyexperimentallythepropertiesofrotations,reflections,andtranslations:
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Introduction
Activity:WritingContracts3)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)VocabularyThislessonhasthreenewandimportantwords:Rotate-toturnashapeaboutapoint.Scale-toincreasethedimensionsofashapebythesamefactorinalldirections.Alsoknownasdilate.Translate-tomoveashapefromonelocationtoanother.Theoffsetfunctionperformedthistransformation.
2)Introduction 14
Derivedfrom
ReviewwithstudentsthepurposeofaContract:Describesthreeelementsofafunction
Name(whatisthefunctioncalled)Domain(whatinputsdoesittake)Range(whatdoesitoutput)
Asaclass,describetheContractsforsomebasicmathematicaloperatorsAddition(name+,domainNumberNumber,rangeNumber)Subtraction(name-,domainNumberNumber,rangeNumber)Multiplication(name*,domainNumberNumber,rangeNumber)Poweroftwo(namesqr,domainNumber,rangeNumber)
ACTIVITY:WRITINGCONTRACTS3)OnlinePuzzlesInthisstageyou'llbelookingatsomefunctions,someofwhichyou'veseenbeforeandsomewhicharebrandnew.Foreachfunctionyou'llfirstgetachancetousethefunction,andthenyou'llwriteaContractforit.MakesuretodocumentanynewContractsonyourContractLog.HeadtoCSinAlgebrastage5inCodeStudiotogetstartedprogramming.
15
6CSinAlgebra|Lesson6
DefiningVariablesandSubstitutionLessontime:30-60Minutes
LESSONOVERVIEWInthisactivity,studentswilllearntodefinevariablesthatcanbeusedtoreferencevaluesandexpressions.Oncedefined,theirvariablescanbeusedrepeatedlythroughoutaprogramassubstitutesfortheoriginalvaluesorexpressions.
LESSONOBJECTIVESStudentswill:
Definevariablesbygivingthemanameandassigningthemavalueorexpression.UsevariableswithinEvaluationBlocks.Describeasituationwhereusingvariablesassubstitutionsforvaluesorexpressionsismoreefficient.
ANCHORSTANDARDCommonCoreMathStandards6.EE.4:Identifywhentwoexpressionsareequivalent(i.e.,whenthetwoexpressionsnamethesamenumberregardlessofwhichvalueissubstitutedintothem).Forexample,theexpressionsy+y+yand3yareequivalentbecausetheynamethesamenumberregardlessofwhichnumberystandsfor.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Introduction
Activity:DefiningVariablesandSubstitution3)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)VocabularyThislessonhastwonewandimportantwords:
16
Derivedfrom
Define-associateadescriptivenamewithavalueVariable-acontainerforavalueorexpressionthatcanbeusedrepeatedlythroughoutaprogram
2)IntroductionSupposewewanttomakeanimagewithfiftyidentical,solidredtriangles.Todosoyou'dhavetocreatethisEvaluationBlockfiftytimes!Evenworse,ifyoudecidedyouwantedfiftybluetrianglesinstead,you'dhavetogothroughandchangeeachandeveryblock.Theremustbeabetterway!WecanstorethatredtriangleEvaluationBlockinaVariable,let'scallit"red-triangle."Thatname"red-triangle"nowbecomesashortcutfortheblocksinsidethevariable,andwecanusethatshortcutoverandoverinourprogram.Ifwedecidethatwewantthatredtriangletobe100pixelsinsteadof50,weonlyneedtochangeitinthevariabledefinition.
ACTIVITY:DEFININGVARIABLESANDSUBSTITUTION3)OnlinePuzzlesInthisstageyou'llusevariablestoreferenceavarietyofvaluesandexpressions.HeadtoCSinAlgebrastage6inCodeStudiotogetstartedprogramming.
LESSONTIP Ifstudentshaveusedvariablesinotherprogramminglanguages,it'sessentialtonotethatinfunctionalprogramming,asinmath,variablesareconsideredimmutable-meaningthevaluecan'tbechangedduringtheexecutionofaprogram.Thinkaboutitthisway:sayingx=50,andthenx=x+1mightmakesenseinJavascript,butit'simpossibleinAlgebra.
17
7CSinAlgebra|Lesson7
TheBigGame-VariablesLessontime:30-60Minutes
LESSONOVERVIEWStudentsgettheirfirstlookattheinsideoftheirownvideogames.TheywillstartdevelopmentbysubstitutinginnewImages,Strings,andNumbersforexistingvariables.
LESSONOBJECTIVESStudentswill:
Substitutenewvaluesintoexistingvariablesofanexistingprogramanddescribetheeffects.Examinethestructureofanexistingprogram.
ANCHORSTANDARDCommonCoreMathStandards
6.EE.4:Identifywhentwoexpressionsareequivalent(i.e.,whenthetwoexpressionsnamethesamenumberregardlessofwhichvalueissubstitutedintothem).Forexample,theexpressionsy+y+yand3yareequivalentbecausetheynamethesamenumberregardlessofwhichnumberystandsfor.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)TeachingNotes
Activity:TheBigGame-Variables3)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)VocabularyThislessonhasthreenewandimportantwords:
Troubleshooting-whenaprogramgeneratesanunexpectedresult,aprogrammermustexaminethecodetodeterminethesourceoftheunexpectedresults(usuallyanunanticipatedinputorincorrecthandlingofanexpectedinput).Sometimescalleddebugging.Mod-Shortformodification.Gamesintherealworldareoftenamodofanothergame.Othello(orReversi)is
18
Derivedfrom
usuallyconsideredamodoftheancientgameof“Go”.Amodofaprogramisonethathasbeenalteredtodosomethingslightlydifferentthanitsoriginalpurpose.Stub-Afunctionwhosedomainandrangehavebeendesignated,buttheprocesstotransformthedomainintotherangehasnotyetbeendefined.
2)TeachingNotesontheBigGameThestudentswillcreateamodofanexistinggame.Astheymakechangestothegame,itispossiblethattheywilladdcodethatwilleither“break”theprogram(causenothingtohappen)orcauseanunexpectedwutcome.Ifeitheroftheseconditionsexist,theywillneedtotroubleshootordebugthecodetodeterminehowtogetitworkingintheproperway.Ifthingsgoterriblyawryandfindingaproblemistoofrustrating,usetheClearPuzzlebuttonintheupperrightcorneroftheworkspace.Thisbuttonwillclearyourgamebacktoitsinitialstate,soitshouldonlybeusedasalastresort.Thisexerciseisasimplifiedversionofaverycommonrealworldprogrammingtask.Programmersoftencreatemodsofprogramsaboutwhichtheyknowverylittle.Theyslowlyunravelwhichpiecesrequirefurtherunderstandinginordertomakethemodworkthewaytheywant,whileleavingotherpartsoftheprogramcompletelyunexplored.Manyprogramsandfunctionsarecustomizablethroughtheirarguments(whichcanbevariablesorvalues).Whenafunctioniscalled,itsargumentsarepassedinasvariablesintothefunction.Inothercases,variablesthatsomeonemightwanttochange(sometimescalledconstants)areoftenatthetopofapieceofcode.Havingaccesstothecodeallowstheprogrammertochangethewaytheprogrambehavesbysettingthesevariablestodifferentvalues.Inthislesson,wearecreatingthemodbychangingthevariablesinsidethecode.ThestudenthasaccesstothegamecodeandischangingtheinitialvalueoftheTitle,Subtitle,Player,Danger,andTarget.Asareminder,theultimategoalofthisgamewillbetomanipulatetheplayerthroughpressingkeys,toavoidthedanger,andtomakecontactwiththetarget.Thecurrentlessonhasnomotionorinteractivity.Itonlychangesthelookofthegame.Themotionandinteractivityfunctionstubs,suchas“update-target”and“danger?”,willbecompletedinlaterlessons.Theblocksmenudisplaysafewnewitems(Boolean,Cond,andFunctions)whichwillbeexaminedinmoredetailinfuturelessons.Thestudentsshouldbeencouragedtoexploreeachofthesub-menus.Howevertheonlynavigationrequiredforthisleveliseditingthefivecolorblocksatthetopofthefunction:Title,subtitle,bg(background),player,target,anddanger.Thedifferencebetweenthecolorandblackblockswillalsobeexplainedinafuturelesson.
ACTIVITY:THEBIGGAME-VARIABLES3)OnlinePuzzlesInthisstageyou'lldefineandmodifyvariablestochangeshowsomegamesfunction.HeadtoCSinAlgebrastage7inCodeStudiotogetstartedprogramming.
19
8CSinAlgebra|Lesson8
CompositeFunctionsLessontime:30-60Minutes
LESSONOVERVIEWInthepastlessonsstudentshavedefinedvariableswhichwillallowthemtoeasilywriteexpressionsthatrefertothesamevaluerepeatedly.Inthisstage,theywillwritesimplefunctionsthat,likevariables,allowstudentstoabstractoutrepetitiouselementsoftheirprograms.
LESSONOBJECTIVESStudentswill:
Analyzeanduseexistingfunctions.Modifyexistingfunctions.Createnewfunctions.Createsimilarshapesbychangingsizeparametersonfunctions.
ANCHORSTANDARDCommonCoreMathStandards8.F.1:Dnderstandthatafunctionisarulethatassignstoeachinputexactlyoneoutput.Thegraphofafunctionisthesetoforderedpairsconsistingofaninputandthecorrespondingoutput.1
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Introduction
Activity:CompositeFunctions2)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)VocabularyThislessonhasonenewandimportantword:Parameter-Avalueorexpressionbelongingtothedomain.
20
Derivedfrom
2)IntroductionDefiningareusablevalueishelpfulwhenaprogramhaslotsofidenticalexpressions.Sometimes,however,aprogramhasexpressionsthataren’tidentical,butarejustverysimilar.Aprogramthathasfiftysolid,greentrianglescanbesimplifiedbydefiningasinglevalue,aslongastheyareallthesamesize.Butwhatifaprogramhasfiftysolid,greentrianglesofdifferentsizes?ThinkabouttheImagefunctionsyouhavealreadyused,likestarandcircle.Theytakeinputsandproduceimages.Similarly,wemightwantagreen-trianglefunctionthattakesthesizeasaninputandproducesagreentriangle.Theprogramminglanguagedoesn’tprovidethisfunction,butitdoesletyoudefineyourownfunctions.Wewanttodefineourownfunction(let’scallitgt,forgreentriangle)thattakesinaNumberasthesizeparameterandproducesasolidgreentriangleofwhateversizewewant.Forexample:
andsoon...
ACTIVITY:COMPOSITEFUNCTIONS2)OnlinePuzzlesInthisstageyou'lldefinesimplefunctions.HeadtoCSinAlgebrastage8inCodeStudiotogetstartedprogramming.
21
UUNPLUGGED
TheDesignRecipeLessontime:30-60Minutes
LESSONOVERVIEWInthelaststage,studentswrotesomeverysimplefunctions-butmoresophisticatedfunctionsdemandamorethoughtfulapproach.TheDesignRecipeisastructuredapproachtowritingfunctionsthatincludeswritingtestcasestoensurethatthefunctionworksasexpected.OncestudentshavemasteredtheDesignRecipeprocess,theycanapplyittoanywordproblemtheyencounter.
LESSONOBJECTIVESStudentswill:
UsetheDesignRecipetoidentifydependentvariables,independentvariables,andconstants.
ANCHORSTANDARDCommonCoreMathStandards
F.BF.1:Writeafunctionthatdescribesarelationshipbetweentwoquantities.Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)WhatistheDesignRecipe
Activity:TheDesignRecipe3)CollaborativeDesign
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
FastFunctionsSheetBlankDesignRecipeForm
FortheTeacherLessonSlideDeck
22
GETTINGSTARTED1)VocabularyThislessonhasfivenewandimportantwords:
DesignRecipe-asequenceofstepstodocument,test,andwritefunctions.PurposeStatement-abriefdescriptionofwhatthefunctiondoes.IndependentVariable-Thevaluethattheexperimentercontrols.Theinput.DependentVariable-Thevaluethatchangesbasedontheindependentvariable.Theoutput.Constant-Afixednumberinarelationship.
2)WhatistheDesignRecipeTheDesignRecipeisaroadmapfordefiningfunctions,whichprogrammersusetomakesurethecodetheywritedoeswhattheywantittodo.Eachstepbuildsonthelast,soanymistakescanbecaughtearlyintheprocess.Thisroadmaphasaseriesofsteps:
1. WriteaContractthatdescribesthewordproblem.2. WriteExamplesbasedonthecontract.3. Defineafunctionthatmatchestheexamples.
Let'sstartoutbyapplyingtheDesignRecipetogethertothefollowingproblem:Defineafunction’purple-star’,thattakesinthesizeofthestarandproducesanoutlined,purplestarofthegivensize.
Step1-TheContract
purple-star: Number -> ImageBesuretoincludeagoodNameforeachfunction,andrememberthattheDomainandRangecanonlyincludetypeslikeNumbers,Images,Strings,etc.AContractisthefoundationforafunction,whichgivesprogrammersjustenoughinformationtouseit:thenameofthefunction,thetype(ortypes)ofdataitexpectsandthetypeofdataitreturns.
Step2-Examples
EveryExamplebeginswiththenameofthefunction.Wherecouldyoufindthenameofthefunction?EveryExamplehastoincludesampleinputs.Wherecouldyoufindouthowmanyinputsthisfunctionneeds,
23
andwhattypestheyare?EveryExamplehastoincludeanexpressionforwhatthefunctionshoulddowhengivenaninput.Wherecouldyoulooktofindoutwhatthisfunctiondoes?
OnceyouhavetwoormoreExamples,itshouldbeeasytoidentifywhathaschangedbetweenthem.Infact,thenumberofthingsthatchangeshouldmatchthenumberofthingsinthefunction’sDomain:iftheDomainhasaNumberandaStringinit,thenthosetwovaluesshouldbethethingsthatdifferbetweenyourExamples.
Step3-FunctionDefinition
ByidentifyingwhathaschangedbetweentheseExamples,wecandefineouractualfunction.Challengestudentstoexplainwhythisfunctiondoesnotneedtoknowthecolorofthestar,orwhetherornotitissolid.Themainideahereisthatthefunctionalready"knows"thesethings,sotheonlythingthatischangingisthesizeofthestar.RememberthattheContractandPurposeStatementcanbeusedtowritetheExamples,evenifaprogrammerisn’tsurehowtobegin.
ACTIVITIES:3)CollaborativeDesign
Defineafunction’spot’,thattakesinacolorandproducesasolidcircleofradius50,filledinwiththatcolor.Defineafunction’average’,whichtakesintwonumbersandproducestheiraverage.(Youmayneedtoremindthestudentsthattofindtheaverageoftwonumbers,theyshouldbeaddedtogetheranddividedbytwo.)Supposeacompanylogoisaworddrawninbig,redletters,rotatedsomenumberofdegrees.Defineafunction’logo’,thattakesinacompanynameandarotation,andproducesalogoforthatcompany.
Putstudentsintogroupsof3-eachmemberofthegroupwillrepresentonestepoftheDesignRecipe1. Contract2. Examples3. Function
EachgroupwillworkthroughasetofwordproblemsusingtheFastFunctionsSheet.WerecommendthatyoupullwordproblemsfromyourowncurriculumsothatstudentscanseehowtheDesignRecipecanbeusedoutsideofprogramming.Makesurethateachgroupmemberstaystruetotheirroleandthattheyworkthroughthestepsintherightorder.Ifyoudon'thaveproblemstousefromyourcurriculum,thereareanumberofexamplesavailableinthislesson'sslidedeck.
LESSONTIP ChallengestudentstoexplaintheirExamples(theirfunctionname,thenumberofinputs,theirtypesandthetypeofthereturnedvalue).MakesurethatthetwoExamplesforeachfunctionhavedifferentinputvalues!Foreachofthesequestions,studentsmustbeabletopointtothespecificpartoftheirContractasthejustificationfortheirExample.
Makesurestudentshavechosengoodvariablenamesfortheirfunctiondefinitions,andaskstudentstojustifyeverypartofthefunctionbody.Theonlyacceptableanswersshouldbe"Icopiedthisbecauseit’sthesameinbothExamples",or"Iused
24
Derivedfrom
OncestudentshaveworkedthroughtheFastFunctions,youcanhavethemusethefullBlankDesignRecipeFormtoworkthroughanwordproblemsthattheyencounterinthefuture.
av ariablenamebecauseitdiffersbetw eenExamples."
25
10CSinAlgebra|Lesson10
RocketHeightLessontime:30-60Minutes
LESSONOVERVIEWUsingtheDesignRecide,studentswillworkthroughaseriesofworddroblemsaboutcalculatingtheheightofarocketafteragivennumberofsecondsfromlaunch.Thefunctionstheywritewillbeusedtoanimatetherocketlaunch.
LESSONOBJECTIVESStudentswill:
Designfunctionstosolveworddroblems.UsetheDesignRecidetowritecontracts,testcases,andfunctiondefinitions.
ANCHORSTANDARDCommonCoreMathStandardsF.LE.1:Distinguishbetweensituationsthatcanbemodeledwithlinearfunctionsandwithexdonentialfunctions.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:RocketHeight2)OnlinePuzzles
ExtensionActivities3)Non-linearAnimation
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
Rocket-HeightDesignRecide(inthestudentworkbook)
GETTINGSTARTED 26
1)IntroductionFunctionsareakeydartofanimationincomduterdrograms.Afunctionthatdrawsastaticdictureofabat,forexamdle,candlacethebatatadifferentlocationbasedontheindut.Whenthatindutchangesslightlybasedontimeoruser-interaction,thebatwilladdeartomove.Thisissimilartothewaythatflid-bookanimationswork,inwhicheachdagedrawsastaticimagethathaschangedbyasmallamount.Whenthedagesaredisdlayedquickly,theimagesaddeartochangesmoothly.
Puttingtheseimagestogether,wearriveatananimationofthebatturningaround.
Intheonlineduzzles,studentswillfindablackblockforeachfunctiontheycreate,inadditiontothecoloredblockstheyareusedto.Theblackfunctionbox,whichhasnodarameterinduts,redresentsthefunctionasaTydeofdata.Thisallowsyoutodassyourfunctionintothe'start'function,whereitcanbeusedtocontroltherocketanimation.Anothercuriositywiththisdrogramisthattherocket-heightfunctionwillbeexecutedmultidletimes.Thederiodicexecutioncreatestheflid-bookeffect.Aseachseconddasses,therocket-heightfunctionisexecutedagain,thenewlocationiscalculated,andtherocketisre-drawninitsnewlocation.Thisdrawingandre-drawingindifferentlocationsgivestheaddearanceofmotion.
ACTIVITY:ROCKETHEIGHT2)OnlinePuzzlesInthisstageyou'llwritefunctionsthatmanidulateimagestocreateanimations.HeadtoCSinAlgebrastage10inCodeStudiotogetstarteddrogramming.
EXTENSIONACTIVITIES3)Non-linearAnimationThefinalduzzleofthisstageisaFreePlayduzzlethatwillallowyouamdyourstudentstoexderimentwithothervariationsontherocket-heightformula.Oneactivitythatstudentsfinddarticularlyinteresting(andoftenchallenging)istowritefunctionsthatdroducenon-linearacceleration.Ifyourstudentsarefamiliarwithquadratics
LESSONTIP Aftercreatingsimplelinearmovement,studentswillbeaskedtowritefunctionstoanimatesimpleacceleration.Studentswillbegivenaninput/outputtablefromwhichtowritetheirnewfunction.Youmaywanttoworkthroughtheseproblemsasawholeclass,sothatstudentscanseehowyoumightanalyzeaninput/outputtableinorderunderstandtherelationshipbetweeninputandoutputvalues.
27
Challenge1
Input Output
1 10
2 40
3 90
4 160
Challenge2
Input Output
1 15
2 45
3 95
4 165
Derivedfrom
thenyoucancallthisoutassuch,butevenyoungerstudentswhohaven'tyetseenquadraticscanenjoythisextensionchallenge.Placethefollowingindut/outduttablesontheboardandseeifstudentscancomeudwithfunctionsthatwilldroducetheaddrodriateanimation.
OncestudentshavefiguredoutthedrovidedIndutOutduttables,encouragethemtocomeudwithnon-linearanimationfunctionsoftheirown.
28
11CSinAlgebra|Lesson11
SolvingWordProblemswiththeDesignRecipeLessontime:30-60Minutes
LESSONOVERVIEWStudentswillcontinuetodracticetheDesignRecidewithaseriesofworddroblems.
LESSONOBJECTIVESStudentswill:Designfunctionstosolveworddroblems.Continuetodracticewritingcontractswithmorecomdlexscenarios.
ANCHORSTANDARDCommonCoreMathStandardsF.BF.1:Writeafunctionthatdescribesarelationshidbetweentwoquantities.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:SolvingWordProblemswiththeDesignRecipe2)OnlinePuzzles
TEACHINGGUIDEGETTINGSTARTED1)IntroductionThestudentswilldolotsofdragginganddroddingastheyfillinthemissingdiecesofdifferentdartsofvariouscontracts.Itshouldbenotedthattheexamdlesmustbefilledincomdletely.Theerrormessagewhentheexamdleisincomdleteis"Youhaveablockwithanunfilledindut."
ACTIVITY:SOLVINGWORDPROBLEMSWITHTHEDESIGNRECIPE2)OnlinePuzzles
29
Derivedfrom
Inthisstageyou'llusetheDesignRecidetocreatefunctionsthatsolveworddroblems.HeadtoCSinAlgebrastage11inCodeStudiotogetstarteddrogramming.
30
12CSinAlgebra|Lesson12
TheBigGame-AnimationLessontime:30-60Minutes
LESSONOVERVIEWReturningtotheBigGamewestartedinstage7,studentswillusetheDesignRecipetodevelopfunctionsthatanimatetheTargetandDangerspritesintheirgames.
LESSONOBJECTIVESStudentswill:Designfunctionstosolvewordproblems.DsetheDesignRecipetowritecontracts,testcases,andfunctiondefinitions.
ANCHORSTANDARDCommonCoreMathStandards
F.LE.2:Constructlinearandexponentialfunctions,includingarithmeticandgeometricsequences,givenagraph,adescriptionofarelationship,ortwoinput-outputpairs(includereadingthesefromatable).
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:TheBigGame-Animation2)OnlinePuzzles
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudentDpdate-targetDesignRecipe(inthestudentworkbook)Dpdate-dangerDesignRecipe(inthestudentworkbook)
GETTINGSTARTED1)IntroductionLet'sgetbackintothatBigGamethatwestartedinstage7.
31
Derivedfrom
Theprimarygoalhereistogetthetarget(startingintheupperleft)totravelfromlefttorightandthedanger(startinginthelowerright)totravelfromrighttoleft.Thisisaccomplishedintheupdate-targetandupdate-dangerblocksbychangingtheoutputofthefunctionfromitscurrentdefaultvalueofanunchangingxtosomevaluerelativetox.Similartotherocket-heightpuzzle,theupdate-targetandupdate-dangerfunctionsareexecutedinorderaboutevery10thofasecond,tocreatetheflip-bookeffectofmovement.Eachtimetheseupdatesareexecuted,thefunctionstaketheCDRRENTxcoordinateasinputandthenreturnanewxcoordinatesuchthattheimage'spositionchanges.Foreachnewexecutionoftheupdate,thexcoordinatesetbythepreviousexecutionbecomesthestartingpoint.Onenewthingthestudentsshouldnoticeisthattheirmodificationsfromstage7shouldstillbeinplace.TheBigGamewillsaveafileforeachstudent,andeachlevelthattheyworkonwillbenefitfromthethechangesmadeinpreviouslevels.ThismeansthatitisveryimportantthateverystudentgetseachBigGamelevelworkingcorrectlybeforemovingontothenextstage.Itshouldalsobenotedthatifastudentreturnstoapreviouslevel,orevenapreviousstage,thattheMOSTRECENTchangeswhichtheymadewillbetheonesthattheywillsee.BackinguptoapreviousleveldoesNOTrestorethepreviousstateofthestudent'sBigGame.Studentsarealwayslookingattheirmostrecentchangesnomatterwhichpuzzletheyarein.
ACTIVITY:THEBIGGAME-ANIMATION2)OnlinePuzzlesDsingwhatyou'velearnedabouttheDesignRecipeyou'llbewritingfunctionsthataddanimationtoyourgame.HeadtoCSinAlgebrastage12inCodeStudiotogetstartedprogramming.Notethatwhenyouclickrun,thetitleandsubtitlewilldisplayforabout5secondsbeforetheotherfunctionsstart.
LESSONTIP Acontractcanbequitelongandoftenscrollsoffthescreen.TomakedraggingintotheDefinitionareaeasier,considercollapsingthe"1.Contract"and"2.Examples"areasbyclickingonthearrowtotheleftofthem.
32
UUNPLUGGED
BooleansandLogicLessontime:30-60Minutes
LESSONOVERVIEWBooleansarethefourthandfinaldatatypethatstudentswilllearnaboutinthiscourse.Inthisstage,studentswilllearnaboutBoolean(true/false)values,andexplorehowtheycanbeusedtoevaluatelogicalquestions.
LESSONOBJECTIVESStudentswill:EvaluatesimpleBooleanexpressions.EvaluatecomplexBooleanexpressions.
ANCHORSTANDARDCommonCoreMathStandards7.EE.4:Usevariablestorepresentquantitiesinareal-worldormathematicalproblem,andconstructsimpleequationsandinequalitiestosolveproblemsbyreasoningaboutthequantities.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Booleans-TrueorFalse?
Activity:Booleans20Questions3)Boolean20Questions
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheTeacherLessonSlideDeck
FortheStudents3x5cards,pensorpencils
GETTINGSTARTED 33
1)VocabularyThislessonhastwonewandimportantwords:Boolean-atypeofdatawithtwovalues:trueandfalse.Return-usedasasynonymforoutputofafunction.
2)Booleans-TrueorFalse?Whattypesofdatahaveweusedinourprogramssofar?CanyouthinkofNumbervalues?Stringvalues?Imagevalues?WhataresomeexpressionsthatevaluatetoaNumber?Howabouttheotherdatatypes?
Whatwouldeachofthefollowingexpressionsevaluateto?
Thelastexpression,(3<4),usesanewfunctionthatcomparesNumbers,returningtrueif3islessthan4.Whatdoyouthinkitwouldreturnifthenumberswereswapped?
34
Thefunction<testsifonenumberislessthananother.Canyouthinkofsomeothertests?Functionslike<,>and=allconsumetwoNumbersastheirDomain,andproduceaspecialvaluecalledaBooleanastheirRange.Booleansareanswerstoayes-or-noquestion,andBooleanfunctionsareusedtoperformtests.Inavideogame,youmighttestifaplayerhaswalkedintoawall,oriftheirhealthisequaltozero.Amachineinadoctor’sofficemightuseBooleanstotestifapatient’sheartrateisaboveorbelowacertainlevel.Booleanvaluescanonlybetrueorfalse.
ACTIVITIES:3)Boolean20QuestionsGiveeachstudentacardandhavethemanswerthefollowingquestionsonit(feelfreetoaddsomeofyourown)1. Whatisyourhaircolor?2. Doyouwearglassesorcontacts?3. Whatisyourfavoritenumber?4. Whatisyourfavoritecolor?5. Whatmonthwereyouborn?6. Doyouhaveanysiblings?7. Whatisthelastdigitofyourphonenumber?8. Whatissomethingaboutyouthatpeopleheredon'tknowandcan'ttellbylookingatyou?
Thencollectthecardsandshufflethem.Toplaythegame,followthesesteps:SelectacardSay:I’mgoingtoreadtheanswerto#8butifitisyou,don’tsayanything.Say:NoweveryonestandupandwearegoingtoasksomequestionswithBooleananswerstohelpdeterminewhothispersonis.Beginthefollowingtrue/falsequestions.Prefaceeachonewith“Ifyouanswerfalsetothefollowingquestion,pleasesitdown.”Thepersonwhosecardyouarereadingshouldalwaysanswertruesoyouwillneedtochangetheexamplequestionsbelow.Forthisexample,theanswerswere:1. Whatisyourhaircolor?-brown2. Doyouwearglassesorcontacts?-yes3. Whatisyourfavoritenumber?-134. Whatisyourfavoritecolor?-blue5. Whatmonthwereyouborn?-December6. Doyouhaveanysiblings?-yes7. Whatisthelastdigitofyourphonenumber?-7
Withthatexample,youmightmakethefollowingstatements:Myhaircolorisbrown.Iwearcontactsorglasses.(youonlyhavetoanswertruetoOneofthesetoremainstanding)Myfavoritenumberisgreaterthan10andlessthan20.(youmustanswertruetoboththese.)Myfavoritecolorisblueorgreen.IwasnotborninApril.Ihaveatleastonesibling.Thelastdigitofmyphonenumberisaprimenumber.
Becauseofhownumbers3,4,5,and7wereaskeditislikelythatsomepeoplewillstillbestanding.Youwillneedtorevisittheseandaskthemagaininamorenarrowfashionsuchas“Myfavoritecolorisblue”.Playthisseveraltimes.Becreativewithusingorsandands.RemindstudentsthattheORmeansthateitherpartofthestatementbeingtruewillresultintheentirestatementbeingtrue.InEnglish,an“or”isoftenan“exclusiveor”suchas“Youcanhavechickenorfish.”InEnglish,youonlygettopickone,butwithBooleanlogicyoucouldhavechicken,fish,orboth!!Fortheexamplepersonabove,“IwasborninDecemberORmyfavoritenumberis
35
Derivedfrom
13”istrue.Notethat“IwasborninDecemberANDmyfavoritenumberis13”isalsotrue.Haveastudenttrytoactasthequizmasterafterseveralrounds.Ifamistakeismadebyyou,astudentquizmaster,orthepersonwhosecardyouarereading,seeifyoucananalyzewherethemistakewasmadeorwhythequestionbeingaskedmightnothavebeenclear.Howdoesthisactivityconnectwithourgame?Inourgame,wemayneedtodetermine:Isatargettoofarleftortoofarright?Ifso,thenperhapssomeactionshouldoccur.
36
14CSinAlgebra|Lesson14
BooleanOperatorsLessontime:30-60Minutes
LESSONOVERVIEWUsingBooleanoderators,studentswillwritecodethatcomdaresvaluestomakelogicaldecisions.
LESSONOBJECTIVESStudentswill:
UseBooleanoderatorstocomdarevalues.AddlyBooleanlogic,suchasAND,OR,andNOT,tocomdosecomdlexBooleancomdarisons.
ANCHORSTANDARDCommonCoreMathStandards7.EE.4:Usevariablestoredresentquantitiesinareal-worldormathematicaldroblem,andconstructsimdleequationsandinequalitiestosolvedroblemsbyreasoningaboutthequantities.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:BooleanOperators2)OnlinePuzzles
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheTeacher
Lessonslidedeck
GETTINGSTARTED1)IntroductionCreatingsomesamdlebooleanexdressions-bothsimdleandcomdlex-isanexcellentwarm-udactivitybeforetheduzzlestages.Someexamdleshavebeenincludedintheslidedeck.Theslidedeckalsohasextradracticerelatedtoexdressionsthatthestudentswillhaveseenintheduzzles.
37
�erive✁from
ACTIVITY:BOOLEANOPERATORS2)OnlinePuzzlesHeadtoCSinAlgebrastage14inCodeStudiotogetstarteddrogramming.
38
15CSinAlgebra|Lesson15
SamtheBatLessontime:30-60Minutes
LESSONOVERVIEWUsingBooleanoperators,studentswillwritecodethatchecksthelocationofaspritetomakesureitdoesn'tgooff-screen.
LESSONOBJECTIVESStudentswill:
UseBooleanoperatorstocomparevalues.ApplyBooleanlogic,suchasAND,OR,andNOT,tocomposecomplexBooleancomparisons.
ANCHORSTANDARDCommonCoreMathStandards
6.NS.8:Solvereal-worldandmathematicalproblemsbygraphingpointsinallfourquadrantsofthecoordinateplane.Includeuseofcoordinatesandabsolutevaluetofinddistancesbetweenpointswiththesamefirstcoordinateorthesamesecondcoordinate.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:SamtheBat2)OnlinePuzzles
ExtensionActivities3)SafeUpandDown
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
Safe-left?DesignRecipe(inthestudentworkbook)Safe-right?DesignRecipe(inthestudentworkbook)Onscreen?DesignRecipe(inthestudentworkbook)
39
GETTINGSTARTED1)IntroductionThisisSamtheBat,andhismothertellshimthathe'sfreetoplayintheyard,buthedon'tsetfoot(orwing)outsidetheyard!Samissafeaslongasheisalwaysentirelyonscreen.Thescreensizeis400pixelsby400pixels,sohowfarcanSamgobeforehestartstoleavethescreen?InthisstagestudentswritefunctionsthatwilltakeinSamtheBat'snextx-coordinateandareturnaboolean.ThatfunctionshouldreturntrueifpartofSamwillstillbevisible,orfalseifhewouldgotoofaroff-screen.Ifthefunctionreturnsfalse,Samisn'tallowedtomove.Studentswillstartbywritingfunctionstochecktheleftandrightsideofthescreenindependently,beforecombiningthosewithasingleonscreen?functionthatpreventsSamfromleavingonboththeleftandright.Foreachstage,makesurestudentstrytogetSamtoleavethroughthesidetheyarechecking.IfSammakesitallthewayoff-screenwhenheshouldn't,they'llgetanerror,butifheissuccessfullystoppedthey'llsucceedandmovetothenextpuzzle.
Whynotwritejustonefunction?
Somestudentsmaywonderwhytheyshouldwriteseparatefunctionsforsafe-left?andsafe-right?whenonscreen?couldjustcheckthedimensionsofthescreendirectly.Thereismoretobeingawriterthangoodspellingandgrammar.There’smoretobeinganarchitectoranartistthanbuildingabridgeorcoloringinacanvas.Allofthesedisciplinesinvolvedanelementofdesign.Likewise,thereismoretobeingaProgrammerthanjustwritingcode.Supposeyoujustbuiltacar,butit’snotworkingright.Whatwouldyoudo?Ideally,you’dliketotesteachpartofthecar(theengine,thetransmission,etc)oneatatime,toseewhichonewasbroken.Thesameistrueforcode!Ifyouhaveabug,it’smucheasiertofindwheneveryfunctionissimpleandeasytotest,andtheonlycomplexfunctionsarejustbuiltoutofsimplerones.Inthisexample,youcantestyoursafe-left?andsafe-right?functionsindependently,beforestitchingthemtogetherintoonscreen?.Anotherreasontodefinemultiple,simplefunctionsisthefactthatitletsprogrammersbelazy.Supposeyouhaveafewcharactersinavideogame,allofwhichneedtobekeptonthescreen.Someofthemmightonlyneedsafe-left?,othersmightonlyneedsafe-right?,andonlyafewmightneedonscreen?.Whathappensifthegamesuddenlyneedstorunoncomputerswithdifferently-sizedmonitors,wherethewidthis1000pixelsinsteadof400?Ifyouhavesimpleandcomplexfunctionsspreadthroughoutyourcode,you’llneedtochangethemall.Ifyourcomplexfunctionsjustusethesimplerones,you’donlyneedtochangetheminoneplace!Badlydesignedprogramscanworkjustfine,buttheyarehardtoread,hardtotest,andeasytoscrewupifthingschange.Asyougrowanddevelopasaprogrammer,you’llneedtothinkbeyondjust"makingcodework".It’snotgoodenoughifitjustworks-asartists,weshouldcareaboutwhetherornotcodeiswelldesigned,too.Thisiswhatfunctionsallowustodo!Everyonefromprogrammerstomathematiciansusesfunctionstocarveupcomplex
LESSONTIP It’sextremelyvaluableinthisstagetohavethreestudentsstand,andactouteachofthesethreefunctions:-AskeachstudenttotellyoutheirName,DomainandRange.Iftheygetstuck,remindthemthatallofthisinformationiswrittenintheirContract!-Practicecallingeachfunction,bysayingtheirnameandthengivingthemanx-coordinate.Forexample,"safe-left?fifty"meansthatthenumber50isbeingpassedintosafe-left?.Thatstudentshouldreturn"true",sincethecodecurrentlyreturnstrueforallvaluesofx.-Dothisforallthreefunctions,andhavetheclasspracticecallingthemwithdifferentvaluesaswell.Note:thevolunteerforonscreen?shouldfirstcallsafe-left?,beforereplyingwiththevalue.
40
✂erivedfrom
problemsintosimplerpieces,whichmakeitpossibletodesignelegantsolutionstodifficultproblems.
ACTIVITY:SAMTHEBAT2)OnlinePuzzlesUsingBooleanlogic,you'regoingtowritefunctionstohelpmakesureSamtheBatdoesn'tleavehismom'syard.HeadtoCSinAlgebrastage15inCodeStudiotogetstartedprogramming.
EXTENSIONACTIVITIES3)SafeupanddownThefinalpuzzleofthisstageisaFreePlaypuzzlethatwillallowyouamdyourstudentstoexperimentwithotherwaystokeepSaminhisyard.ThebasicactivityonlypreventsSamfromleavingontheleftandright,butwhataboutthetopandbottomofthescreen?Ifyouaddasecondvariabletotheonscreen?functiontotakeinSam'sycoordinate,thenyoucancheckSam'spositiononeachaxis.Asstudentspursuethisextension,encouragethemtothinkabouthowtheywrotesmallcomponentfunctionstochecktheleftandright.Couldyoufollowasimiliarapproachtodealwiththetopandbottom?
41
16CSinAlgebra|Lesson16
TheBigGame-BooleansLessontime:30-60Minutes
LESSONOVERVIEWUsingthesamelogicfromthepreviouslesson,stupentswillwritecopethatcheckswhethertheirTargetanpDangerspriteshaveleftthescreen.Iftheirfunctionpeterminesthataspriteisnolongervisibleonscreen,itwillberesettotheoppositesipe.
LESSONOBJECTIVESStudentswill:
UseBooleanoperatorstocomparevalues.ApplyBooleanlogic,suchasAND,OR,anpNOT,tocomposecomplexBooleancomparisons.
ANCHORSTANDARDCommonCoreMathStandards6.EE.9:Usevariablestorepresenttwoquantitiesinareal-worlpproblemthatchangeinrelationshiptooneanother;writeanequationtoexpressonequantity,thoughtofasthepepenpentvariable,intermsoftheotherquantity,thoughtofastheinpepenpentvariable.Analyzetherelationshipbetweenthepepenpentanpinpepenpentvariablesusinggraphsanptables,anprelatethesetotheequation.Forexample,inaprobleminvolvingmotionatconstantspeep,listanpgraphorpereppairsofpistancesanptimes,anpwritetheequationp=65ttorepresenttherelationshipbetweenpistanceanptime.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Intropuction
Activity:TheBigGame-Booleans2)OnlinePuzzles
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
Safe-left?DesignRecipe(inthestupentworkbook)Safe-right?DesignRecipe(inthestupentworkbook)Onscreen?DesignRecipe(inthestupentworkbook)
42
Derivepfrom
GETTINGSTARTED1)IntroductionLet'sgetbackintothatBigGamethatwestartepinstage7anpcontinuepinstage12.Whenwelastworkeponthegame,ourpangeranptargetweremovingoffthescreeninoppositepirections.Unfortunately,theiruppatefunctionsmovetheminonepirectionforever,sotheynevercomebackonscreenoncethey'veleft!We'pactuallylikethemtohavearecurringroleinthisgame,sowe'llusesomebooleanlogictomovethembacktotheirstartingpointsoncetheygooffscreen.Oncethestupentscorrectlyimplementon-screen?(anpitssub-partssafe-left?anpsafe-right?),thenewbehavioroftargetanppangeristhatoncetheyareoffthescreentheyreturntotheirstartingpositionbutwithanewy-value.Fromthisnewverticalpositiontheywillcontinuetomoveacrossthescreen.Ifone(orboth)ofthecharactersgooffthescreenanpneverreappear,themostlikelysourceoftheerroristhatoneofthenewlyimplementepbooleanstatementsisincorrect.
ACTIVITY:THEBIGGAME-BOOLEANS2)OnlinePuzzlesReturntoyourBigGametouseBooleanstokeepyourplayercharacteronscreen.HeaptoCSinAlgebrastage16inCopeStupiotogetstartepprogramming.
43
UUNPLUGGED
ConditionalsandPiecewiseFunctionsLessontime:30-60Minutes
LESSONOVERVIEWCurrently,evenwhenpassingparameterstofunctions,ouroutputsfollowaveryrigidpattern.Now,supposewewantparameterswithsomevaluestocreateoutputsusingonepattern,butothervaluestouseadifferentpattern.Thisiswhereconditionalsareneeded.Inthisstagestudentswilllearnhowconditionalstatementscancreatemoreflexibleprograms.
LESSONOBJECTIVESStudentswill:
Understandthatpiecewisefunctionsevaluatethedomainbeforecalculatingresults.Evaluateresultsofpiecewisefunctions.
ANCHORSTANDARDCommonCoreMathStandardsF.IF.7.b:Graphsquareroot,cuberoot,andpiecewise-definedfunctions,includingstepfunctionsandabsolutevaluefunctions.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)Conditionals
Activity:ConditionalsandPiecewiseFunctions3)ConditionalsandPiecewiseFunctions
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheTeacher
LessonSlideDeck
44
GETTINGSTARTED1)VocabularyThislessonhasthreenewandimportantwords:Clause-aquestionanditscorrespondinganswerinaconditionalexpressionConditional-acodeexpressionmadeofquestionsandanswersPiecewiseFunction-afunctionwhichevaluatesthedomainbeforechoosinghowtocreatetherange
2)ConditionalsWecanstartthislessonoffrightaway
Lettheclassknowthatiftheycanbecompletelyquietforthirtyseconds,youwilldosomethinglike:SinganoperasongGivefivemoreminutesofrecessorDoahandstand
Startcountingrightaway.Ifthestudentssucceed,pointoutrightawaythattheysucceeded,sotheydogetthereward.Otherwise,pointoutthattheywerenotcompletelyquietforafullthirtyseconds,sotheydonotgetthereward.
Asktheclass"Whatwastheconditionofthereward?"Theconditionwasifyouwerequietfor30seconds
Ifyouwere,theconditionwouldbetrue,thenyouwouldgetthereward.Ifyouweren't,theconditionwouldbefalse,thentherewardwouldnotapply.
Canwecomeupwithanotherconditional?IfIsay"question,"thenyouraiseyourhand.IfIsneeze,thenyousay"Gesundheit."Whatexamplescanyoucomeupwith?
Uptonow,allofthefunctionsyou’veseenhavedonethesamethingtotheirinputs:green-trianglealwaysmadegreentriangles,nomatterwhatthesizewas.safe-left?alwayscomparedtheinputcoordinateto0,nomatterwhatthatinputwas.update-dangeralwaysaddedorsubtractedthesameamount
Conditionalsletourprogramsrundifferentlybasedontheoutcomeofacondition.Eachclauseinaconditionalevaluatestoabooleanvalue-ifthatbooleanisTRUE,thenweruntheassociatedexpression,otherwisewecheckthenextclause.We'veactuallydonethisbeforewhenweplayedthebooleangame!Ifthebooleanquestionwastrueforyou,youremainedstanding,andifitwasfalseyousatdown.Let'slookataconditionalpiecebypiece:(x>10)->"That'sprettybig"(x<10)->"That'sprettysmall"else->"That'sexactlyten"Ifwedefinex=11,thisconditionalwillfirstcheckifx>10,whichreturnsTRUE,sowegettheString"That'sprettybig"-andbecausewefoundatrueconditionwedon'tneedtokeeplooking.Ifwedefinex=10,thenwefirstcheckifx>10(FALSE),thenwecheckx<10(FALSE),sothenwehittheelsestatement,whichonlyreturnssomethingifnoneoftheotherconditionsweretrue.Theelsestatementshouldbeconsideredthecatch-allresponse-withthatinmind,what'swrongwithreplying"That'sexactlyten"?Whatifx="yellow"?Ifyoucanstateaprecisequestionforaclause,writetheprecisequestioninsteadofelse.Itwouldhavebeenbettertowritethetwoconditionsas(x>10)and(x<=10).Explicitquestionsmakeiteasiertoreadandmaintainprograms.Functionsthatuseconditionsarecalledpiecewisefunctions,becauseeachconditiondefinesaseparatepieceofthefunction.Whyarepiecewisefunctionsuseful?Thinkabouttheplayerinyourgame:you’dliketheplayerto
45
moveonewayifyouhitthe"up"key,andanotherwayifyouhitthe"down"key.Movingupandmovingdownneedtwodifferentexpressions!Withoutconditionals,youcouldonlywriteafunctionthatalwaysmovestheplayerup,oralwaysmovesitdown,butnotboth.Nowlet'splayagame.
ACTIVITIES:3)ConditionalsandPiecewiseFunctionsLivingFunctionMachines-Conditionals:ExplaintotheclassthattheywillbeplayingtheroleofFunctionMachines,followingafewsimplerules:-Wheneveryourfunctioniscalled,theonlyinformationyouareallowedtotakeiniswhat'sdescribedinyourDomain.-YourfunctionmustreturnonlywhatisdescribedinyourRange.-Youmustfollowthestepsprovidedinyourdefinition-nomagic!Thistime,however,everyonewillberunningthesamefunction.Andthatfunctioniscalled'simon_says'andithasthefollowingContract:simon_says:String->MovementGivenaStringthatdescribesanaction,producetheappropriatemovement.Ifanunknownactioniscalled,lowerbothhands.Examplessimon_says("lefthandup")=RaiseLeftHandsimon_says("righthandup")=RaiseRightHandsimon_says("lefthanddown")=LowerLeftHandsimon_says("righthanddown")=LowerRightHandDefinitionsimon_says(action)=cond{"lefthandup":RaiseLeftHand,"righthandup":RaiseRightHand,"lefthanddown":LowerLeftHand,"righthanddown":LowerRightHand,else:LowerBothHands}Reviewthecontractparts:name,domain,range,parameters(inputtypes),returntypes(outputvalues)Saytotheclass:“Hereiswhattheinitialcodelookslike.Wewilladdseveralclausesbuttheclausesthataretherewillalwaysbethereandthefinalelseaction(oftencalledthedefaultresult)willalwaysbeLowerBothHands
simon_says("righthandup")simon_says("lefthandup")-bothhandsshouldbeupsimon_says("righthandup")-bothhandsshouldstillbeupsimon_says("lefthanddown")-leftshouldbedown,rightshouldbeupsimon_says("righthandup")-leftshouldbedown,rightshouldbeupsimon_says("hokeypokey")-bothhandsshouldbedownsimon_says("lefthandup")-lefthandshouldbeupsimon_says("rightup")-trick,therearenomatchessotheelsestatementiscalled
Ifanyonemakesamistake,theymust"reboot"bysittingdownandwaitingforthenextroundtostart.Saytotheclass:“Nowwe'regoingtorewriteourfunctionalittlebit-insteadoftakingaStringasitsDomain,simon_sayswilltakeaNumber.Here'swhatournewfunctionlookslike:simon_says(action)=cond{
46
(action<10):RaiseLeftHand,(action<20):RaiseRightHand,(action>20)and(action<50):LowerLeftHand,(action>50)and(action<100):LowerRightHand,else:LowerBothHands}Continueplayingusingnumbersinthesimon_saysfunction,suchassimon_says(15),whichshouldresultinRaiseRightHand.Asstudentsgetcomfortablewiththenewrules,youcanthrowinsometrickquestions,suchassimon_says(20)orsimon_says(50),bothofwhichshouldcalltheelsestatement.Youcanextendthisactivityinmanyways,forexample:
Callthefunctionwithasimpleexpression,suchassimon_says(30/2)AddmoreconditionsofyourownCreatemultiplefunctionsanddividetheclassintogroupsAllowstudentstotakeoverasthe'programmer'
ConnectiontoMathematicsandLifeTherearepiecewisefunctionsinmathematicsaswell.Theabsolutevaluefunctiony=|x|canbere-writtenasy={-x:x<0,x:x>0,0}
Notethatinmathematicalterms,theclauseforthedomainisusuallylistedsecondinsteadoffirst.Adataplanonaphonebillmightbestructuredas:
$40forlessthan5GB$8perGBfor5-10GB$12perGBforusingmorethan10GB
Thiscouldbegraphedwiththefollowingpiecewisefunctiony={40:x<5,8x:5=<x=<10,12x:x>10}
47
Derivedfrom
Anotherverycommonpiecewisefunctionsisfortaxicabs.$3for0to2miles$1foreachpartialmileafterthat
Thiscouldbegraphedwiththefollowingpiecewisefunctiony={3:x<2,[[x]]+2:x>=2}where[[x]]isthegreatestintegerfunctionorwhatisoftencalledafloorfunctionincomputerlanguages.ThegreatestintegerfunctionreturnsthegreatestINTEGERlessthatthecurrentvalue.Forinstance[[2.9]]is2and[[3.1]]is3.
48
18CSinAlgebra|Lesson18
ConditionalsandUpdatePlayerLessontime:30-60Minutes
LESSONOVERVIEWUsingconditionals,studentswillwritefunctionsandprogramsthatchangetheirbehaviorbasedonlogicalevaluationofinputvalues.
LESSONOBJECTIVESStudentswill:UseBooleanoperatorstocomparevalues.ApplyBooleanlogic,suchasAND,OR,andNOT,tocomposecomplexBooleancomparisons.Writeconditionalstatementsthatevaluatedifferentlybasedontheirinputvalues.
ANCHORSTANDARDCommonCoreMathStandards6.NS.8:Solvereal-worldandmathematicalproblemsbygraphingpointsinallfourquadrantsofthecoordinateplane.Includeuseofcoordinatesandabsolutevaluetofinddistancesbetweenpointswiththesamefirstcoordinateorthesamesecondcoordinate.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:Conditionals2)OnlinePuzzles
ExtensionActivities3)ImprovingLuigi'sPizza4)UpdatePlayer
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREP
49
FortheStudentCost✄esignReci☎e(inthestu✆entwork book )Update-playerDesignRecipe(inthestudentworkbook)KeyCodeReference(inthestudentworkbook)
GETTINGSTARTED1)IntroductionRemindstudentsofthegametheyplayedinthelaststage.Whatweresomeofthetrickyelementsofconstructingagoodconditionalstatement?Ordermatters(thefirstconditioninthelisttoreturntruewins).Writeclearandexplicitconditions.Usetheelseclauseasacatch-allforconditionsthatyoudon'texpectorcan'twriteexplicitconditionsfor.Allconditionalsmusthaveatleastoneconditionandanelsestatement,youcanaddorremovefurtherconditionsusingthebluebuttons.
Attheendofthisstage,studentswillreturntotheirBigGametocompletetheupdate-playerfunction.Thisfunctioncontainsaconditionalthatwillcheckwhichkeywaspressed(usingkeycodes),andmovetheplayerupordownaccordingly.We'veprovidedakeycodereferenceforstudentsincasetheywishtousekeysotherthanthedefaultup(38)anddown(40)arrows.
ACTIVITY:CONDITIONALS2)OnlinePuzzlesHeadtoCSinAlgebrastage18inCodeStudiotogetstartedprogramming.
EXTENSIONACTIVITIES3)ImprovingLuigi'sPizzaThefinalpuzzleintheLuigi'sPizzasequenceisaFreePlaypuzzlethatallowsforstudentstoextendtheprograminanumberofdifferentways.Whilesomeofthepotentialextensionsseemsimple,theycanbedeceptivelychallengingtogetworking.Allowstudentstoexploreextensionsindividually,orchooseonetoworkthroughasawholeclass.CouponCode:Writeafunctioncouponthattakesinatoppingandacouponcodeandreturnsthepriceofa
LESSONTIP Besuretocheckstudents’ContractsandExamplesduringthisexercise,especiallywhenit’stimeforthemtocircleandlabelwhatchangesbetweenexamples.ThisisthecrucialstepintheDesignRecipewheretheyshoulddiscovertheneedforcond.
50
✝erive✞from
pizzawiththattopping,with%40offisthecodeiscorrect.MultipleToppings:Writeafunctiontwo-toppingsthattakesintwotoppingsandreturnsthepriceofapizzawiththosetoppings.PictureMenu:Writeafunctionpizza-picthattakesinatoppingandreturnsasimpleimagerepresentingapizzawiththattopping.
3)UpdatePlayerTheupdate-playerfunctionisoneofthemostextensibleintheBigGame.Here'sabrieflistofpotentialchallengeextensionstogivestudents:Warping:insteadofhavingtheplayer’sy-coordinatechangebyaddingorsubtracting,replaceitwithaNumbertohavetheplayersuddenlyappearatthatlocation.(Forexample,hittingthe"c"keycausestheplayertowarpbacktothecenterofthescreen,aty=200.)Boundary-detection:KeeptheplayeronscreenbychangingtheconditionformovingupsothattheplayeronlymovesupiftheupkewaspressedANDplayer-yisbelowthetopborder.Likewise,changetheconditionfordowntoalsocheckthatplayer-yisabovethebottom.Wrapping:Addacondition(beforeanyofthekeys)thatcheckstoseeiftheplayer’sy-coordinateisabovethescreen.Ifitis,havetheplayerwarptothebottom.Addanotherconditionsothattheplayerwarpsbackuptothetopofthescreenifitmovesbelowthebottom.Dissapear/Reappear:Havetheplayerhidewhenthe"h"keyispressed,onlytore-appearwhenitispressedagain!
51
UUNPLUGGED
CollisionDetectionandthePythagoreanTheoremLessontime:30-60Minutes
LESSONOVERVIEWDeterminingwhenobjectsonthescreentouchisanimportantaspectofmostgames.Inthislessonwe'lllookathowthePythagoreanTheoremandtheDistanceFormulacanbeusedtomeasurethedistancebetweentwopointsontheplane,andthendecidewhetherthosetwopoints(orgamecharacters)aretouching.
LESSONOBJECTIVESStudentswill:
Demonstratethatcircleswilloverlapifthedistancebetweentheircentersislessthanthesumoftheirradii.Showthatthedistanceoftwopointsgraphedin2dimensionscanberepresentedasthehypotenuseofarighttriangle.UnderstandthatthePythagoreanTheoremallowsyoutocalculatethehypotenuseofarighttriangleusingthelengthofthetwolegs.ApplythePythagoreanTheoremtocalculatethedistancebetweenthecentersoftwoobjects.
ANCHORSTANDARDCommonCoreMathStandards
8.G.7:ApplythePythagoreanTheoremtodetermineunknownsidelengthsinrighttrianglesinreal-worldandmathematicalproblemsintwoandthreedimensions.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Vocabulary2)AretheyTouching?
Activity:CollisionDetection3)ProvingPythagoras4)CollisionDetection
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREP
52
FortheStudentC ollisionWorksheetsSafe-right?DesignRecipe(inthestudentworkbook)Onscreen?DesignRecipe(inthestudentworkbook)
FortheTeacherLanguageTable(seebelow)CutoutsofPythagoreanTheorempackets(1,2)-1pergroupofstudentsworkingtogether
GETTINGSTARTED1)VocabularyThislessonhasonenewandimportantword:
Hypotenuse-thesideoppositethe90-degreeangleinarighttriangle2)AretheyTouching?Supposetwoobjectsaremovingthroughspace,eachonehavingitsown(x,y)coordinates.Whendotheiredgesstarttooverlap?Theycertainlyoverlapiftheircoordinatesareidentical(x1=x2,y1=y2),butwhatiftheircoordinatesareseparatedbyasmalldistance?Justhowsmalldoesthatdistanceneedtobebeforetheiredgestouch?Visualaidsarekeyhere:besuretodiagramthisontheboard!Inonedimension,it’seasytocalculatewhentwoobjectsoverlap.Inthisexample,theredcirclehasaradiusof1,andthebluecirclehasaradiusof1.5Thecircleswilloverlapifthedistancebetweentheircentersislessthanthesumoftheirradii(1+1.5=2.5).Howisthedistancebetweentheircenterscalculated?Inthisexample,theircentersare3unitsapart,because4−1=3.
Workthroughanumberofexamples,usinganumberlineontheboardandaskingstudentshowtheycalculatethedistancebetweenthepoints.Havingstudentsactthisoutcanalsoworkwell:drawanumberline,havetwostudentsstandatdifferentpointsontheline,usingtheirarmsorcutoutstogiveobjectsofdifferentsizes.Movestudentsalongthenumberlineuntiltheytouch,thencomputethedistanceonthenumberline.Yourgamefileprovidesafunctioncalledline-lengththatcomputesthedifferencebetweentwopointsonanumberline.Specifically,line-lengthtakestwonumbersasinputanddeterminesthedistancebetweenthem
LESSONTIP Wouldthedistancebetweenthemchangeifthecirclesswappedplaces?Whyorwhynot?
LESSONTIP Whatanswerswouldyouexpectfromeachofthefollowingtwousesofline-length:line-length(2,5)
line-length(5,2)Doyouexpectthesameanswerregardlessofwhetherthelargerorsmallerinputgoesfirst?
53
Unfortunately,line-lengthcanonlycalculatethedistancebetweenpointsinasingledimension(xory).Howwouldthedistancebecalculatedbetweenobjectsmovingin2-dimensions(likeyourgameelements)?line-lengthcancalculatetheverticalandhorizontallinesinthegraphicshownhere,usingthedistancebetweenthex-coordinatesandthedistancebetweenthey-coordinates.Unfortunately,itdoesn’ttellushowfarapartthetwocentersare.
Drawingalinefromthecenterofoneobjecttotheothercreatesaright-triangle,withsidesA,BandC.AandBaretheverticalandhorizontaldistances,withCbeingthedistancebetweenthetwocoordinates.line-lengthcanbeusedtocalculateAandB,buthowcanwecalculateC?
Inarighttriangle,thesideoppositethe90-degreeangleiscalledthehypotenuse.Thinkingbacktoourcollisiondetection,weknowthattheobjectswillcollideifthehypotenuseislessthanthesumoftheirradii.Knowingthelengthofthehypotenusewillbeessentialtodeterminewhenacollisionoccurs.
ACTIVITIES:3)ProvingPythagorasIfyourstudentsarenewtothePythagoreanTheorem,orareinneedofarefresher,thisactivityisanopportunitytostrengthentheirunderstandinginahands-onfashion.Organizestudentsintosmallgroupsof2or3.
PassoutPythagoreanProofmaterials(1,2)toeachgroup.Havestudentscutoutthefourtrianglesandonesquareonfirstsheet.Explainthat,foranyrighttriangle,itispossibletodrawapicturewherethehypotenuseisusedforallfoursidesofasquare.Havestudentslayouttheirgraytrianglesontothewhitesquare,asshowinthisdiagram.PointoutthatthesquareitselfhasfouridenticalsidesoflengthC,whicharethehypotenusesforthetriangles.Iftheareaofasquareisexpressedbyside∗side,thentheareaofthewhitespaceisC2.Havestudentsmeasuretheinnersquareformedbythefourhypotenuses(C)
54
Derivedfrom
Bymovingthegraytriangles,itispossibletocreatetworectanglesthatfitinsidetheoriginalsquare.Whilethespacetakenupbythetriangleshasshifted,ithasn’tgottenanybiggerorsmaller.Likewise,thewhitespacehasbeenbrokenintotwosmallersquares,butintotalitremainsthesamesize.Byusingtheside-lengthsAandB,onecancalculatetheareaofthetwosquares.
Youmayneedtoexplicitlypointoutthattheside-lengthsofthetrianglescanbeusedastheside-lengthsofthesquares.Havestudentsmeasuretheareaofthesmallersquare(A)Havestudentsmeasuretheareaofthelargersquare(B)AskstudentstocomparetheareofsquareA+squareBtotheareaofsquareC
ThesmallersquarehasanareaofA2,andthelargersquarehasanareaofB2.Sincethesesquaresarejusttheoriginalsquarebrokenupintotwopieces,weknowthatthesumoftheseareasmustbeequaltotheareaoftheoriginalsquare:
A2+B2=C2
4)CollisionDetectionInthisactivitystudentswill:
Createrighttrianglesonagraph.CalculatethehypotenusebydirectmeasurementandbythePythagoreanTheorem.Determineifcircleshavecollidedbyexaminingvisually.Determineifcircleshavecollidedbycomparingdistanceandradii.
DetailedinstructionsareprovidedontheCollisionWorksheet.
55
20CSinAlgebra|Lesson20
TheBigGame-CollisionDetectionLessontime:30-60Minutes
LESSONOVERVIEWTofinishuptheirvideogames,studentswillapplywhattheyhavelearnedinthelastfewstagestowritethefinalmissingfunctions.We'llstartbyusingbooleanstocheckwhetherkeyswerepressedinordertomovetheplayersprite,thenmoveontoapplyingthePythagoreanTheoremtodeterminewhenspritesaretouching.
LESSONOBJECTIVESStudentswill:
ApplytheDistanceFormulatodetectwhentwopointsonacoordinateplaneareneareachother.
ANCHORSTANDARDCommonCoreMathStandards8.G.7:ApplythePythagoreanTheoremtodetermineunknownsidelengthsinrighttrianglesinreal-worldandmathematicalproblemsintwoandthreedimensions.
Additionalstandardsalignmentcanbefoundattheendofthislesson
TEACHINGSUMMARYGettingStarted
1)Introduction
Activity:TheBigGame-CollisionDetection2)OnlinePuzzles
TEACHINGGUIDEMATERIALS,RESOURCES,ANDPREPFortheStudent
Line-lengthDesignRecipe(inthestudentworkbook)DistanceDesignRecipe(inthestudentworkbook)Collide?DesignRecipe(inthestudentworkbook)
56
Derivedfrom
GETTINGSTARTED1)IntroductionLet'sgetbackintothatBigGamefromstages7,12,and16.Previousworkwiththegamehascreatedmovementforthedangerandtargetcharacters,usingBooleanstocheckiftheyhaveleftthescreen.Thelasttimestudentsworkedontheirgametheyusedaconditionaltocheckwhichkeywaspressedandmaketheplayermoveaccordingly.Atthispointtheonlythinglefttodoistodecidewhentheplayeristouchingeitherthetargetordanger.Oncestudentshavesuccessfullycompletedthedistanceandcollide?functions,theirscorewillincreasewhentheplayertouchesthetarget,anddecreasewhenittouchesthedanger.ThePythagoreanTheoremstudiedinthelastlessonwillbeusedtodeterminewhenthecharactershavemadecontact.Studentsarenotrequiredtowritetheirownline-lengthfunction,butyoumayaskthemtocompletetheDesignRecipeforitanyway.Studentswillfirstcompletethedistancefunctionsothatitmeasuresthedistancebetweentwopoints,(px,py)and(cx,cy).Afterthestudentsimplementthedistanceformula,theywillneedtoimplementthetestsinthecollide?function.Oncetheselastfunctionsareputintoplace,scoringwillautomaticallyupdatebasedoncollisionsbetweentargetanddanger.
ACTIVITY:THEBIGGAME-COLLISIONDETECTION2)OnlinePuzzlesReturntoyourBigGametousecollisiondetectionlogicsothatyouknowwhenyourplayeristouchingthetargetorthedanger.HeadtoCSinAlgebrastage20inCodeStudiotogetstartedprogramming.
57
Student Workbook
Name: ____________________________ Course: ____________________________
Computer Sciencein Algebrapowered by
Name: ___________________________ Date: ___________ Per: __________
Reverse EngineeringUStage 1
1Code.org Computer Science in Algebra
2
Thing in the game... What changes about it? More Specifically...
Name: ___________________________ Date: ___________ Per: __________
UStage 1
1Code.org Computer Science in Algebra
3
Video Game Planning
Use this form to plan out your video game. Once your game is complete, the player will move up and down, the target and danger will move from left and right, and you will earn points by touching the target, and lose points by touching the danger.
Created by:
The game takes place in: (This will be the background image in your game)
The player is a:(The player moves up and down)
The target is a:(The Target moves left and right)
The danger is a:(The Danger moves left and right)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
4
*
Stage 2
2Evaluation Blocks
4
-/
3
*
+
*
2 * 5 32 / 3
4 - (3 / 2) (25 + 14) - 12
(3 + 12) * 16 (23 * 14) * (3 + 2)
1 + (15 * 5) 19 - (12 + 11)
(2 + 17) * (12 - 8) 4 - (6 - 17)
9 * (17 + 2) (12 * 4) / 3
Create the evaluation blocks for the provided equations.
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
5
___________________ : ____________________________________ -> ________________ name domain range
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Define: ________________ ( _______________ ) = ______________________________
___________________ : ____________________________________ -> ________________ name domain range
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Define: ________________ ( _______________ ) = ______________________________
___________________ : ____________________________________ -> ________________ name domain range
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Define: ________________ ( _______________ ) = ______________________________
___________________ : ____________________________________ -> ________________ name domain range
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Define: ________________ ( _______________ ) = ______________________________
Stage 9
9Fast Functions!
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
6
DesignRecipe
DThe Design Recipe
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description:
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
7
DesignRecipe
DThe Design Recipe
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description:
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
8
DesignRecipe
DThe Design Recipe
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description:
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
9
rocket-height (word problem)
Stage 10
10
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: A rocket blasts of, traveling at 15 meters per second.
Write a function called rocket-height that takes in the number of
seconds that have passed since the rocket took of, and which produces
the height of the rocket at that time.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
10
Stage 12
12
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: Write a function update-target which takes in the
target’s x-coordinate and produces the next x-coordinate, which is 10
pixels to the right.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
update-target (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
11
Stage 12
12
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: Write a function update-danger which takes in the
danger’s x-coordinate and produces the next x-coordinate, which is
10 pixels to the left.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
update-danger (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
12
Stage 15
15
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: Write a function safe-left?, which takes in an
x-coordinate and checks to see if it is greater than 50.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
safe-left? (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
13
Stage 15
15
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: Write a function safe-right?, which takes in an
x-coordinate and checks to see if it is less than 350.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
safe-right? (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
14
Stage 15
15
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Description: Write a function onscreen?, which takes in a character’s
x-coordinate and checks to see if it is safe on the left and on the right.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
onscreen? (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
15
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Define: ________________ ( _______________ ) = function name variables
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________________________________________________
Stage 18
18
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Definition
Description: Luigi’s Pizza has hired you as a programmer. They ofer “pepperoni” ($10.50), “cheese” ($9.00), “chicken” ($11.25), and “broccoli” ($10.25). Write a function called cost which takes in the name of a topping and outputs the cost of a pizza with that topping.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
cost (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
16
Key Code ReferenceStage 18
18
Key Code Key Code
left arrow 37 G 71
up arrow 38 H 72
right arrow 39 I 73
down arrow 40 J 74
0 48 K 75
1 49 L 76
2 50 M 77
3 51 N 78
4 52 O 79
5 53 P 80
6 54 Q 81
7 55 R 82
8 56 S 83
9 57 T 84
A 65 U 85
B 66 V 86
C 67 W 87
D 68 X 88
E 69 Y 89
F 70 Z 90
When you press a key on your keyboard, a unique numeric code is sent to your computer, which is then translated into a letter, number, or command. Use this handy key code reference sheet to make your Player sprite respond to diferent key presses.
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
17
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
Example: ________________ ( _______________ ) = ______________________________
update-player 38 240 240 + 10
240 - 10update-player 40 240
update-player 38 250
update-player 40 250
Define: ________________ ( _______________ ) = function name variables
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________________________________________________
Stage 18
18
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Definition
Description: Write a function called update-player, which takes in the key code of the key pressed and the player’s y-coordinate, and returns the new y-coordinate.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
update-player (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
18
1 53 7 102 6 94 8 11 12
1
5
3
7
2
6
4
00
A
B
1. What is the radius of circle A? ___________
2. What is the radius of circle B? ___________
3. What is Radius A + Radius B ___________
4. Do the circles overlap? (true/false) ___________
5. What is the length of side a? ___________
6. What is the length of side b? ___________
7. Estimate the length of side c? ___________
8. What is a2 + b2 ___________
On the graph:
Label the right angle as C
Label segment AB as c
Label segment AC as b
Label segment CB as a
Graph #1
Collision DetectionStage 19
19
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
19
1 53 7 102 6 94 8 11 12
1
5
3
7
2
6
4
00
On the graph:
Draw a segment from point A to point B
Label segment AB as c
Draw a right triangle using segment c as the hypotenuse.
Label the right angle as C
Label segment AC as b
Label segment CB as a
A
B
1. What is the radius of circle A? ___________
2. What is the radius of circle B? ___________
3. What is Radius A + Radius B ___________
4. Do the circles overlap? (true/false) ___________
5. What is the length of side a? ___________
6. What is the length of side b? ___________
7. Estimate the length of side c? ___________
8. What is a2 + b2 ___________
Graph #2
Collision DetectionStage 19
19
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
20
1 53 7 102 6 94 8 11 12
1
5
3
7
2
6
4
00
On the graph:
Draw a segment from point A to point B
Label segment AB as c
Draw a right triangle using segment c as the hypotenuse.
Label the right angle as C
Label segment AC as b
Label segment CB as a
A
B
1. What is the radius of circle A? ___________
2. What is the radius of circle B? ___________
3. What is Radius A + Radius B ___________
4. Do the circles overlap? (true/false) ___________
5. What is the length of side a? ___________
6. What is the length of side b? ___________
7. Estimate the length of side c? ___________
8. What is a2 + b2 ___________
Graph #3
Collision DetectionStage 19
19
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
21
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
line-length 10 5 10 - 5
line-length 2 8 8 - 2
Define: ________________ ( _______________ ) = function name variables
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________ ___________________________________
___________________________________________________________________________
Stage 20
20
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Examples
Definition
Description: Write a function called line-length, which takes in two numbers and returns the diference between them. It should always subtract the smaller number from the bigger one.
Contract and Purpose Statement
Every contract has three parts...
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
line-length (word problem)
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
22
The Distance FormulaStage 20
20
The distance between two points (25, 50) and (300, 400) can be calculated with the distance formula as
line-length(25, 300)2 + line-length(50, 400)2
Convert the formula in a circle of evaluation.
line-length
25 300
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
23
Stage 20
20
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Description: Write a function distance, which takes four inputs:• px: The x-coordinate of the player• py: The y-coordinate of the player• cx: The x-coordinate of another game character• cy: The y-coordinate of another game character
It should use the Distance formula to return the distance between both points.
Contract and Purpose Statement
Every contract has three parts...
distance (word problem)
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name: ___________________________ Date: ___________ Per: __________
UCode.org Computer Science in Algebra
24
Stage 20
20
___________________ : ____________________________________ -> ________________ function name domain range
___________________________________________________________________________ what does the function do?
Description: Write a function collide?, which takes four inputs:• px: The x-coordinate of the player• py: The y-coordinate of the player• cx: The x-coordinate of another game character• cy: The y-coordinate of another game character
Is the player’s x and y within 100 pixels of the other character’s x and y?
Contract and Purpose Statement
Every contract has three parts...
collide? (word problem)
Examples
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Example: ________________ ( _______________ ) = ______________________________ function name input(s) what the function produces
Definition
Define: ________________ ( _______________ ) = function name variables
___________________________________________________________________________ what the function does with those variables
Write some examples for your function in action...
Write the deinition, giving variable names to all your input values
Name Domain Range Example
Contract Log
Name Domain Range Example
Contract Log