Code Ninja Tutorial - Variables and Mathematics
Variables in Code Ninja are containers that store values. They can hold numbers and are extremely useful in making your code more flexible and reusable.
Setting and Using Variables
Creating a Variable
- To create a variable, use the
var
command followed by a name and a value. - Example:
var length 100
creates a variable namedlength
with a value of 100.
Using Variables in Commands
- Use a dollar sign
$
before the variable name to use its value. - Example:
fd $length
moves the pointer forward by the value stored inlength
.
Basic Mathematical Operations
Code Ninja supports basic math operations, enabling you to alter variable values.
Math Commands
-
add
,sub
,mul
,div
: Perform addition, subtraction, multiplication, and division. - Example:
var length add $length 50
increaseslength
by 50. Think of this as ‘length = length + 50’.
Using Math in Drawing
- Alter the value of variables to change the dimensions of shapes dynamically.
- Example: Increase the length each time you draw a side.
Exercise: Drawing a Polygon Using Variables and Math
Let’s put variables and math to use by drawing a polygon. We’ll make each side longer than the previous one.
// Set up the variables
var length 30
var angle 50
// Draw the pattern.
repeat 30 {
fd $length
rt $angle
var length add $length 5
}
Your Task
Experiment by changing the length, angle and the amount you add to length each time. You can also change the amount of repetitions to create different shapes.
Wrap-Up
You’ve now learned how to use variables and basic math in Code Ninja. This opens up a world of possibilities, allowing for more complex and interesting designs. As you become more comfortable with these concepts, you’ll find that your Code Ninja creations can become more dynamic and creative.
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 - Basic Concepts and CommandsCode Ninja Tutorial - Colors, Line Width and some Randomness →