Math Functions

SeaTurtle is full of numbers. The turtle moves, turns, changes its color, and therefore draws completely based on the integers it is sent from your program. These numbers can be hardcoded when the program is written using literals, or the numbers that the turtle is commanded with can be calculated while the program is running.

Arithmetic in SeaTurtle

Anywhere in SeaTurtle that a number is expected, an arithmetic expression can be supplied instead. SeaTurtle supports all of the arithmetic operators that one learns in grade school. For example the statement FORWARD 75 is the same as the statement FORWARD 50 + 25.

Arithmetic operators in SeaTurtle follow the familiar PEMDAS (parentheses, exponents, multiplication, division, addition, subtraction) rule. For example, the following statement will turn the turtle 128 degrees: RIGHT 2 * (4 + 4) ^ 2. Arithmetic expressions can also include variables. For instance, the following code will move the turtle backward 2 times whatever the variable length has been set to: BACKWARD 2 * length. Here are all of the arithmetic operators in SeaTurtle in order of their precedence:

Symbol Purpose
() Parentheses
^ Exponentiation
* Multiplication
/ Division (same precedence as multiplication)
+ Addition
- Subtraction (same precedence as addition)

Generating Random Numbers

SeaTurtle has a simple mechanism for generating random integers. The RANDOM keyword can be followed by a number to generate a random number between 0 and the number (inclusive). For instance the statement SET x RANDOM 9 will set x to a random number between 0 and 9.

If you want a random number between 1 and some number, just add 1 to the range below it. For instance, to get a random number between 1 and 3 you could write: SET x (RANDOM 2) + 1. Note that the parentheses around (RANDOM 2) are needed to ensure RANDOM 2 is executed first because otherwise the 2 will be immediately added to the 1 leading to the equivalent of RANDOM 3 which will result in a number between 0 and 3.