What is a function?
In everyday language, the human body possesses functions, for example, the ability to walk. If we say the word « walk » to someone, the person can, through a series of complex imbalances, shift his or her weight from one leg to the other in order to freely move the free foot forward...
So we see that just by saying a single word, an « instruction to act », we can trigger behaviors of varying complexity. The details might escape us and in fact may not interest us in the least, provided that we get the result we’re looking for.
This is the case in programming or coding, where we may know what the tools and functions available to us do, without necessarily knowing the details of how they work.
- In this chapter you will put two functions and their arguments into practice;
- You must use these two functions (their descriptions will be provided below along with instructions for using them) and organize them in such a way as to guide the animal through a maze to its destination;
- If there is an error, you should re-read your program, code, or script and correct it so that everything goes as required.
Your challenge, your task
Help the bear find the honey.
The bear finds itself at the bottom left of a maze that is scattered with obstacles. He is hungry, so you must guide him to the honey feast at the bottom right side of the maze, but make him expend as little energy as possible in doing so.
There are two functions you can use to do this :
- forward (x); where x is an « argument », in this case, a positive integer equal to the number of squares the bear must move ahead;
In the picture below, forward (2); will take the bear to the corner of the path ahead, and forward (3); will make him fall into the ice water, which would not be good for him considering his lack of energy.
- turn ('direction'); lets you turn the bear a quarter turn (90°), either to his left or his right.
Here’s a little trick if you have trouble distinguishing your left from your right: look at which hand you write with and think about whether it’s the left or right. Usually this will keep you from forgetting again :O)
Note: you will observe that the argument is written differently. Here, 'left' or 'right' must be in single or double quotes because it is a character string, not a number as in the previous function.
Using the functions
To « activate » a function, all you need to do is call it, using the following rules of syntax :
- The spaces between single or double quotation marks matter. So you cannot add them to arguments of the character string type;
To make your task easier, you can « copy/paste » from the list of functions found in the exercise you’re working on.