Code Ninja Tutorial - Variables and Mathematics
Variables in Code Ninja are containers that store values. They are especially useful for numbers and make your code easier to change and reuse.
Setting and Using Variables
Creating a Variable
- To create a variable, use
var, then the name, then=, then the value. - Example:
var length = 100creates a variable namedlengthwith a value of 100. - Once a variable exists you can change it with
length = 150.
Using Variables in Commands
- You can use the variable name directly in commands.
- Example:
fd lengthmoves the pointer forward by the value stored inlength. - Older code using
$lengthstill works too.
Basic Mathematical Operations
Code Ninja supports normal maths operations, so you can alter variable values in a way that feels a bit more natural.
Maths
- Use
+,-,*,/,^and brackets. - Example:
length = length + 50increaseslengthby 50. - If you want to use a more complicated bit of maths inside a command then wrap it in brackets, like
fd (length * 2). - You can use
^for powers, sovar area = length ^ 2squares the value.
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
var growBy = 5
// Draw the pattern.
repeat 30 {
fd length
rt angle
length = length + growBy
}
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. If you want to push it further try using ^ or brackets in your maths, such as length = (length + 2) ^ 1.
Wrap-Up
You’ve now learned how to use variables and maths in Code Ninja. This makes it much easier to build patterns that grow, shrink, rotate, or react to each loop in a more interesting way.
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
- 7: Debugging Your Code
← Code Ninja Tutorial - Basic Concepts and CommandsCode Ninja Tutorial - Colors, Line Width and some Randomness →