Skip to main content

← Help Code Ninja

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 = 100 creates a variable named length with 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 length moves the pointer forward by the value stored in length.
  • Older code using $length still 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 + 50 increases length by 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, so var area = length ^ 2 squares 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