Lets put together some of the things youve learned so far. In this task the frog must catch the fly, which it does by being in the same square as the fly at the same time. As the fly is moving around randomly, the frog will have to move around to catch up with it. Because the fly can move in different directions, we will have to make decisions on which is the best direction for the frog to move in, and because we will have to move over and over again, we will have to loop. We will make use of the following instructions:
| isFlyUp() | Evaluates to true if the fly is further up the screen than the frog |
| isFlyDown() | Evaluates to true if the fly is further down the screen than the frog |
| isFlyLeft() | Evaluates to true if the fly is further left than the frog |
| isFlyRight() | Evaluates to true if the fly is further right than the frog |
| isFlyCaught() | Evaluates to true if the fly has been caught |
You may already be thinking of what the program will look like. Go ahead and start programming at any time if you like.
If the fly is further up the screen than the frog, we can edge a step closer to it with the instruction frogUp(1); We could use a larger number than 1 but we risk shooting straight past it, and this way well catch it eventually. That part of the program will look like this:
if( isFlyUp() ) frogUp(1);
You can use four if statements, one for each direction. Alternativly you could use two groups of if/else statements. Either way, well have to perform those statements many times over, so those statements need to be inside a loop. To end the loop, we can use the statement isFlyCaught(). However, we want to loop while the fly is not caught, so we will have to take the opposite:
while( ! isFlyCaught() )
Write a program that causes the frog to catch the fly