Code Ninja Tutorial - Custom Functions
Custom functions in Code Ninja allow you to create reusable blocks of code. This makes your coding more efficient and your programs easier to read and maintain.
Functions can contain any number of commands including loops, and variables. Keep in mind that functions are not executed until you call them in your code. All variables are global, so if you set them in your function they will be available outside of the function, and changing values will affect the global value.
How to Create a Custom Function
- Use the
function
keyword followed by the function name and curly braces{}
. - Inside the braces, include the commands that make up the function.
function drawLine {
fd 100
bk 100
}
This function, named drawLine
, moves the pointer forward and backward by 100 units.
Using Your Custom Function
- To use your function, simply type its name followed by
()
. - Example:
drawLine()
will execute thedrawLine
function.
Exercise: Building a Function to Draw a House
Now, letβs create a function to draw a simple house.
function drawHouse {
// Draw the square base of the house
color white
repeat 4 {
rt 90
fd 100
}
// Draw the roof
color red
rt 45
fd 70
rt 90
fd 70
rt 45
}
drawHouse()
This function draws a square and a triangular roof to form a house.
You can now add the following code along with some random numbers, and the pen up and pen down commands, to create a small village of houses.
If you add the following code to the editor (along with the drawHouse function above), you will draw 10 houses.
repeat 10 {
pu
setxy rand 512 rand 512
pd
drawHouse()
}
You may notice that some of these houses are upside down. Why is this? The answer is that the drawHouse
function changes the direction of the pointer. To fix this, you can add a rt 180
command at the end of the drawHouse
function to turn the pointer around and make it face the same direction as when it started.
The final code will look like this:
function drawHouse {
// Draw the square base of the house
color white
repeat 4 {
rt 90
fd 100
}
// Draw the roof
color red
rt 45
fd 70
rt 90
fd 70
rt 45
// Reset the cursor
rt 180
}
repeat 10 {
pu
setxy rand 512 rand 512
pd
drawHouse()
}
Creating a Tree Function (Optional Challenge)
For a more advanced challenge, try creating a function to draw a tree. Think about the shapes that make up a tree (like rectangles for the trunk and triangles for leaves) and how you can use repeat loops and colors for added detail.
Wrap-Up
Custom functions are a game-changer in your Code Ninja toolkit. They help you avoid repetition and make complex drawings more manageable. By mastering functions, youβre well on your way to becoming a proficient Code Ninja coder.
Tutorials
- 1: Getting Started
- 2: Basic Concepts and Commands
- 3: Variables and Mathematics
- 4: Colors, Width and some Randomness
- 5: Loops and Patterns
- 6: Custom Functions
β Code Ninja Tutorial - Loops and PatternsComic Maker Help β