Skip to curriculum
Jump to the editor

23.8. Interpret turtle drawing commands

Medium
Topics
15–30 min

Turtle graphics is the smallest real programming language you can build: a "turtle" sits on a page, holding a pen, and obeys commands such as forward 10 and right 90. repeat 4 [ forward 10 right 90 ] draws a square. Writing an interpreter for it teaches the same steps as any language tool, from a formula field to a template engine: split the text into tokens, parse the tokens into a tree, and run the tree against some state.

Write runTurtle(program, options) in turtle.js. It returns the lines the turtle drew and where it ended.

Signature

JAVASCRIPT
function runTurtle(program, options) // returns { x, y, heading, penDown, lines }
  • program: the program text.
  • options.maxSteps: the most steps the program may take (default 100000). options may be left out.
  • Returns { x, y, heading, penDown, lines }, where each line is { x1, y1, x2, y2 }, in drawing order.
CommandShort formWhat it does
forward nfd nmove n along the heading
back nbk nmove n the other way (the heading does not change)
right drt dturn d degrees clockwise
left dlt dturn d degrees counter-clockwise
penuppustop drawing
pendownpdstart drawing
repeat k [ … ]run the commands in brackets k times

Requirements

  1. The turtle starts at (0, 0) with heading 0 (north, toward positive y) and the pen down. Moving n changes x by n * sin(heading) and y by n * cos(heading).
  2. A move records a line when the pen is down and the distance is not 0.
  3. The heading is always reported between 0 (included) and 360 (excluded).
  4. Every returned number (position, heading, line ends) is rounded to 6 decimals and is never -0. Rounding is for the output only: the turtle keeps exact values while it runs.
  5. Words are separated by any whitespace; brackets need no spaces around them; letter case does not matter; # starts a comment to the end of the line. A number has an optional -, digits and an optional decimal part (10, -5, .5, 1.25).
  6. Repeats nest to any depth. repeat 0 runs nothing.
  7. The whole program is parsed before anything runs. A SyntaxError is thrown for an unknown command, a missing or non-numeric argument, a repeat without [, a [ that is never closed, and a ] that closes nothing. A RangeError is thrown, while parsing, for a repeat count that is not a whole number of 0 or more.
  8. Each command run counts as one step, and so does each round of a repeat. Going past maxSteps throws a RangeError, even when the repeat's body is empty.
  9. Each call starts from a fresh turtle.

Examples

JAVASCRIPT
runTurtle("repeat 3 [ fd 10 rt 120 ]");
// { x: 0, y: 0, heading: 0, penDown: true, lines: [
//   { x1: 0, y1: 0, x2: 0, y2: 10 },
//   { x1: 0, y1: 10, x2: 8.660254, y2: 5 },
//   { x1: 8.660254, y1: 5, x2: 0, y2: 0 },
// ] }
JAVASCRIPT
runTurtle("pu fd 10 pd fd 5").lines;
// [{ x1: 0, y1: 10, x2: 0, y2: 15 }]

runTurtle("lt 90").heading;
// 270
JAVASCRIPT
runTurtle("repeat 2 [ fd 1");                    // throws SyntaxError
runTurtle("repeat 2 [ fd 1 ]", { maxSteps: 3 }); // throws RangeError: 2 rounds + 2 moves = 4 steps

Environment

  • Plain JavaScript in a browser page; the tests call the global runTurtle from turtle.js.
  • Procedures, variables, colours and drawing on a canvas are not part of this problem.
  • Any built-in is allowed. eval and new Function are blocked in the page.

Hints

  1. A repeat holds a list of commands, which can hold a repeat. What shape of data, and what kind of function, fits that?
  2. JavaScript's % keeps the sign: -90 % 360 is -90. How do you get 270?
  3. If only commands count as steps, how long does repeat 1000000000 [ ] run?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…