previous post
We're going to play "Get Gold" game. This is a game of finding gold which is represented by value 1 in 1 or 2 array dimension. In this chapter we'll focus on the simplest game play, where there are only three blocks in array. The character should find gold in this area.
There you can see, the dog-like picture is our avatar. He should find the gold, which is represented by yellow rock. We can only move forward and backward.
Why using recursive?
In this example, it's not really the best solution if we use recursive. We can just iterate the array from 0 to 2 and check whether there is gold or not. But, if we want to make it as animation, where the dog moves to next block one by one from the starting point to the gold position and from the gold position to the starting position. (or it will go to the right most block if there is no gold). In this case we'll find that using recursive is a bit helpful. We don't need to write line to make the dog walk to the starting position. Be thankful, we've got the RETURN statement. I know, it's not a big thing. We'll see another advantages in the next chapters.
What is happening if the dog tries to find the gold?
- If the dog has gold and is in the starting position, (to step 6)
- If the dog hasn't got the gold, he checks, whether on his block position the gold exists, (to step 3). Else (to step 4)
- If the dog find the gold, he will bring the gold (to step 4) Else (to step 5)
- He will move to the left (to step 1)
- The dog will move one step to the right. (to step 1)
- Finish
That is what happening. If you don't get it, see this picture.
Now we'll make the code.
- The blocks can be made from an array. The gold can be represented by 1 and empty block with 0.
- The recursive function is very simple. We need one parameter to keep the position of the dog. Let's call it j.
- Inside the recursive function we'll check whether the position is still in the size of array or not. Since the size is 3, we'll make it j < 3
- Then we will check if there is gold or not. Just check the value, if it is 1 then there is gold, if it is 0 then there isn't
- If the dog find gold, just do return.
- The initial calling of the method is done in the main function. Just start at position j = 0, by calling find_1(0)
If you've tried it, you'll only get output "Got Gold"
So, where is the process?
Try this one. You can see the process by printing the array value and giving delay in your program.
Source Code 2
I added two functions. The first one, delay, is used to delay the process in the program so that our eyes can catch up the speed. The other one is the view function, which shows the position.
There you've finished making an animation using recursive. This is the simplest one. If you have any questions or advice please comment.
See you at the next part.