Conditional Logic!
Goals:
- Use conditional logic to control program flow
- Use Boolean functions to enable sprites to interact with each other and with other elements on the screen
Coding Snippets:
- Follow the keyword
ifwith an expression that evaluates totrueorfalse. - The argument to
touchesandinsidecan be sprites or the backgroundwindow.touchesalso accepts colors. - Use a
breakstatement within anifblock inside aforblock to immediately exit a loop if the specified condition is met. For example, the code on the left could be used to end a race when the sprite namedantreaches the (red) finish line.
Math and Computer Concepts:
- Certain special statements allow us to control the flow of our code. We already use
forstatements to cause designated blocks of code to repeat. The conditional statementsifandelseare also tools for control. If the expression in theifstatement evaluates totrue, the program will branch one way, otherwise it will go in another direction. - Precede calls to functions that return information about the current state of the program, such as
touchesorinside, with a call toawait done defer()to ensure that they are evaluated in the right place.
- A branch of math, Boolean algebra, is devoted to working with logic values
trueandfalse. That's whytrueandfalseare referred to as Boolean values and why functions that returntrueorfalse(such astouchesandinside) are called Boolean functions.
Activities:
Save each of the following in a folder called ConditionalLogic.
- RandomTurtlesInside: Code an improved version of RandomTurtles, using
inside(window)to ensure the turtles always stay on screen. - CagedBird: Instruct a bird to move about inside a cage, changing direction if it reaches the sides or top. Construct the cage using a sprite, and use the
insidefunction to carry out the conditional logic. - CoinFlip: Simulate the flipping of a single coin using the
randomfunction. Use anif/elsestatement to show the appropriate image. - LuckyStreak: Use a for loop to simulate flipping a coin multiple times. Stop once you get tails, using
breakto exit the loop.
RaceWithEnd: draw start and finish lines, line up several turtles, and iterate repeatedly with random movements to carry out a race. When a turtle reaches (i.e.,touches) the finish line, stop the race.


