CompSci 4Chap 7 Sec 2Apr 7, 2005Prof. Susan RodgerNote: thanks to Wanda Dann and Steve Cooper for slide ideasAnnouncements• Read Chapter 8.1 for next time• Assignment 8 Part 1 due Tuesday– Detailed storyboard– Name of partnerWhat we will do today• Lecture on Chap 7 Sec 2 and Tips and Tech.– While loop – indefinite loop– Event Loops• ClassworkRepetition• Sometimes don’t know exactly how many times a set of instructions are repeated.• Stopping is based on a condition•Example: – Game of Chess, how many moves until win– Stop: when markers are in check mate positionIndefinite Repetition• In programs where number of repetitions now known in advance, can use– While statement (today)– Recursion (next time - Chap 8)While statement• While some condition is true– execute instructionsconditiontrue?execute instructionsnoyesexitloopExample• Common feature in popular “action films”is a chase scene• Example: hungry shark chasing fleeing goldfish– Repeat: fish swim away from shark, and shark swim toward fish– Shark swim distance a little more than fish swim distance– Eventually, shark will catch up with fish and eat fishStoryboardWorld.chaseWhile goldfish more than .5 meters from sharkDo in ordershark point at goldfishDo togethershark swim (toward goldfish)goldfish flee (away from shark)shark eat goldfishshark.Swim, shark.eat and goldfish.flee in bookWorld.chaseShark will catch goldfish• How do you know the shark will eventually catch the goldfish?– Shark always moves 0.4 meters towards goldfish– Goldfish moves randomly away from shark at most .2 meters– Shark will eventually catch up, the loop will endGeneral “Rule of Thumb”• As a general rule, a While loop should be written so the loop will eventually end– Requires statements inside the loop change the conditions of the world such that condition for While eventually becomes false• If While loop never ends– Infinite while loopPractice – From Bunny eats Broccoli• Replace with while loop, bunny hops until close to closestBroc (< 1 meter)Practice – Eat Broccoli until all invisibleAssume method bunny.hopToClosestBroccoliAndEatIt existsReWrite with while loop• Eat broccoli (broc1, broc2, and broc3) until gone (all invisible)• Assume at least one of the brocs is visible when startClasswork today• Modify play method in CinderellaMeetsPrinceCode (cont)Rewrite Play method• Do not change any code except the Play method• Use a while instead of a loop infinitely• Cinderella and Prince randomly move until they meet in the middle – Note they STOP!• If one gets to middle alone, then they turn and start over.• Download
View Full Document