Reference · Karel the Robot

Karel the Robot

This reference details the Java model for Karel used in Stanford's material: the grid world, robot state, commands, sensors, control flow, methods, and ways to plan and test solutions. Other implementations may follow different rules.

Reference Stanford KarelSyntax Java

01 · Overview

About Karel

Karel is a robot that receives instructions to solve simple tasks in a world of streets, corners, and walls. The model was created so early programming exercises emphasize breaking down problems and sequencing commands.

This page follows Stanford's Java reference, which defines a program class and a run method. Other implementations may use Python or their own syntax; do not mix examples from different versions.

02 · Environment

The grid world

Karel's world is a grid of streets and avenues; each intersection is a corner. The robot occupies a corner and faces north, south, east, or west. The world has boundary walls, while its dimensions vary by exercise.

  • Position and direction: the occupied corner and the robot's current orientation.
  • Walls: block movement between corners; sensors check the surroundings relative to the current orientation.
  • Beepers: may be on a corner or in the bag. Karel detects beepers only on its current corner; the standard bag can hold an unlimited number.
  • Initial state and goal: each exercise defines a starting world and the result the program should reach.

Trying to move through a wall, pick up a missing beeper, or place one with an empty bag causes a runtime error.

03 · Organization

Program structure

A Java Karel program declares a class that extends SuperKarel. The public run() method contains the starting instructions; private methods can name reusable command sequences.

import stanford.karel.*;

public class ExampleKarel extends SuperKarel {
    public void run() {
        move();
        turnLeft();
    }
}

Code uses braces for blocks, semicolons after instructions, and Java comments with // or /* ... */.

04 · Actions

Basic commands

CommandAction
move()Moves one corner forward if no wall is ahead.
turnLeft()Turns 90 degrees to the left.
putBeeper()Places a beeper on the current corner and removes one from the bag.
pickBeeper()Picks up a beeper from the current corner and stores it in the bag.

The four primitive instructions use empty parentheses and end with a semicolon. move() fails at a wall; pickBeeper() requires a beeper on the corner; putBeeper() requires one in the bag.

05 · Observation

Sensors and conditions

Karel checks its immediate surroundings; it does not receive the whole map as a value. Each sensor returns a boolean that can be used in if, while, and boolean expressions.

SensorTrue when
frontIsClear() / frontIsBlocked()There is no wall / there is a wall ahead.
leftIsClear() / leftIsBlocked()The path to the left is clear / blocked.
rightIsClear() / rightIsBlocked()The path to the right is clear / blocked.
beepersPresent() / noBeepersPresent()There are / are no beepers on the current corner.
beepersInBag() / noBeepersInBag()The bag contains / does not contain beepers.
facingNorth(), facingEast(), facingSouth(), facingWest()Karel faces the named direction.
notFacingNorth(), notFacingEast(), notFacingSouth(), notFacingWest()Karel faces a different direction.

Wall sensors are relative to Karel's current direction. In Java, negate a condition with ! or combine them with && and ||; use the opposite sensor names when they make the intent clearer.

06 · Flow

Decisions and loops

The Java reference uses if, if/else, while, and for to respond to world conditions and repeat actions.

if (frontIsClear()) {
    move();
} else {
    turnLeft();
}
while (beepersPresent()) {
    pickBeeper();
}
for (int i = 0; i < 3; i++) {
    move();
}

A sensor-based loop must change the world or the robot's position so it can reach its stopping condition. Check the walls and beepers in the scenario before running the sequence.

07 · Reuse

Custom methods

A private method names a compound action. Once declared in the class, it can be called from run() or another method in the same class.

private void turnRightSafely() {
    turnLeft();
    turnLeft();
    turnLeft();
}
public void run() {
    move();
    turnRightSafely();
    move();
}

This method uses three left turns, the primitive turn command in the base reference. When SuperKarel is available, turnRight() expresses the same action directly.

08 · State

State and data

A task can be solved using only position, direction, walls, and beepers, but the Java reference also allows local variables and counters. The robot maintains the world's physical state; program variables can record steps or quantities.

int steps = 0;
while (frontIsClear()) {
    move();
    steps++;
}
putBeeper();

Use extra state when it helps describe the solution. Many beginner tasks can be solved with sensors and well-named methods alone.

09 · Combined example

Move forward and mark the final corner

This program moves until it reaches a wall, then leaves a beeper on the final corner if one is not already there:

import stanford.karel.*;

public class MarkDestination extends SuperKarel {
    public void run() {
        while (frontIsClear()) {
            move();
        }
        if (noBeepersPresent()) {
            putBeeper();
        }
    }
}

10 · Additional features

SuperKarel features

SuperKarel adds features to the base class. They are available when the program class extends SuperKarel.

ElementKindBehavior
turnRight()ActionTurns 90 degrees to the right.
turnAround()ActionTurns 180 degrees.
random(p)ConditionReturns true with probability p, from 0.0 to 1.0.
paintCorner(color)ActionPaints the current corner.

In Stanford's Java materials, colors are constants such as RED and YELLOW, without quotation marks. The original book also documents random(), which returns true half the time, and the cornerColorIs(color) condition. These two features are not listed in the Karel Reader's short reference card; check whether the library in use provides them.

11 · Safe repetition

Loops, boundaries, and off-by-one errors

Use for when the number of steps is known. Use while when the robot must respond to the world, such as moving until a wall. A while condition is checked before its body, which may run zero times.

while (frontIsClear()) {
    if (noBeepersPresent() && beepersInBag()) {
        putBeeper();
    }
    move();
}
if (noBeepersPresent() && beepersInBag()) {
    putBeeper();
}

The check inside the loop covers each corner before moving; the final check covers the corner where Karel stops. Confusing the number of corners with the number of moves causes a common off-by-one error.

Every loop needs a reachable stopping condition. In a sensor loop, each iteration must change position, direction, or beepers so the condition can change.

12 · Planning

Decomposition and contracts

Before writing commands, describe the initial state and the expected result: where Karel starts, which way it faces, which walls exist, and how many beepers are available. Split the solution into named actions that express an intention.

A private method without parameters works like a new instruction. For each method, consider its precondition — what must be true before the call — and postcondition — what it guarantees when it returns. One method's result must satisfy what the next method expects.

private void moveToWall() {
    while (frontIsClear()) {
        move();
    }
}

public void run() {
    moveToWall();
    turnAround();
}

This method leaves Karel at the farthest corner ahead, still facing the wall. Stating that result makes the sequence easier to reuse and review.

13 · Verification

Test more than one world

A correct solution must respect the world state, not only work in the scenario used while writing it. Vary grid size, wall positions, starting direction, and beeper placement.

  • Test a minimal grid and a corridor with only one move available.
  • Test a wall directly ahead at the start.
  • Test corners with and without beepers, and an empty bag when the task allows it.
  • Check final position, direction, walls, and beeper count.

Trying to cross a wall, pick up a missing beeper, or place one with an empty bag causes an error in that world. Use sensors to guard actions that depend on these conditions.

14 · Further reading

References

Return to the Potoo IDE Manual

Explore the other references and project information.

Open the Manual