
A lot going on, right?
The conditionals we've played with so far couldn't handle this much. They could handle, "if Marte goes then throw to second, else throw to pitcher", but they can't handle, "if Marte goes and the pitcher throws a fastball, then throw to second, else throw back to the pitcher."
Fortunately, there are logical operators. What are logical operators, you ask? Good question. Let's take a look at Apple's documentation:

Now let's put these logical operators to work in our Marte and Harrison example above:

We have a few options here. If it is true that the runner on first goes AND (&&) it is true that the pitcher throws a fastball then the catcher can throw down to second (better chance than if the pitcher throws a slower pitch, but still a tough play); else, it is false that the runner on first goes in which case there is no need to throw to second.
In the second conditional, if it is true that the runner on first goes AND (&&) if it is true that the pitcher does NOT (!) throw a fastball, then the catcher can eat it as there's not a good chance he'll get the runner at second; else, if it is false that the runner is going to second, then there is no play at second and no need to throw it there.
In the third conditional, if it is true that the runner on first goes OR (||) it is true that the runner on third is fast, then the catcher should call a play for the shortstop to cut off the throw to second behind the pitcher's mound to try and get the runner from third at home; else, if it is false that the runner from first is going to steal second, there there is no play at second and no need to throw there.
As you may have noticed, when Marte did not go for second I skipped over whether or not Harrison would take off from third. Why? Because in baseball terms didn't matter. More importantly, the computer thinks the same way. That is, if the first condition is not true, then the program we've written breaks and stops running. The programs stops running as soon as something is false so in this case, it doesn't even get to Harrison.
Unfortunately, there's a problem with this code. Can you see it? The problem is that the catcher is told to do three different things when we need to do one. Why is that? That's because each "if" statement - or function - is considered unique and not related to the others. In the next post we'll re-write the code as one function which will solve this problem.
Challenge: Marte on first, Harrison on third, less than two outs. You're the centerfielder. Depending on where the ball is hit, how hard it is hit, and what the runners do, what are your options? Code it out, take a screen shot and tweet it to me (@randallmardus).
On Deck: Nested ifs!
No comments:
Post a Comment