← Help Code Ninja

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 named length 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 in length.

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 increases length 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.


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.