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
if
with an expression that evaluates totrue
orfalse
. - The argument to
touches
andinside
can be sprites or the backgroundwindow
.touches
also accepts colors. - Use a
break
statement within anif
block inside afor
block 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 namedant
reaches the (red) finish line.
Math and Computer Concepts:
- Certain special statements allow us to control the flow of our code. We already use
for
statements to cause designated blocks of code to repeat. The conditional statementsif
andelse
are also tools for control. If the expression in theif
statement 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
touches
orinside
, 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
true
andfalse
. That's whytrue
andfalse
are referred to as Boolean values and why functions that returntrue
orfalse
(such astouches
andinside
) 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
inside
function to carry out the conditional logic. - CoinFlip: Simulate the flipping of a single coin using the
random
function. Use anif
/else
statement to show the appropriate image. - LuckyStreak: Use a for loop to simulate flipping a coin multiple times. Stop once you get tails, using
break
to 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.