lesson 3.1 introduction to universe programs 3.1 introductio… · 5. design systems iteratively 6....

Post on 22-Jul-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

IntroductiontoUniversePrograms

CS5010ProgramDesignParadigms“Bootcamp”Lesson3.1

1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.

ModuleOutline

• WewilllearnabouttheUniversemodule,whichwewillusetocreateinteractiveanimations.

• Wewilllearnhowtodo“iterativerefinement”– thatis,addingfeaturestoaprogram

• Wewilllearnmoreabouthowtodesigndata.• We’lldoallthisinthecontextof3versionsofasimplesystem.

2

Generalization

OverConstants

OverExpressions

OverContexts

OverDataRepresentations

OverMethodImplementations

MixedData

DataRepresentations

Basics

RecursiveData

FunctionalData

Objects&Classes

Stateful Objects

DesignStrategies

Combinesimplerfunctions

Useatemplate

DivideintoCases

Callamoregeneralfunction

CommunicateviaState

Module03

3

Let'sseewhereweare

AddingaNewFeaturetoanExistingProgram

1.Perform informationanalysisfornewfeature

2.Modifydatadefinitions asneeded

3.Updateexistingfunctionstoworkwithnewdatadefinitions

4.Writewishlist offunctionsfornewfeature

5.DesignnewfunctionsfollowingtheDesignRecipe

6.Repeatforthenextnewfeature

4

TheSixPrinciples for WritingBeautifulPrograms

1.ProgrammingisaPeopleDiscipline

2.RepresentInformationasData;InterpretDataasInformation

3. Programsshouldconsistoffunctionsandmethodsthatconsumeandproducevalues

4.DesignFunctions Systematically

5.DesignSystemsIteratively

6.Passvalueswhenyoucan,sharestateonlywhenyoumust.

The SystemDesignRecipe

1.Writeapurposestatementforyoursystem.

2.Designdatatorepresenttherelevantinformation intheworld.

3.Makeawishlist ofmainfunctions.Writedowntheircontractsandpurposestatements.

4.Designtheindividualfunctions.Maintainawishlist(orwishtree)offunctionsyouwillneedtowrite.

Thismodule ismostlyaboutprinciple#5:“DesignSystemsIteratively”

LearningObjectivesforthislesson• Inthislesson,youwilllearnaboutthe2htdp/universemodule,whichallowsyoutocreateinteractiveanimations.

• Attheendofthislesson,studentsshouldbeableto:– Usethe2htdp/universemoduletocreateasimpleinteractiveanimation,including:• Analyzingdatatodeterminewhetheritshouldbeconstantorpartoftheworldstate,

• Writingdatadefinitionsforworlds,keyevents,andmouseevents,and

• Writingcodetohandlethevariouseventsduringtheanimation.– ExplainthestepsoftheSystemDesignRecipe

5

The2htdp/universemodule

• Providesawayofcreatingandrunninganinteractivemachine.

• Machinewillhavesomestate.• Machinecanrespondtoinputs.• Responsetoinputisdescribedasafunction.• Machinecanshowitsstateasascene.• Wewillusethistocreateinteractiveanimations.

6

Example:atrafficlight• Thelightisamachinethatrespondstotimepassing;astimepasses,thelightgoesthroughitscycleofcolors.

• Thestateofthemachineconsistsofitscurrentcolorandtheamountoftime(inticks)untilthenextchangeofcolor.Ateverytick,theamountoftimedecreasesby1.

• Whenthetimerreaches0,thelightgoestoitsnextcolor(fromgreentoyellow,fromyellowtored,fromredtogreen),andthetimerisresettothenumberofticksthatlightshouldstayinitsnewcolor.

• Inaddition,thetrafficlightshouldbeabletodisplayitselfasscene,perhapsliketheoneontheslide.

7

TrafficLightExample• Thetrafficlightisthemachine.Itsstateiscompoundinformation:– itscurrentcolorAND#ofticksuntilnextchange

• Inputswillbethetime(ticks).Ateverytick,thetimerisdecremented.

• Whenthetimerreaches0,thelightgoestoitsnextcolor(fromgreentoyellow,fromyellowtored,fromredtogreen),andthetimerisresettothenumberofticksthatlightshouldstayinitsnewcolor.

• Thetrafficlightcanshowitsstateasascene,perhapssomethinglikethis:

8

Asecondexample:TheFallingCatProblemStatement

• Wewillproduceananimationofafallingcat.• Thecatwillstartsatthetopofthecanvas,andfallataconstantvelocity.

• Ifthecatisfalling,hittingthespacebarshouldpausethecat.

• Ifthecatispaused,hittingthespacebarshouldunpause thecat.

9

falling-cat.rkt demo

10

https://www.youtube.com/watch?v=ojHukwW-vuw

TheFallingCat:InformationAnalysis

• Therearetheonlytwothingsthatchangeastheanimationprogresses:thepositionofthecat,andwhetherornotthecatispaused.Sothat’swhatweputinthestate:

• Thestateofthemachinewillconsistof:– anintegerdescribingthey-positionofthecat.– aBooleandescribingwhetherornotthecatispaused

11

FallingCat:DataDesign

(define-struct world (pos paused?));; A World is a (make-world Integer Boolean);; Interpretation: ;; pos describes how far the cat has fallen, in pixels. ;; paused? describes whether or not the cat is paused.

;; template:;; world-fn : World -> ??;(define (world-fn w); (... (world-pos w) (world-paused? w)))

12

FallingCat1:InformationAnalysis,part2

• Whatinputsdoesthecatrespondto?• Answer:itrespondstotimepassingandtokeystrokes

13

WhatkindofKeyEventsdoesitrespondto?

• Itrespondstothespacecharacter,whichisrepresentedbythestring""thatconsistsofasinglespace.

• Allotherkeyeventsareignored.

14

Next,makeawishlist

• Whatfunctionswillweneedforourapplication?

• Writecontractsandpurposestatementsforthesefunctions.

• Thendesigneachfunctioninturn.

15

Wishlist(1):Howdoesitrespondtotimepassing?

Weexpresstheanswerasafunction:

;; world-after-tick: World -> World;; RETURNS: the world that should;; follow the given world after a ;; tick.

16

Wishlist(2):Howdoesitrespondtokeyevents?

;; world-after-key-event :;; World KeyEvent -> World;; RETURNS: the world that should follow the given world;; after the given key event.;; on space, toggle paused?-- ignore all others

Herewe'vewrittenthepurposestatementintwoparts.Thefirst

isthegeneralspecification("produces theworldthat

should followthegivenworldafterthegivenkeyevent"),andthesecondisamorespecific

statementofwhatthatworldis.

17

Wishlist(3)

• Wealsoneedtorender thestateasascene:

;; world-to-scene : World -> Scene;; RETURNS: a Scene that portrays the given ;; world.

Anotherresponsedescribedasafunction!

18

Wishlist(4):Runningtheworld;; main : Integer -> World;; GIVEN: the initial y-position in the cat;; EFFECT: runs the simulation, starting with the cat;; falling;; RETURNS: the final state of the world

Herethefunctionhasaneffectintherealworld(like readingorprinting). Wedocument thisbywritinganEFFECTclauseinourpurpose statement.

Fornow, functions likemain willbeouronlyfunctions withreal-worldeffects.Allourother functionswillbepure:thatis,theycomputeavaluethatisamathematicalfunctionoftheirarguments.Theywillnothaveside-effects.

Side-effectsmakeitmuchmoredifficult tounderstandwhatafunction does.Wewillcoverthesemuchlaterinthecourse.

19

Next:developeachofthefunctions

;; world-after-tick : World -> World;; RETURNS: the world that should follow the given;; world after a tick

;; EXAMPLES: ;; cat falling:;; (world-after-tick unpaused-world-at-20) ;; = unpaused-world-at-28;; cat paused:;; (world-after-tick paused-world-at-20) ;; = paused-world-at-20

Weaddsomeexamples.We'veincludedsomecommentaryandusedsymbolicnamessothereadercanseewhattheexamplesillustrate.

20

Choosestrategytomatchthedata

• World iscompound,sousethetemplateforWorld

;; strategy: use template for World on w(define (world-after-tick w)(... (world-pos w) (world-paused? w)))

• Whatgoesin... ?• Iftheworldispaused,weshouldreturnwunchanged.Otherwise,weshouldreturnaworldinwhichthecathasfallenCATSPEED pixels.

21

FunctionDefinition;; STRATEGY: Use template for World on w

(define (world-after-tick w)(if (world-paused? w)

w(make-world (+ (world-pos w) CATSPEED)

(world-paused? w))))

Herewe’vejustwrittenoutthefunctionbecauseitwassosimple.Ifitwereanymorecomplicated,wemightbreakitupintopieces,asonthenextslide.

Amorecompletedescription ofourstrategymightbe

STRATEGY:UsetemplateforWorldonw,thencasesonwhetherwispaused.

Youdon’thavetobesodetailed.

22

FunctionDefinition;; STRATEGY: Use template for World on w

(define (world-after-tick w)(if (world-paused? w)

(paused-world-after-tick w)(unpaused-world-after-tick w))

Herewe’vebroken thedefinition intopieces.Ifeitherofthepiecesiscomplicated,thiswouldbebettercodethanwhatwesawontheprecedingslide.

23

Tests(define unpaused-world-at-20 (make-world 20 false)) (define paused-world-at-20 (make-world 20 true))(define unpaused-world-at-28 (make-world (+ 20 CATSPEED) false)) (define paused-world-at-28 (make-world (+ 20 CATSPEED) true))

(begin-for-tests(check-equal?

(world-after-tick unpaused-world-at-20) unpaused-world-at-28"in unpaused world, the cat should fall CATSPEED pixels and world should still be unpaused")

(check-equal? (world-after-tick paused-world-at-20)paused-world-at-20"in paused world, cat should be unmoved"))

24

Howdoesitrespondtokeyevents?

;; world-after-key-event : ;; World KeyEvent -> World;; GIVEN: a world w;; RETURNS: the world that should follow the given world;; after the given key event.;; on space, toggle paused?-- ignore all others;; EXAMPLES: see tests below;; STRATEGY: cases on kev : KeyEvent

(define (world-after-key-event w kev)(cond[(key=? kev " ")(world-with-paused-toggled w)][else w])) Wemakeadecisionbasedon

kev,andpassthedataon toahelpfunction todotherealwork.

25

RequirementsforHelperFunction;; world-with-paused-toggled : World -> World;; RETURNS: a world just like the given one, but with ;; paused? toggled

Ifthishelperfunction doeswhatit'ssupposed to,thenworld-after-key-eventwilldowhatit issupposed todo.

26

Tests(1);; for world-after-key-event, we have 4 ;; equivalence classes: all combinations of: ;; a paused world and an unpaused world, ;; and a "pause" key event and a "non-pause" key;; event

;; Give symbolic names to "typical" values:;; we have these for worlds, ;; now we'll add them for key events:(define pause-key-event " ")(define non-pause-key-event "q")

27

Tests(2)(check-equal?(world-after-key-event paused-world-at-20 pause-key-event)unpaused-world-at-20"after pause key, a paused world should become unpaused")

(check-equal?(world-after-key-event unpaused-world-at-20 pause-key-event)paused-world-at-20

"after pause key, an unpaused world should become paused")

28

Tests(3)(check-equal?(world-after-key-event paused-world-at-20 non-pause-key-event)

paused-world-at-20"after a non-pause key, a paused world should be unchanged")

(check-equal?(world-after-key-event unpaused-world-at-20 non-pause-key-event)

unpaused-world-at-20"after a non-pause key, an unpaused world should be unchanged")

29

Tests(4)(define (world-after-key-event w kev) ...)

(begin-for-test(check-equal? ...)(check-equal? ...) (check-equal? ...)(check-equal? ...))

(define (world-with-paused-toggled? w) ...)

Here'showwelayoutthetestsinourfile.

Contract,purposefunction, etc.,forworld-with-paused-toggled?

30

Nowwe'rereadytodesignourhelpfunction

31

DefinitionforHelperFunction;; world-with-paused-toggled : World -> World;; RETURNS: a world just like the given one, but with ;; paused? toggled;; STRATEGY: Use template for World on w(define (world-with-paused-toggled w)(make-world(world-pos w)(not (world-paused? w))))

Don'tneedtotestthisseparately,sincetestsforworld-after-key-eventalreadytestit.

32

Whatelseisonourwishlist?

;; world-to-scene : World -> Scene;; RETURNS: a Scene that portrays the given world.;; EXAMPLE: ;; (world-to-scene (make-world 20 ??));; = (place-image CAT-IMAGE CAT-X-COORD 20 EMPTY-CANVAS);; STRATEGY: use template for World on w

(define (world-to-scene w)(place-image CAT-IMAGE CAT-X-COORD

(world-pos w)EMPTY-CANVAS)) Here'swherewedecomposew.Note

thatwedon'tneed(world-paused? w).That'sok– thetemplatetellsuswhatwecan use,notwhatwemustuse.

33

Testingworld-to-scene;; an image showing the cat at Y = 20;; check this visually to make sure it's what you want(define image-at-20 (place-image CAT-IMAGE CAT-X-COORD 20 EMPTY-CANVAS))

;; these tests are only helpful if image-at-20 is the right image.;; Here I've made the strings into error messages. This is often;; works well.

(begin-for-tests(check-equal? (world->scene unpaused-world-at-20)image-at-20"unpaused world yields incorrect image")

(check-equal?(world->scene paused-world-at-20)image-at-20"paused world yields incorrect image"))

34

Lastwishlist item;; main : Integer -> World;; GIVEN: the initial y-position in the cat;; EFFECT: runs the simulation, starting with the cat;; falling;; RETURNS: the final state of the world

The realpurpose ofmain isnottoreturnausefulvalue;instead,itspurpose ishavesomevisibleeffectintherealworld– inthiscase,todisplaysomethingsontherealscreenandtakeinput fromtherealuser.Wedocument thisinthepurposestatementbywritinganEFFECT clause.

35

Templateforbig-bang;; big-bang ;; EFFECT : runs a world with the specified event handlers. ;; RETURNS: the final state of the world(big-bang

initial-world(on-tick tick-handler rate)(on-key key-handler)(on-draw render-fcn)))

namesofevents functions forresponses

framerateinsecs/tick

Thereareothereventsthatbig-bangrecognizes,seetheHelpDeskfordetails

36

Puttingthepiecestogether;; main : Integer -> World;; GIVEN: the initial y-position in the cat;; EFFECT: runs the simulation, starting with the cat;; falling;; RETURNS: the final state of the world;; STRATEGY: Combine simpler functions(define (main initial-pos)(big-bang (make-world initial-pos false)

(on-tick world-after-tick 0.5)(on-key world-after-key-event)(on-draw world-to-scene)))

Herethesimpler functionsarebig-bang,world-after-tick,world-after-key-event,andworld-to-scene

37

Let'swalkthroughfalling-cat.rkt

• Note:thisvideodiffersfromourcurrenttechnologyinacoupleofways:– ittalksabouttestsuites;thesearereplacedbybegin-for-test.

– ittalksabout"partitiondata"andgivesatemplateforFallingCatKeyEvents.We'vesimplifiedthepresentation-- nowwejusthaveKeyEvents,whicharescalars(notemplateneeded),andwetakethemapartusingthe"Cases"strategy.

– Andremember,the“StructuralDecomposition”strategyisnowcalled“Usetemplate”.

38

falling-cat.rkt readthrough

39

https://www.youtube.com/watch?v=ahAoFZVVqio

TheSystemDesignRecipe

• Inbuildingthissystem,wewereactuallyfollowingarecipe.

• Thisrecipeissowidelyusablethatwegiveitaname:theSystemDesignRecipe.

• Hereitis– youcanseethatitmatcheswhatwedid.

40

The SystemDesignRecipe1.Writeapurposestatementforyoursystem.2.Designdatatorepresenttherelevantinformation intheworld.3.Makeawishlist ofmainfunctions.Writedowntheircontractsandpurposestatements.4.Designtheindividualfunctions.Maintainawishlist (orwishtree)offunctionsyouwillneedtowrite.

41

Summary

• Theuniversemoduleprovidesawayofcreatingandrunninganinteractivemachine.

• Machinewillhavesomestate.• Machinecanrespondtoinputs.• Responsetoinputisdescribedasafunction.• Machinecanshowitsstateasascene.• Weusethistocreateinteractiveanimations.• Webuiltasystem,usingthesystemdesignrecipe.

42

NextSteps

• StudythefilesintheExamplesfolder.• Ifyouhavequestionsaboutthislesson,askthemontheDiscussionBoard

• DoGuidedPractice3.1• Goontothenextlesson

43

top related