# &turtlescript; Programming Reference

This is the reference for &kturtle;'s &turtlescript;. In the first section of this chapter have a look at some aspects of the grammar of &turtlescript; programs. The second section deals exclusively with mathematical operators, boolean (true/false) operators and comparison operators. The third section is basically a giant list of all commands explaining them one-by-one. Section four explains how to assign values to variables. Finally we explain how to arrange the execution of commands with execution controlling statements in section five and how to create you own commands with learn in section six.

## The Grammar of &turtlescript;

As in any language, &turtlescript; has different types of words and symbols. In English we distinguish verbs (like 'to walk' or 'to sing') and nouns (like 'sister' or 'house'), they are used for different purposes. &turtlescript; is a programming language, it is used to instruct &kturtle; what to do.

In this section some of &turtlescript;'s different types of words and symbols are briefly explained. We explain comments, commands and the three different kinds of literals: numbers, strings and boolean (true/false) values.

### Comentarios

A program consists instructions that are executed when the program is run and so called comments. Comments are not executed, &kturtle; simply ignores them when executing your program. Comment are there for other programmers to make them understand your program better. Everything that follows on a `#` symbol is considered a comment in &turtlescript;. For example this little program that does nothing:

    # this little program does nothing, it is only a comment!

It is a bit useless but it explain the matter well.

Comments get very useful when the program gets a little bit more complex. It can help to give some advice to other programmers. In the following program you see comments being used together with the print command.

    # this program has been made by Cies Breijs.
    print "this text will get printed on the canvas"
    # the previous line is not a comment, but the next line is:
    # print "this text will not get printed!"

The first line describes the program. The second line is executed by &kturtle; and prints `this text will get printed on the canvas` on the canvas. The third line is a comment. And the forth line is a comment that contains a piece of &turtlescript;, if the `#` symbol would be removed on the fourth line the print statement will we executed by &kturtle;. Programmers say: the print statement on the fourth line is 'commented out'.

Commented lines are highlighted with light gray in the code editor.

### Comandos

Using commands you tell the turtle or &kturtle; to do something. Some commands need input, some give output.

    # forward is a command that needs input, in this case the number 100:
    forward 100

The first line is a comment. The second line contains the `forward` command and the number `100`. The number is not part of command, it is considered 'input' for the command.

For a detailed overview of all commands that &kturtle; supports go here. Built-in commands are highlighted in dark blue

### Números

Posibelmente xa saiba bastante acerca dos números. A maneira de utilizar os números en &kturtle; non é moi diferente da oral, nen da matemática.

We have the so called natural numbers: `0`, `1`, `2`, `3`, `4`, `5`, etc. The negative numbers: `-1`, `-2`, `-3`, etc. And the numbers with decimals, or dot-numbers, for example: `0.1`, `3.14`, `33.3333`, `-5.05`, `-1.0`.

Numbers can be used in mathematical operators and comparison operators. They can also be stored in variables. Numbers are highlighted in dark red.

### Textos

Primeiro un exemplo:

    escrebe "Olá, son un texto."

Neste exemplo `escrebe` é un comando no que `"Olá, son un texto."` é un texto. Os textos comezan e rematan con aspas, `"`, mediante as cais &kturtle; sabe que é un texto.

Strings can be put in variables, just like numbers. Yet, unlike numbers, strings cannot be used in mathematical operators or comparison operators. Strings are highlighted with red.

### Boolean (true/false) values

There are only two boolean values: `true` and `false`. Sometimes they are also called: on and off, yes and no, one and zero. But in &turtlescript; we call them, always, `true` and `false`. Have a look at this piece of &turtlescript;:

    $a = true

If you look in the inspector you can see that the variable `$a` is set to `true`, and has the boolean type.

Often boolean values are the result of a comparison operator, like in the following piece of &turtlescript;:

    $answer = 10 > 3

The variable `$answer` is set to `true` because `10` is larger than `3`.

Boolean values, `true` and `false`, are highlighted with dark red.

## Mathematical, boolean and comparing operators

The title of this section might sound very difficult, yet it is not as difficult as it sound.

### Mathematical operators

These are the basic math symbols known as: add (`+`), subtract (`-`), multiply (`*`), divide (`/`) and power (`^`).

Here a small example of the mathematical operators you can use in &turtlescript;:

    $add      = 1 + 1
    $subtract = 20 - 5
    $multiply = 15 * 2
    $divide   = 30 / 30
    $power    = 2 ^ 2

The values resulting from the mathematical operations get assigned to various variables. Using the inspector you can see the values.

Se só quer facer un cálculo simples pode facer algo como isto:

    print 2010-12

Now an example with parentheses:

    print ( ( 20 - 5 ) * 2 / 30 ) + 1

The expressions inside parentheses will be calculated first. In this example, 20-5 will be calculated, then multiplied by 2, divided by 30, and then 1 is added (giving 2). Parentheses can also be used in other cases.

&kturtle; also has more advanced mathematical features in the form of commands. Have a look at the following commands but be aware that it concerns advanced operations: round, random, sqrt , pi, sin, cos, tan, arcsin, arccos, arctan.

### Boolean (true/false) operators

Where mathematical operators are mainly for numbers, boolean operators are for boolean values (`true` and `false`). There are only three boolean operators, namely: `and`, `or`, and `not`. The following piece of &turtlescript; shows how to use them:

    $and_1_1 = true and true    # -> true
    $and_1_0 = true and false   # -> false
    $and_0_1 = false and true   # -> false
    $and_0_0 = false and false  # -> false

    $or_1_1 = true or true    # -> true
    $or_1_0 = true or false   # -> true
    $or_0_1 = false or true   # -> true
    $or_0_0 = false or false  # -> false

    $not_1 = not true   # -> false
    $not_0 = not false  # -> true

Using the inspector you can see the values, yet we also supply these results as little comments at the end of the lines. `and` evaluates `true` only if both sides are `true`. `or` evaluates `true` if either side is `true`. And `not` turns a `true` into `false` and a `false` into `true`.

Boolean operators are highlighted with pink.

#### Some more advanced examples

Consider the following example with `and`:

    $a = 1
    $b = 5
    if (($a < 10) and ($b == 5)) and ($a < $b) {
      print "hello"
    }

In this piece of &turtlescript; the result of three comparing operators are merged using `and` operators. This means that all three have to evaluate "true" in order for the "hello" to be printed.

An example with `or`:

    $n = 1
    if ($n < 10) or ($n == 2) {
      print "hello"
    }

In this piece of &turtlescript; the left side of the `or` is evaluating to 'true', the right side to 'false'. Since one of the two sides of the `or` operator is 'true', the `or` operator evaluates 'true'. That means "hello" gets printed.

And finally an example with `not` which changes 'true' into 'false' and 'false' into 'true'. Have a look:

    $n = 1
    if not ($n == 3) {
      print "hello"
    } else {
      print "not hello ;-)"
    }

### Comparing operators

Consider this simple comparison:

    $answer = 10 > 3

Here `10` is compared to `3` with the 'greater than' operator. The result of this comparison, the boolean value `true` is stored in the variable `$answer`.

All numbers and variables (that contain numbers) can be compared to each other with comparing operators.

Here are all possible comparing operators:

### Types of questions

`$A == $B` | equals | answer is true if `$A` equals `$B`
`$A != $B` | not-equals | answer is true if `$A` does not equal `$B`
`$A > $B` | greater than | answer is true if `$A` is greater than `$B`
`$A < $B` | smaller than | answer is true if `$A` is smaller than `$B`
`$A >= $B` | greater than or equals | answer is true if `$A` is greater than or equals `$B`
`$A <= $B` | smaller than or equals | answer is true if `$A` is smaller than or equals `$B`

Please note that $A and $B have to be numbers or variables that contain numbers.

## Comandos

Using commands you tell the turtle or &kturtle; to do something. Some commands need input, some give output. In this section we explain all the built-in commands of &kturtle;. Alternatively, using learn, you can create your own commands. Built-in commands we discuss here are highlighted with dark blue.

### Mover o sapoconcho

Hai varios comandos que moven o sapoconcho pola pantalla.

avanza (av)

-     avanza X

  `avanza` move o sapoconcho cara diante X píxeles. Cando o lápis está pousado deixará un rastro. `avanza` pode abreviarse como `av`

recua (re)

-     recua X

  `recua` move o sapoconcho cara atrás X píxeles. Se o lápis está pousado deixará un rastro. `recua` pode ser abreviado como `re`.

xiraesquerda (xe)

-     xiraesquerda X

  `xiraesquerda` ordénalle ao sapoconcho que xire X graus á esquerda. `xiraesquerda` pode abreviarse como `xe`.

xiradereita (xd)

-     xiradereita X

  `xiradereita` ordénalle ao sapoconcho que xire X graus á dereita. `xiradereita` pode abreviarse como `xd`.

direccion (dir)

-     direccion X

  `direccion` fai que o sapoconcho tome unha ruta a X graus do cero, polo que non é relativa á anterior ruta que seguise o sapoconcho. `direccion` pode abreviarse como `dir`.

vaiaocentro

-     vaiaocentro

  `vaiaocentro` leva o sapoconcho ao centro do lenzo.

vai

-     vai X,Y

  `go` commands the turtle to go to a certain place on the canvas. This place is X pixels from the left of the canvas, and Y pixels form the top of the canvas.

vaix

-     vaix X

  `vaix` fai que o sapoconcho vaia a unha posición situada a X píxeles do borde esquerdo do lenzo sen desprazarse en altura.

vaiy

-     vaiy Y

  `gox` using this command the turtle will move to Y pixels from the top of the canvas whilst staying at the same distance from the left border of the canvas.

Cando se utilizan os comandos `vai`, `vaix`, `vaiy` e `vaiaocentro` o sapoconcho non debuxa a liña, con independencia de que o lápis estexa erguido ou pousado.

### Onde está o sapoconcho?

Hai dous comandos que din a posición do sapoconcho na pantalla.

coordenadaX

- `coordenadaX` devolve a cantidade de píxeles que hai desde a esquerda do lenzo até a posición do sapoconcho.

coordenadaY

- `coordenadaY` devolve a cantidade de píxeles que hai do cume do lenzo até a posición do sapoconcho.

### O sapoconcho ten un lápis

O sapoconcho ten un lápis que debuxa unha liña á medida que se move o animal. Hai uns poucos comandos que controlan este lápis. Nesta sección explicarémolos.

subelapis (sl)

-     subelapis

  `subelapis` separa o lápis do lenzo. Cando o lápis está subido non se debuxan liñas ao moverse o sapoconcho. Consulte tamén `baixalapis`. `subeLapis` pode abreviarse como `sl`.

baixalapis (bl)

-     baixalapis

  `baixalapis` pousa o lápis no lenzo. Cando o lápis está baixado debúxanse liñas cando se move o sapoconcho. Consulte tamén `subelapis`. `baixalapis` pode abreviarse como `bl`.

ancholapis (al)

-     ancholapis X

  `ancholapis` estabelece o grosor do trazo co valor de X píxeles. `ancholapis` pode abreviarse como `al`.

corlapis (cl)

-     corlapis R,G,B

  `corlapis` estabelece a cor do trazo. `corlapis` toma como parámetro unha combinación RGB. `corlapis` code abreviarse como `cl`.

### Comandos para controlar o lenzo

Hai varios comandos que controlan o lenzo.

tamañolenzo (tlz)

-     tamañolenzo X,Y

  Mediante o comando `tamañolenzo` pode axustar o tamaño da área. Toma X e Y como entradas, onde X é o novo ancho do lenzo en píxeles e Y é o novo alto en píxeles. `tamañolenzo` pode abreviarse como `tlz`.

corlenzo (clz)

-     corlenzo R,G,B

  `corlenzo` estabelece a cor do lenzo. `corlenzo` toma unha combinación RGB como entrada. `corlenzo` pode abreviarse como `clz`.

### Comandos para borrar

Hai dous comandos para limpar o lenzo cando o emborrona.

borra (br)

-     borra

  Con `borra` pode borrar do lenzo todos os debuxos. As demais cousas fican: a posición e ángulo do sapoconcho, a cor do lenzo, a visibilidade do sapoconcho e o tamaño do lenzo.

reinicia

-     reinicia

  `reinicia` limpa máis a fondo do que o fai o comando `borra`. Despois de executar un comando `reinicia` todo volta a ser como cando iniciou &kturtle;. O sapoconcho estará posto no centro da pantalla, a cor do lenzo será branco, debuxarase cun trazo negro e o tamaño do lenzo será de 400 x 400 píxeles.

### O sapoconcho é un sprite

Os sprites son pequenas imaxes que se poden mover pola pantalla, como se ve nos xogos de consola. O noso animaliño tamén é un sprite. Para saber máis acerca disto, consulte a entrada sprites no glosario.

A seguir ten un resumo completo de todos os comandos que traballan sobre sprites.

[A versión actual de &kturtle; aínda non permite utilizar outros sprites que non sexan o sapoconcho. En versións futuras poderá mudar para outro deseño á súa escolla]

mostrasapoconcho (msc)

-     mostrasapoconcho

  `mostrasapoconcho` fai de novo visíbel ao sapoconcho se antes foi agochado. `mostrasapoconcho` pode abreviarse como `msc`.

agochasapoconcho (asc)

-     agochasapoconcho

  `agochasapoconcho` fai invisíbel ao sapoconcho. Isto pode empregarse se o animal non couber no debuxo. `agochasapoconcho` pode abreviarse como `asc`.

### Pode escreber o sapoconcho?

A resposta é: pode. A tartaruga pode escreber, e escreberá calquera cousa que lle mande.

escrebe

-     escrebe X

  O comando `escrebe` ordénalle ao sapoconcho que escreba algo no lenzo. `escrebe` pode tomar textos e números como parámetros. Pode `escrebe`r varios números e cadeas mediante o símbolo +. Aquí vai un exemplo:

      $ano = 2009
      $autor = "Bruno"
      escrebe $autor + " debuxou unha nora en KTurtle no ano" + $ano + " e gustoulle moito!"

letratamaño

-     letratamaño X

  `letratamaño` modifica o tamaño de letra utilizado ao `escreber`. `letratamaño` toma un argumento numérico. O tamaño indícase en píxeles.

### Mathematical commands

The following commands are &kturtle;'s more advanced mathematical commands.

redondea

-     redondea (x)

  `round` the given number to the nearest integer.

      print round(10.8)
      forward 20
      print round(10.3)

  With this code the turtle will print the numbers 11 and 10.

aleatorio (alea)

-     aleatorio X,Y

  `aleatorio` é un comando que toma unha entrada e saca un resultado. Como entrada precisa de dous números, o primeiro (X) é o resultado mínimo, o segundo (Y) o máximo. A saída é un número escollido ao chou que é como mínimo o menor e como máximo o maior. Aquí vai un exemplo:

      repite 500 {
        $x = aleatorio 1,20
        avanza $x
        xiraesquerda 10 - $x
      }

  Mediante o comando `aleatorio` pode introducir algo de caos no programa.

sqrt

-     sqrt X

  The `sqrt` command is sued to find the square root of a number, X.

pi

-     pi

  This command returns the constant Pi, `3.14159`.

sin
, cos
, tan

-     sin X
      cos X
      tan X

  These three commands represent the world famous trigoniometrical functions `sin`, `cos` and `tan`. The input argument of these commands, X, is a number.

arcsin
, arccos
, arctan

-     arcsin X
      arccos X
      arctan X

  These commands are the inverse functions of sin, cos and tan. The input argument of these commands, X, is a number.

### Introdución de datos e obtención de resultados mediante diálogos

Un diálogo é unha pequena fiestra emerxente que lle dá algo de información ou que lle pide algún dato. &kturtle; ten dous comandos para diálogos, que son: `mostra` e `pergunta`

mostra

-     mostra X

  O comando `mostra` toma un texto como entrada, e mostra un diálogo que contén o texto.

      message "Cies started KTurtle in 2003 and still enjoys working on it!"

pergunta

-     pergunta X

  `ask` takes a string as input. It shows this string in a pop-up dialog (similar to message), along with an input field. After the user has entered a number or a string into this, the result can be stored in a variable or passed as an argument to a command. For example:

      $in = ask "What is your year of birth?"
      $out = 2003 - $in
      print "In 2003 you were " + $out + " years old at some point."

  If the user cancels the input dialog, or does not enter anything at all, the variable is empty.

## Assignment of variables

First we have a look at variables, then we look at assigning values to those variables.

Variables are words that start with a $, in the editor they are highlighted with purple.

Variables can contain any number, string or boolean (true/false) value. Using the assignment, `=`, a variable is given its content. It will keep that content until the program finishes executing or until the variable is reassigned to something else.

You can use variables, once assigned, just as if they are their content. For instance in the following piece of &turtlescript;:

    $x = 10
    $x = $x / 3
    print $x

First the variable `$x` is assigned to `10`. Then `$x` is reassigned to itself divided by `3` — this effectively means `$x` is reassigned to product of `10 / 3`. Finally `$x` is printed. In line two and three you see that `$x` is used as if it is its contents.

Variables have to be assigned in order to be used. For example:

    print $n

Will result in an error message.

Please consider the following piece of &turtlescript;:

    $a = 2004
    $b = 25

    # the next command prints "2029"
    print $a + $b
    backward 30
    # the next command prints "2004 plus 25 equals 2029"
    print $a + " plus " + $b + " equals " + ($a + $b)

In the first two lines the variables `$a` and `$b` are set to 2004 and 25. Then in two `print` commands with a `backward 30` in between are executed. The comments before the `print` commands explain what they are doing. The command `backward 30` is there to make sure every output is on a new line. As you see variables can be used just as if their where what they contain, you can use them with any kind of operators or give them as input when invoking commands.

One more example:

    $name = ask "What is your name?"
    print "Hi " + $name + "! Good luck while learning the art of programming..."

Pretty straight forward. Again you can see that the variable `$name`, treated just like a string.

When using variables the inspector is very helpful. It shows you the contents of all variables that are currently in use.

## Control da execución

Os controladores da execución permítenlle, como indica o nome, controlar o fluxo de execución.

Execution controlling commands are highlighted with dark green in a bold font type. The brackets are mostly used together with execution controllers and they are highlighted with black.

### Facer que o sapoconcho agarde

Se programou algo en &kturtle; xa se terá decatado de que o sapoconcho pode ser moi moi moi rápido cando debuxa. Este comando fai que agarde durante un tempo.

agarda

-     agarda X

  `agarda` fai que o sapoconcho estexa quedo durante X segundos.

      repite 36 {
        avanza 5
        xiradereita 10
        agarda 0.5
      }

  Este código debuxa un círculo, pero o animal agardará medio segundo tras cada paso. Isto dá a impresión dun sapoconcho lento.

### Executar "se"

se

-     if boolean { ... }

  The code that is placed between the brackets will only be executed `if` the boolean value evaluates true.

      $x = 6
      if $x > 5 {
        print "$x is greater than five!"
      }

  On the first line `$x` is set to 6. On the second line a comparing operator is used to evaluate `$x > 5`. Since this evaluates true, 6 is larger than 5, the execution controller `if` will allow the code between the brackets to be executed.

### Se non, o caso contrario: "noutrocaso"

noutrocaso

-     if boolean { ... } else { ... }

  `else` can be used in addition to the execution controller `if`. The code between the brackets after `else` is only executed if the boolean evaluates false.

      reset
      $x = 4
      if $x > 5 {
        print "$x is greater than five!"
      } else {
        print "$x is smaller than six!"
      }

  The comparing operator evaluates the expression `$x > 5`. Since 4 is not greater than 5 the expression evaluates false. This means the code between the brackets after `else` gets executed.

### O ciclo "mentres"

mentres

-     while boolean { ... }

  The execution controller `while` is a lot like `if`. The difference is that `while` keeps repeating (looping) the code between the brackets until the boolean evaluates false.

      $x = 1
      while $x < 5 {
        forward 10
        wait 1
        $x = $x + 1
      }

  On the first line `$x` is set to 1. On the second line `$x < 5` is evaluated. Since the answer to this question is true the execution controller `while` starts executing the code between the brackets until the `$x < 5` evaluates false. In this case the code between the brackets will be executed 4 times, because every time the fifth line is executed `$x` increases by 1.

### O ciclo "repite"

repite

-     repeat number { ... }

  The execution controller `repeat` is a lot like `while`. The difference is that `repeat` keeps repeating (looping) the code between the brackets for as many times as the given number.

### O ciclo "desde", un ciclo cun contador

desde

-     for variable = number to number { ... }

  The `for` loop is a counting loop, &ie; it keeps count for you. The first number sets the variable to the value in the first loop. Every loop the number is increased until the second number is reached.

      for $x = 1 to 10 {
        print $x * 7
        forward 15
      }

  Every time the code between the brackets is executed the `$x` is increased by 1, until `$x` reaches the value of 10. The code between the brackets prints the `$x` multiplied by 7. After this program finishes its execution you will see the times table of 7 on the canvas.

  O paso por omisión no bucle é 1, pero pode utilizar outro valor mediante

      for variable = number to number step number { ... }

### Sair dun bucle

sair

-     sair

  Terminates the current loop immediately and transfers control to the statement immediately following that loop.

### Stop executing your program

fin

-     fin

  Finishes the execution of your program.

## Cree os seus proprios comandos con define

`learn` is special as it is used to create your own commands. The commands you create can take input and return output. Let us take a look at how a new command is created:

    learn circle $x {
      repeat 36 {
        forward $x
        turnleft 10
      }
    }

The new command is called `circle`. `circle` takes one input argument, to set the size of the circle. `circle` returns no output. The `circle` command can now be used like a normal command in the rest of the code. See this example:

    define faiCirculo $X {
      repite 36 {
        avanza $X
        xiraesquerda 10
      }
    }
    vai 200,200
    faiCirculo 20

    vai 300,300
    faiCirculo 40

In the next example, a command with a return value is created.

    learn faculty $x {
      $r = 1
      for $i = 1 to $x {
        $r = $r * $i
      }
      return $r
    }

    print faculty 5

In this example a new command called `faculty` is created. If the input of this command is `5` then the output is `5*4*3*2*1`. By using `return` the output value is specified and the execution is returned.

Commands can have more than one input. In the next example, a command that draws a rectangle is created:

    learn box $x, $y {
      forward $y
      turnright 90
      forward $x
      turnright 90
      forward $y
      turnright 90
      forward $x
      turnright 90
    }

Now you can run `box 50, 100` and the turtle will draw a rectangle on the canvas.