Logic Ops!
Goals:
- Code more complex Boolean expressions using logic operators
Coding Snippets:
and
,or
, andnot
are logic operators. Use them express more complex logic in a single expression.- Logic operators combine boolean values, i.e.,
variables or expressions that evaluate to
true
orfalse
.
Math and Computer Concepts:
- The expression
a
or
b
evaluates to true if eithera
is true orb
is true (or both). The expressiona
and
b
evaluates to true if botha
andb
are true simultaneously. not
a
gives the opposite of the boolean expressiona
. For example,not
a
evaluates to true ifa
is false.- Logic operators allow us to avoid using nested if statements, as illustrated by the following functionally equivalent snippets:
- Animate rolling a pair of dice repeatedly until you get SnakeEyes. Report how many rolls it takes.
- WhichQuad: The four sections of the Cartesian coordinate system are called quadrants. They are numbered one through four, denoted with roman numerals, in a counter-clockwise fashion beginning in the upper-right quadrant. For this activity, draw a a set of math axes, then make a sprite move randomly about the screen, keeping it in the visible window. Use logic operators to highlight the quadrant in which the turtle is currently located.
- Predator: Write a script that instructs the default turtle to be a predator that hunts and eats several other randomly moving turtles (its prey). On each turn, the default turtle should turn to and move a step towards the closest turtle. If it touches it, it should eat it (i.e, code this by making the prey hide). Use a while loop that continues until all prey are consumed.
To make this (even) more challenging (and interesting), add blue dots representing pools of water. The prey not only move faster in water (like real turtles), but they should also be "hidden" from the predator. The predator won't move toward or eat prey it cannot see.
Activities:
Save each of the following in a folder called LogicOps.