TurtleLoading saved progress…

Turtle

Build a Turtle class that tracks a position and a heading as you issue movement and turn commands, the way turtle graphics work in Logo or Python's turtle module. The turtle lives on a 2D plane. You can turn it left or right, send it forward or backward, and ask where it is and which way it's pointing. The whole job is keeping x, y, and the heading consistent as those commands accumulate.

The convention is fixed and you must follow it exactly. The turtle starts at { x: 0, y: 0 } facing east, with heading 0. Angles are in degrees, measured counterclockwise — the standard math convention — so left increases the heading and right decreases it.

Signature

class Turtle {
  // No arguments. Starts at (0, 0) facing east (heading 0).
  constructor();

  forward(distance: number): void;  // move `distance` along the current heading
  backward(distance: number): void; // move `distance` opposite the heading

  left(deg: number): void;          // turn counterclockwise: heading += deg
  right(deg: number): void;         // turn clockwise:        heading -= deg

  position(): { x: number; y: number }; // current location
  heading(): number;                     // current angle, normalized to [0, 360)
}

Internally, a heading of theta degrees means forward(d) adds d * cos(theta) to x and d * sin(theta) to y (with theta first converted to radians). So heading 0 points along +x (east), 90 along +y (north), 180 along -x (west), and 270 along -y (south).

Examples

// Turn north, walk 5: x stays 0, y becomes 5.
const t = new Turtle();
t.left(90);
t.forward(5);
t.position(); // → { x: 0, y: 5 }
t.heading();  // → 90
// A closed square returns to the origin and the original heading.
const t = new Turtle();
for (let i = 0; i < 4; i++) {
  t.forward(10);
  t.left(90);
}
t.position(); // → { x: 0, y: 0 }
t.heading();  // → 0   (four left(90) turns sum to 360, which normalizes to 0)

Notes

  • Heading normalizes to [0, 360). heading() always returns an angle in that half-open range. left(370) reads as 10; right(90) from 0 reads as 270; a negative turn like left(-90) is the same as right(90) and reads as 270.
  • right is the mirror of left. right(deg) is exactly left(-deg) — turning right by 90 is turning left by −90. Implement one in terms of the other if you like, but test both.
  • backward is forward reversed. backward(d) moves the turtle d units opposite its heading and leaves the heading itself unchanged. It is forward(-d).
  • Floats need a little care. cos(90°) is not exactly 0 in floating point — it's about 6e-17. After a 90-degree turn, a naive forward leaves dust like 4.3e-16 in the coordinate that should read 0. Decide how to handle that (the solution snaps near-integers); axis-aligned moves should land cleanly on whole numbers.
  • forward(0) is a no-op. Moving zero distance changes neither position nor heading.
Loading editor…