JavaScratch Sprite API

JavaScratch

Sprite API Reference

Every method you can call from a sprite's Java code,
grouped like Scratch's block categories, with an example for each.

Version 1.0 · 124 methods and concepts

JavaScratch Sprite API

How sprite code works

In JavaScratch every sprite (and the stage) is programmed in Java instead of blocks. The code you type in the Scripts tab is the inside of a Java class that extends SpriteScript, so you write fields (variables) and methods. You can call every method in this reference directly — no this. or object needed.

Event methods are the hat blocks. A method called whenFlagClicked() runs when the green flag is clicked, whenKeyPressed(String key) when a key is pressed, and so on. Every event method runs in its own thread, at the same time as the others — exactly like separate scripts in Scratch.

int score = 0;                       // a field: a variable for this sprite only

public void whenFlagClicked() {      // when green flag clicked
    goTo(0, 0);
    say("Hello!", 2);
    forever(() -> {                  // forever (one repetition per frame)
        move(5);
        ifOnEdgeBounce();
    });
}

public void whenClicked() {          // when this sprite clicked
    score++;
    playSound("pop");
}

Loops and frames

forever, repeat and repeatUntil wait one frame (1/30 second) after each repetition, so you can see the animation. In your own Java while / for loops, call nextFrame(). Inside the () -> { } lambdas you can change fields but not local variables, so keep counters and scores in fields.

Coordinates and directions

x: -240x: 240 y: 180y: -180(0, 0) 90 0 -90 180

The stage is 480 × 360 pixels. x goes from -240 (left) to 240 (right) and y from -180 (bottom) to 180 (top); (0, 0) is the centre. Direction 90 points right, 0 up, -90 left and 180 down.

Reading this reference

  • Each method shows its Java signature, whether it works for Sprites only or Sprites & Stage, the matching Scratch block, its parameters and an example.
  • Every example is complete sprite code: paste it into a sprite's Scripts tab and click the green flag.
  • Examples use the names of the built-in sprites (Bean, Ball, Apple, Star…), sounds (“pop”) and backdrops (“blue sky”, “night”) — rename them to match your project.
  • Costume, backdrop and letter numbers start at 1, like in Scratch.

Categories

Motion

Move and turn the sprite. The stage is 480 × 360: x runs from -240 (left) to 240 (right) and y from -180 (bottom) to 180 (top). Direction 90 points right, 0 up, -90 left and 180 down.

void move(double steps) Sprites only

Moves the sprite forward in the direction it is pointing. Negative numbers move backwards. If the pen is down, a line is drawn.

Scratch blockmove (10) steps
Parameters
stepshow far to move, in stage pixels
Example
public void whenFlagClicked() {
    goTo(-200, 0);
    pointInDirection(90);
    repeat(40, () -> move(10));   // walks 400 steps to the right
}
void turnRight(double degrees) Sprites only

Turns the sprite clockwise.

Scratch blockturn ↻ (15) degrees
Parameters
degreeshow many degrees to turn
Example
public void whenFlagClicked() {
    forever(() -> turnRight(5));   // spins forever
}
void turnLeft(double degrees) Sprites only

Turns the sprite anticlockwise.

Scratch blockturn ↺ (15) degrees
Parameters
degreeshow many degrees to turn
Example
public void whenKeyPressed(String key) {
    if (key.equals("left arrow")) {
        turnLeft(15);
    }
}
void pointInDirection(double degrees) Sprites only

Points the sprite in a direction: 90 = right, 0 = up, -90 = left, 180 = down. Values are wrapped into the range -179…180.

Scratch blockpoint in direction (90)
Parameters
degreesthe new direction
Example
public void whenKeyPressed(String key) {
    if (key.equals("up arrow"))    pointInDirection(0);
    if (key.equals("right arrow")) pointInDirection(90);
    if (key.equals("down arrow"))  pointInDirection(180);
    if (key.equals("left arrow"))  pointInDirection(-90);
    move(10);
}
void pointTowards(String target) Sprites only

Points the sprite towards the mouse pointer or towards another sprite.

Scratch blockpoint towards [mouse-pointer]
Parameters
target"mouse-pointer" (or "mouse") or the name of another sprite
Example
public void whenFlagClicked() {
    forever(() -> {
        pointTowards("mouse-pointer");
        move(3);                    // follows the mouse
    });
}
void goTo(double x, double y) Sprites only

Jumps straight to a position on the stage.

Scratch blockgo to x: (0) y: (0)
Parameters
x-240 (left) … 240 (right)
y-180 (bottom) … 180 (top)

Note: Sprites always keep a small part on the stage, like in Scratch.

Example
public void whenFlagClicked() {
    goTo(0, 0);        // centre of the stage
}
void goTo(String target) Sprites only

Jumps to the mouse pointer, a random position or another sprite.

Scratch blockgo to [random position]
Parameters
target"mouse-pointer", "random position" or the name of another sprite
Example
public void whenClicked() {
    goTo("random position");   // hop away when clicked
}
void glide(double seconds, double x, double y) Sprites only

Moves smoothly to a position over a number of seconds. The script waits until the glide finishes.

Scratch blockglide (1) secs to x: (0) y: (0)
Parameters
secondshow long the glide takes
xtarget x
ytarget y
Example
public void whenFlagClicked() {
    goTo(-200, -100);
    glide(2, 200, 100);    // diagonal glide across the stage
    glide(1, 0, 0);
}
void changeXBy(double dx) Sprites only

Moves the sprite right (positive) or left (negative).

Scratch blockchange x by (10)
Parameters
dxhow far to move horizontally
Example
public void whenFlagClicked() {
    forever(() -> {
        if (isKeyPressed("right arrow")) changeXBy(5);
        if (isKeyPressed("left arrow"))  changeXBy(-5);
    });
}
void setX(double x) Sprites only

Sets the x position, keeping y the same.

Scratch blockset x to (0)
Parameters
xnew x position
Example
public void whenFlagClicked() {
    setX(-240);              // start at the left edge
    repeatUntil(() -> getX() >= 240, () -> changeXBy(4));
}
void changeYBy(double dy) Sprites only

Moves the sprite up (positive) or down (negative).

Scratch blockchange y by (10)
Parameters
dyhow far to move vertically
Example
@WhenKeyPressed("space")
public void jump() {
    repeat(10, () -> changeYBy(10));    // up
    repeat(10, () -> changeYBy(-10));   // and down again
}
void setY(double y) Sprites only

Sets the y position, keeping x the same.

Scratch blockset y to (0)
Parameters
ynew y position
Example
public void whenFlagClicked() {
    setY(-150);    // stand on the ground
}
void ifOnEdgeBounce() Sprites only

If the sprite is touching the edge of the stage, it turns around (like a ball bouncing off a wall) and moves back onto the stage.

Scratch blockif on edge, bounce

Note: Combine with setRotationStyle("left-right") so a character doesn't walk upside-down.

Example
public void whenFlagClicked() {
    pointInDirection(45);
    forever(() -> {
        move(6);
        ifOnEdgeBounce();
    });
}
void setRotationStyle(String style) Sprites only

Chooses how the costume turns when the direction changes.

Scratch blockset rotation style [left-right]
Parameters
style"all around" (rotates), "left-right" (only flips), or "don't rotate"
Example
public void whenFlagClicked() {
    setRotationStyle("left-right");
    forever(() -> {
        move(4);
        ifOnEdgeBounce();       // faces the way it walks, never upside-down
    });
}
double getX() Sprites only

Reports the sprite's x position.

Scratch block(x position)
Returnsdouble — the sprite's x position
Example
public void whenFlagClicked() {
    forever(() -> {
        if (getX() > 200) {
            say("Too far right!");
        }
        changeXBy(3);
    });
}
double getY() Sprites only

Reports the sprite's y position.

Scratch block(y position)
Returnsdouble — the sprite's y position
Example
public void whenFlagClicked() {
    watch("height", () -> getY());     // live monitor on the stage
}
double getDirection() Sprites only

Reports the direction the sprite points in.

Scratch block(direction)
Returnsdouble — the direction, -179 … 180
Example
public void whenClicked() {
    say("I'm pointing at " + str(getDirection()) + " degrees", 2);
}

Looks

Speech and thought bubbles, costumes, size, visibility, graphic effects and layers. Costume and backdrop numbers start at 1, like in Scratch.

void say(Object message) Sprites only

Shows a speech bubble that stays until the sprite says something else. say("") removes the bubble. Numbers are shown like Scratch shows them (10.0 is shown as 10).

Scratch blocksay [Hello!]
Parameters
messageany value: text, number, boolean, list…
Example
public void whenFlagClicked() {
    say("Hello!");
    waitSeconds(2);
    say("");          // remove the bubble
}
void say(Object message, double seconds) Sprites only

Shows a speech bubble for some seconds, then removes it. The script waits meanwhile.

Scratch blocksay [Hello!] for (2) seconds
Parameters
messagewhat to say
secondshow long to show it
Example
public void whenFlagClicked() {
    say("Hello!", 2);
    say("Welcome to JavaScratch.", 2);
}
void think(Object message) Sprites only

Shows a thought bubble (with little circles instead of a pointer).

Scratch blockthink [Hmm...]
Parameters
messagewhat to think
Example
public void whenClicked() {
    think("Hmm... what should I do?");
}
void think(Object message, double seconds) Sprites only

Shows a thought bubble for some seconds.

Scratch blockthink [Hmm...] for (2) seconds
Parameters
messagewhat to think
secondshow long to show it
Example
public void whenFlagClicked() {
    think("Zzz...", 3);
    say("I'm awake!", 1);
}
void show() Sprites only

Makes the sprite visible.

Scratch blockshow
Example
public void whenFlagClicked() {
    hide();
    waitSeconds(1);
    show();           // appears after one second
}
void hide() Sprites only

Makes the sprite invisible. Hidden sprites can't be clicked and don't touch anything.

Scratch blockhide
Example
public void whenClicked() {
    playSound("pop");
    hide();           // disappear when clicked
}
boolean isVisible() Sprites only

Tells whether the sprite is currently shown.

Returnsboolean — true if the sprite is shown
Example
public void whenKeyPressed(String key) {
    if (key.equals("h")) {
        if (isVisible()) hide(); else show();
    }
}
void switchCostumeTo(String name) Sprites only

Switches to the costume with that name (see the Costumes tab).

Scratch blockswitch costume to [costume2]
Parameters
namethe costume's name
Example
public void whenFlagClicked() {
    switchCostumeTo("bean-a");
}
void switchCostumeTo(int number) Sprites only

Switches to a costume by number. Numbers start at 1, like in Scratch, and wrap around.

Scratch blockswitch costume to (1)
Parameters
number1 for the first costume
Example
public void whenFlagClicked() {
    switchCostumeTo(pickRandom(1, 2));
}
void nextCostume() Sprites only

Switches to the next costume (back to the first after the last). Great for walking animations.

Scratch blocknext costume
Example
public void whenFlagClicked() {
    forever(() -> {
        move(3);
        nextCostume();
        waitSeconds(0.15);
        ifOnEdgeBounce();
    });
}
int getCostumeNumber() Sprites only

Reports the current costume number.

Scratch block(costume #)
Returnsint — current costume number (starting at 1)
Example
public void whenClicked() {
    say("This is costume number " + getCostumeNumber(), 1);
}
String getCostumeName() Sprites only

Reports the current costume's name.

ReturnsString — current costume name
Example
public void whenClicked() {
    nextCostume();
    say(getCostumeName(), 1);
}
void switchBackdropTo(String name) Sprites & Stage

Switches the stage's backdrop by name. Triggers whenBackdropSwitchesTo on every sprite.

Scratch blockswitch backdrop to [backdrop1]
Parameters
namea backdrop name from the stage's Backdrops tab
Example
public void whenFlagClicked() {
    switchBackdropTo("blue sky");
}
void switchBackdropTo(int number) Sprites & Stage

Switches the backdrop by number (starting at 1).

Scratch blockswitch backdrop to (1)
Parameters
number1 for the first backdrop
Example
public void whenFlagClicked() {
    switchBackdropTo(1);
}
void nextBackdrop() Sprites & Stage

Switches to the next backdrop.

Scratch blocknext backdrop
Example
public void whenKeyPressed(String key) {
    if (key.equals("n")) nextBackdrop();
}
String backdropName() Sprites & Stage

Reports the backdrop name.

Scratch block(backdrop name)
ReturnsString — the current backdrop's name
Example
public void whenFlagClicked() {
    if (backdropName().equals("night")) {
        say("It's dark!", 2);
    }
}
int backdropNumber() Sprites & Stage

Reports the backdrop number.

Scratch block(backdrop #)
Returnsint — current backdrop number (starting at 1)
Example
public void whenClicked() {
    say("Level " + backdropNumber(), 1);
}
void setEffect(String effect, double value) Sprites & Stage

Sets a graphic effect. "color" shifts the colours around the rainbow (0–200 is a full turn), "brightness" goes from -100 (black) to 100 (white), "ghost" from 0 (solid) to 100 (invisible).

Scratch blockset [ghost] effect to (50)
Parameters
effect"color", "brightness" or "ghost"
valuethe effect amount
Example
public void whenFlagClicked() {
    setEffect("ghost", 50);   // half transparent
}
void changeEffect(String effect, double by) Sprites & Stage

Changes a graphic effect by an amount.

Scratch blockchange [color] effect by (25)
Parameters
effect"color", "brightness" or "ghost"
byhow much to change it
Example
public void whenFlagClicked() {
    repeat(20, () -> changeEffect("ghost", 5));   // fade out
    hide();
    clearGraphicEffects();
}
void clearGraphicEffects() Sprites & Stage

Removes all graphic effects.

Scratch blockclear graphic effects
Example
public void whenFlagClicked() {
    clearGraphicEffects();
    show();
}
void changeSizeBy(double percent) Sprites only

Grows (positive) or shrinks (negative) the sprite.

Scratch blockchange size by (10)
Parameters
percenthow many percent to grow
Example
public void whenClicked() {
    repeat(10, () -> changeSizeBy(5));
    repeat(10, () -> changeSizeBy(-5));   // "pulse"
}
void setSizeTo(double percent) Sprites only

Sets the size in percent of the costume's normal size (100 = normal). Very small and very large sizes are limited, like in Scratch.

Scratch blockset size to (100) %
Parameters
percentnew size, e.g. 50 for half size
Example
public void whenFlagClicked() {
    setSizeTo(50);
}
double getSize() Sprites only

Reports the size.

Scratch block(size)
Returnsdouble — the size in percent
Example
public void whenFlagClicked() {
    repeatUntil(() -> getSize() >= 200, () -> changeSizeBy(2));
}
void goToFront() Sprites only

Draws this sprite in front of all other sprites.

Scratch blockgo to front
Example
public void whenClicked() {
    goToFront();
}
void goToBack() Sprites only

Draws this sprite behind all other sprites (but in front of the backdrop).

Example
public void whenFlagClicked() {
    goToBack();     // e.g. scenery sprites
}
void goBackLayers(int n) Sprites only

Moves the sprite back by some layers.

Scratch blockgo back (1) layers
Parameters
nhow many layers to go back
Example
public void whenClicked() {
    goBackLayers(1);
}
void goForwardLayers(int n) Sprites only

Moves the sprite forward by some layers.

Parameters
nhow many layers to come forward
Example
public void whenClicked() {
    goForwardLayers(1);
}

Sound

Play the sounds from the Sounds tab, play MIDI notes and drums, and control volume and tempo.

void playSound(String name) Sprites & Stage

Starts playing a sound from the sprite's Sounds tab and continues immediately.

Scratch blockstart sound [pop]
Parameters
namethe sound's name
Example
public void whenClicked() {
    playSound("pop");
}
void playSoundUntilDone(String name) Sprites & Stage

Plays a sound and waits until it has finished.

Scratch blockplay sound [pop] until done
Parameters
namethe sound's name
Example
public void whenFlagClicked() {
    forever(() -> playSoundUntilDone("pop"));   // a sound loop
}
void stopAllSounds() Sprites & Stage

Stops every sound that is playing.

Scratch blockstop all sounds
Example
public void whenKeyPressed(String key) {
    if (key.equals("m")) stopAllSounds();
}
void playNote(double note, double beats) Sprites & Stage

Plays a MIDI note for some beats and waits. 60 is middle C; each step is a semitone.

Scratch blockplay note (60) for (0.5) beats
Parameters
noteMIDI note number (60 = C, 62 = D, 64 = E …)
beatslength in beats (see setTempo)
Example
public void whenFlagClicked() {
    int[] tune = {60, 62, 64, 65, 67, 67};
    for (int n : tune) {
        playNote(n, 0.5);
    }
}
void playDrum(int drum, double beats) Sprites & Stage

Plays a drum sound for some beats. 1 snare, 2 bass drum, 3 side stick, 4 crash cymbal, 5 open hi-hat, 6 closed hi-hat, 7 tambourine, 8 hand clap, 9 claves, 10 wood block, 11 cowbell, 12 triangle, 13 bongo, 14 conga, 15 cabasa, 16 guiro, 17 vibraslap, 18 cuica.

Scratch blockplay drum (1) for (0.25) beats
Parameters
drumdrum number 1–18
beatslength in beats
Example
public void whenFlagClicked() {
    repeat(8, () -> {
        playDrum(2, 0.5);   // bass drum
        playDrum(1, 0.5);   // snare
    });
}
void rest(double beats) Sprites & Stage

Waits for some beats (a musical pause).

Scratch blockrest for (0.25) beats
Parameters
beatshow many beats
Example
public void whenFlagClicked() {
    playNote(60, 1);
    rest(1);
    playNote(67, 1);
}
void setInstrument(int instrument) Sprites & Stage

Chooses the General MIDI instrument used by playNote: 1 piano, 13 marimba, 25 nylon guitar, 33 bass, 41 violin, 57 trumpet, 66 saxophone, 74 flute, 81 synth lead …

Scratch blockset instrument to (1)
Parameters
instrument1–128
Example
public void whenFlagClicked() {
    setInstrument(74);      // flute
    playNote(72, 1);
}
void setTempo(double bpm) Sprites & Stage

Sets the tempo in beats per minute (shared by all sprites).

Scratch blockset tempo to (60) bpm
Parameters
bpmbeats per minute, 20–500
Example
public void whenFlagClicked() {
    setTempo(120);          // 120 bpm: one beat = 0.5 s
    playNote(60, 1);
}
void changeTempo(double by) Sprites & Stage

Changes the tempo.

Scratch blockchange tempo by (20)
Parameters
byhow many bpm to add
Example
public void whenKeyPressed(String key) {
    if (key.equals("f")) changeTempo(20);   // faster
}
double tempo() Sprites & Stage

Reports the tempo.

Scratch block(tempo)
Returnsdouble — beats per minute
Example
public void whenFlagClicked() {
    watch("tempo", () -> tempo());
}
void setVolume(double percent) Sprites & Stage

Sets this sprite's volume, 0–100 %.

Scratch blockset volume to (100) %
Parameters
percent0 (silent) to 100 (full)
Example
public void whenFlagClicked() {
    setVolume(30);
    playSound("pop");
}
void changeVolume(double by) Sprites & Stage

Changes the volume.

Scratch blockchange volume by (-10)
Parameters
bypercent to add (negative = quieter)
Example
public void whenFlagClicked() {
    setVolume(100);
    repeat(10, () -> {
        playSoundUntilDone("pop");
        changeVolume(-10);      // gets quieter each time
    });
}
double volume() Sprites & Stage

Reports the volume.

Scratch block(volume)
Returnsdouble — the volume in percent
Example
public void whenClicked() {
    say("Volume: " + str(volume()) + "%", 1);
}

Pen

Draw on the stage. When the pen is down, the sprite leaves a line wherever it moves.

void penDown() Sprites only

Puts the pen down: from now on the sprite draws a line as it moves.

Scratch blockpen down
Example
public void whenFlagClicked() {
    clearPen();
    goTo(0, 0);
    penDown();
    repeat(4, () -> {        // a square
        move(100);
        turnRight(90);
    });
    penUp();
}
void penUp() Sprites only

Lifts the pen: the sprite stops drawing.

Scratch blockpen up
Example
public void whenFlagClicked() {
    penUp();
    goTo(-100, 0);   // move without drawing
    penDown();
    goTo(100, 0);    // draws a line
    penUp();
}
void clearPen() Sprites & Stage

Erases all pen lines and stamps from the stage.

Scratch blockclear
Example
public void whenKeyPressed(String key) {
    if (key.equals("c")) clearPen();
}
void stamp() Sprites only

Prints a picture of the sprite onto the stage, like a rubber stamp.

Scratch blockstamp
Example
public void whenFlagClicked() {
    clearPen();
    goTo(-200, 0);
    repeat(9, () -> {
        stamp();
        changeXBy(50);
    });
}
void setPenColor(Color color) Sprites only

Sets the pen colour. Use a constant like Color.RED or any colour with new Color(red, green, blue).

Scratch blockset pen color to [■]
Parameters
colora java.awt.Color
Example
public void whenFlagClicked() {
    setPenColor(new Color(255, 128, 0));   // orange
    setPenSize(5);
    penDown();
    glide(1, 200, 0);
    penUp();
}
void setPenHue(double hue) Sprites only

Sets the pen colour as a number like Scratch 2: 0 red, 35 yellow, 70 green, 130 blue, 170 purple, 200 red again.

Scratch blockset pen color to (0)
Parameters
hue0–200
Example
public void whenFlagClicked() {
    setPenHue(130);   // blue
}
void changePenHue(double by) Sprites only

Shifts the pen colour around the rainbow.

Scratch blockchange pen color by (10)
Parameters
byhow far to shift (200 = full circle)
Example
public void whenFlagClicked() {
    clearPen();
    goTo(0, 0);
    setPenSize(4);
    penDown();
    repeat(72, () -> {     // rainbow circle
        move(10);
        turnRight(5);
        changePenHue(3);
    });
    penUp();
}
void setPenSize(double size) Sprites only

Sets the pen thickness in pixels.

Scratch blockset pen size to (1)
Parameters
size1–255
Example
public void whenFlagClicked() {
    setPenSize(10);
}
void changePenSize(double by) Sprites only

Makes the pen thicker or thinner.

Scratch blockchange pen size by (1)
Parameters
bypixels to add
Example
public void whenFlagClicked() {
    clearPen();
    setPenSize(1);
    goTo(-200, 0);
    penDown();
    repeat(40, () -> {
        move(10);
        changePenSize(0.5);   // a line that gets thicker
    });
    penUp();
}

Variables

Java fields are “for this sprite only” variables. The methods below manage global variables shared by every sprite and the stage, and show values as monitors on the stage.

fields: int score = 0; Sprites & Stage

A variable “for this sprite only” is simply a Java field: declare it outside any method. Every method of the sprite can read and change it — also inside forever/repeat lambdas. Clones get a copy of the fields.

Scratch blockmake a variable (for this sprite only)

Note: Local variables (inside a method) can't be changed inside a lambda — use fields for counters.

Example
int score = 0;
double speed = 3;
List<String> items = new ArrayList<>();

public void whenFlagClicked() {
    score = 0;
    forever(() -> {
        move(speed);
        ifOnEdgeBounce();
    });
}

public void whenClicked() {
    score++;
    items.add("click " + score);
    say(score, 0.5);
}
void setVariable(String name, Object value) Sprites & Stage

Sets a global variable that every sprite and the stage can read.

Scratch blockset [score] to (0)
Parameters
namevariable name
valueany value (number, text…)
Example
public void whenFlagClicked() {
    setVariable("score", 0);
    setVariable("player", "Alex");
}
void changeVariable(String name, double by) Sprites & Stage

Adds a number to a global variable (a variable that doesn't exist yet starts at 0).

Scratch blockchange [score] by (1)
Parameters
namevariable name
byamount to add
Example
public void whenClicked() {
    changeVariable("score", 1);
}
Object getVariable(String name) Sprites & Stage

Reads a global variable.

Scratch block(score)
Parameters
namevariable name
ReturnsObject — the value (0 if it was never set)
Example
public void whenClicked() {
    say("Player: " + getVariable("player"), 2);
}
double getNumber(String name) Sprites & Stage

Reads a global variable as a number (text that isn't a number gives 0).

Scratch block(score)
Parameters
namevariable name
Returnsdouble — the value as a number
Example
public void whenFlagClicked() {
    forever(() -> {
        if (getNumber("score") >= 10) {
            say("You win!");
            stopAll();
        }
    });
}
void showVariable(String name) Sprites & Stage

Shows a monitor for a global variable at the top-left of the stage.

Scratch blockshow variable [score]
Parameters
namevariable name
Example
public void whenFlagClicked() {
    setVariable("score", 0);
    showVariable("score");
}
void hideVariable(String name) Sprites & Stage

Hides a variable monitor.

Scratch blockhide variable [score]
Parameters
namevariable name
Example
public void whenKeyPressed(String key) {
    if (key.equals("h")) hideVariable("score");
}
void watch(String label, Supplier<Object> value) Sprites & Stage

Shows a monitor for any value — for example one of your fields. The value is read again every frame.

Parameters
labelthe label shown on the monitor
valuea lambda returning the value, e.g. () -> lives
Example
int lives = 3;

public void whenFlagClicked() {
    watch("lives", () -> lives);
    watch("x", () -> getX());
}
void unwatch(String label) Sprites & Stage

Removes a monitor created with watch() or showVariable().

Parameters
labelthe monitor's label
Example
public void whenKeyPressed(String key) {
    if (key.equals("x")) unwatch("x");
}

Events

Event methods are JavaScratch's hat blocks: give a method one of these names (or annotation) and it runs automatically when the event happens. Each runs in its own thread, at the same time as the others.

public void whenFlagClicked() Sprites & Stage

Runs when the green flag is clicked (or F5 / Ctrl+Enter). Most programs start here.

Scratch blockwhen ⚑ clicked
Example
public void whenFlagClicked() {
    goTo(0, 0);
    say("Ready!", 1);
}
public void whenKeyPressed(String key) Sprites & Stage

Runs when any key is pressed. key is "space", "up arrow", "down arrow", "left arrow", "right arrow", "enter", a letter like "a" or a digit like "1". The stage must have keyboard focus (click on it).

Scratch blockwhen [space] key pressed
Parameters
keythe name of the pressed key
Example
public void whenKeyPressed(String key) {
    switch (key) {
        case "space": changeYBy(30); break;
        case "a":     turnLeft(15);  break;
        case "d":     turnRight(15); break;
        default:      break;
    }
}
public void whenClicked() Sprites & Stage

Runs when this sprite is clicked (on the stage: when the stage is clicked).

Scratch blockwhen this sprite clicked
Example
public void whenClicked() {
    playSound("pop");
    changeEffect("color", 25);
}
public void whenIReceive(String message) Sprites & Stage

Runs when any message is broadcast with broadcast() or broadcastAndWait(). If the same message arrives again while the method is still running, it restarts — like Scratch.

Scratch blockwhen I receive [message1]
Parameters
messagethe broadcast message
Example
public void whenIReceive(String message) {
    if (message.equals("game over")) {
        say("Bye!");
        hide();
    }
}
public void whenBackdropSwitchesTo(String backdrop) Sprites & Stage

Runs when the stage switches backdrop.

Scratch blockwhen backdrop switches to [backdrop1]
Parameters
backdropthe new backdrop's name
Example
public void whenBackdropSwitchesTo(String backdrop) {
    if (backdrop.equals("night")) {
        think("Time to sleep...");
    }
}
@WhenFlagClicked @WhenKeyPressed("key") @WhenThisSpriteClicked @WhenIReceive("message") @WhenIStartAsClone @WhenBackdropSwitchesTo("name") Sprites & Stage

Annotations let a method with any name react to an event — and let one sprite have several scripts for the same event, like several hat blocks in Scratch. @WhenKeyPressed("any") reacts to every key.

Scratch blockseveral hat blocks
Example
@WhenFlagClicked
public void walk() {
    forever(() -> { move(2); ifOnEdgeBounce(); });
}

@WhenFlagClicked
public void blink() {
    forever(() -> { waitSeconds(1); nextCostume(); });
}

@WhenKeyPressed("space")
public void jump() {
    repeat(8, () -> changeYBy(10));
    repeat(8, () -> changeYBy(-10));
}

@WhenIReceive("level up")
public void levelUp() {
    changeSizeBy(10);
}
void broadcast(String message) Sprites & Stage

Sends a message to every sprite and the stage, starting their whenIReceive methods. Continues immediately.

Scratch blockbroadcast [message1]
Parameters
messageany text
Example
public void whenFlagClicked() {
    waitUntil(() -> isTouching("edge"));
    broadcast("game over");
}
void broadcastAndWait(String message) Sprites & Stage

Sends a message and waits until every script started by it has finished.

Scratch blockbroadcast [message1] and wait
Parameters
messageany text
Example
public void whenFlagClicked() {
    broadcastAndWait("intro");     // wait for the intro to finish
    say("Let's play!", 2);
}

Control

Waiting, loops, stopping and clones. Loop helpers wait one frame (1/30 s) after each repetition, just like Scratch's loops, so animations are visible.

void waitSeconds(double seconds) Sprites & Stage

Pauses this script for some seconds. Other scripts keep running.

Scratch blockwait (1) seconds
Parameters
secondshow long to wait (decimals allowed)

Note: Named waitSeconds because wait() already exists in every Java object.

Example
public void whenFlagClicked() {
    say("3"); waitSeconds(1);
    say("2"); waitSeconds(1);
    say("1"); waitSeconds(1);
    say("Go!", 1);
}
void forever(Runnable body) Sprites & Stage

Repeats the body forever, waiting one frame (1/30 s) after each repetition. Ends only when the project is stopped (or with stopThisScript()).

Scratch blockforever { }
Parameters
bodya lambda: () -> { ... }
Example
public void whenFlagClicked() {
    forever(() -> {
        turnRight(3);
        move(2);
    });
}
void repeat(int times, Runnable body) Sprites & Stage

Repeats the body a number of times, one repetition per frame.

Scratch blockrepeat (10) { }
Parameters
timeshow many times
bodya lambda: () -> { ... }
Example
public void whenFlagClicked() {
    repeat(36, () -> {
        turnRight(10);    // one full turn in 36 frames
    });
}
void repeatUntil(BooleanSupplier condition, Runnable body) Sprites & Stage

Repeats the body until the condition becomes true.

Scratch blockrepeat until <> { }
Parameters
conditiona lambda returning boolean: () -> ...
bodya lambda: () -> { ... }
Example
public void whenFlagClicked() {
    goTo(0, 0);
    repeatUntil(() -> isTouching("edge"), () -> move(5));
    say("Ouch!", 1);
}
void waitUntil(BooleanSupplier condition) Sprites & Stage

Waits until the condition becomes true.

Scratch blockwait until <>
Parameters
conditiona lambda returning boolean
Example
public void whenFlagClicked() {
    say("Click the mouse to start");
    waitUntil(() -> isMouseDown());
    say("Go!", 1);
}
void nextFrame() Sprites & Stage

Waits until the next screen refresh (1/30 s). Call it inside your own while / for loops so the animation is visible and the stop sign works.

Note: A loop that never calls any JavaScratch method can't be stopped by the stop sign.

Example
public void whenFlagClicked() {
    for (int i = 0; i < 100; i++) {
        move(2);
        nextFrame();          // without this the loop would finish instantly
    }
    while (!isTouching("edge")) {
        changeYBy(3);
        nextFrame();
    }
}
if / else Sprites & Stage

Plain Java if-statements work like Scratch's if and if-else blocks. Compare numbers with < > == and text with .equals(…).

Scratch blockif <> then / else
Example
public void whenFlagClicked() {
    forever(() -> {
        if (isTouching("mouse-pointer")) {
            setEffect("brightness", 30);
        } else {
            setEffect("brightness", 0);
        }
    });
}
void stopAll() Sprites & Stage

Stops every script of every sprite, like the red stop sign.

Scratch blockstop [all]
Example
public void whenFlagClicked() {
    waitUntil(() -> isTouching("edge"));
    say("Game over");
    stopAll();
}
void stopThisScript() Sprites & Stage

Stops the method (script) that is running this line.

Scratch blockstop [this script]
Example
public void whenFlagClicked() {
    forever(() -> {
        move(5);
        if (getX() > 200) {
            stopThisScript();    // leaves the forever loop
        }
    });
}
void stopOtherScriptsInSprite() Sprites & Stage

Stops all other running methods of this sprite.

Scratch blockstop [other scripts in sprite]
Example
public void whenClicked() {
    stopOtherScriptsInSprite();   // stop walking
    say("You caught me!", 2);
}
public void whenIStartAsClone() Sprites only

Event method: runs in a new clone right after createClone(). Use it to give every clone its own behaviour.

Scratch blockwhen I start as a clone
Example
public void whenFlagClicked() {
    hide();
    repeat(10, () -> createClone());
}

public void whenIStartAsClone() {
    goTo("random position");
    show();
    forever(() -> turnRight(5));
}
void createClone() Sprites only

Creates a copy of this sprite (position, costume, size, effects and field values are copied). The clone then runs its whenIStartAsClone methods. At most 300 clones exist at the same time.

Scratch blockcreate clone of [myself]
Example
public void whenFlagClicked() {
    hide();
    forever(() -> {
        createClone();
        waitSeconds(0.5);
    });
}

public void whenIStartAsClone() {
    goTo(pickRandom(-220, 220), 180);
    show();
    repeatUntil(() -> getY() < -170, () -> changeYBy(-5));
    deleteThisClone();
}
void createCloneOf(String spriteName) Sprites & Stage

Creates a clone of another sprite (or of this sprite with "myself"). Available on the stage too.

Scratch blockcreate clone of [Sprite1]
Parameters
spriteNamethe sprite's name, or "myself"
Example
public void whenKeyPressed(String key) {
    if (key.equals("space")) createCloneOf("Ball");
}
void deleteThisClone() Sprites only

Deletes this clone and stops its scripts. Does nothing in the original sprite.

Scratch blockdelete this clone
Example
public void whenIStartAsClone() {
    show();
    waitSeconds(3);
    deleteThisClone();
}
boolean isClone() Sprites only

Tells whether this is a clone.

Returnsboolean — true for clones, false for the original
Example
public void whenClicked() {
    if (isClone()) {
        deleteThisClone();
    } else {
        say("I'm the original!", 1);
    }
}

Sensing

Find out about touching, the mouse, the keyboard, other sprites, the timer, and ask the user questions.

boolean isTouching(String what) Sprites only

Checks pixel-perfectly whether the sprite touches the edge of the stage, the mouse pointer or another sprite (including that sprite's clones). Hidden sprites never touch anything.

Scratch block<touching [ ]?>
Parameters
what"edge", "mouse-pointer" or a sprite name
Returnsboolean — true if touching
Example
public void whenFlagClicked() {
    forever(() -> {
        move(4);
        if (isTouching("Apple")) {
            playSound("pop");
            changeVariable("score", 1);
        }
        ifOnEdgeBounce();
    });
}
boolean isTouchingColor(Color color) Sprites only

Checks whether the sprite touches a colour drawn on the stage (backdrop, pen lines or other sprites).

Scratch block<touching color [■]?>
Parameters
colorthe colour to look for, e.g. Color.RED or new Color(0, 200, 0)
Returnsboolean — true if touching that colour

Note: The colour must match closely (within about 16 per red/green/blue channel).

Example
public void whenFlagClicked() {
    forever(() -> {
        changeYBy(-3);
        if (isTouchingColor(new Color(80, 150, 50))) {   // the green ground
            say("Landed!");
            stopThisScript();
        }
    });
}
double distanceTo(String target) Sprites only

Reports the distance to the mouse pointer or to another sprite.

Scratch block(distance to [mouse-pointer])
Parameters
target"mouse-pointer" or a sprite name
Returnsdouble — distance in pixels
Example
public void whenFlagClicked() {
    forever(() -> {
        if (distanceTo("mouse-pointer") < 50) {
            say("Too close!");
        } else {
            say("");
        }
    });
}
String ask(Object question) Sprites & Stage

Shows the question (as a speech bubble for a visible sprite) and an input box under the stage, and waits until the user presses Enter.

Scratch blockask [What's your name?] and wait
Parameters
questionwhat to ask
ReturnsString — the text the user typed
Example
public void whenFlagClicked() {
    String name = ask("What's your name?");
    say("Hello, " + name + "!", 2);
    int age = (int) toNumber(ask("How old are you?"));
    say("Next year you'll be " + (age + 1), 2);
}
String answer() Sprites & Stage

Reports the most recent answer to ask().

Scratch block(answer)
ReturnsString — the last answer
Example
public void whenFlagClicked() {
    ask("Favourite colour?");
    say(answer() + " is nice!", 2);
}
boolean isKeyPressed(String key) Sprites & Stage

Checks whether a key is held down right now. Best for smooth movement in a forever loop.

Scratch block<key [space] pressed?>
Parameters
key"space", "up arrow", "a", "1", … or "any"
Returnsboolean — true while the key is held down
Example
public void whenFlagClicked() {
    forever(() -> {
        if (isKeyPressed("up arrow"))    changeYBy(5);
        if (isKeyPressed("down arrow"))  changeYBy(-5);
        if (isKeyPressed("left arrow"))  changeXBy(-5);
        if (isKeyPressed("right arrow")) changeXBy(5);
    });
}
boolean isMouseDown() Sprites & Stage

Checks whether the mouse button is down.

Scratch block<mouse down?>
Returnsboolean — true while the mouse button is pressed
Example
public void whenFlagClicked() {
    forever(() -> {
        if (isMouseDown()) {
            goTo("mouse-pointer");
        }
    });
}
double mouseX() Sprites & Stage

Reports the mouse x position.

Scratch block(mouse x)
Returnsdouble — mouse x position on the stage
Example
public void whenFlagClicked() {
    forever(() -> setX(mouseX()));   // a paddle that follows the mouse
}
double mouseY() Sprites & Stage

Reports the mouse y position.

Scratch block(mouse y)
Returnsdouble — mouse y position on the stage
Example
public void whenFlagClicked() {
    forever(() -> goTo(mouseX(), mouseY()));
}
double timer() Sprites & Stage

Reports the timer in seconds.

Scratch block(timer)
Returnsdouble — seconds since the green flag (or resetTimer)
Example
public void whenFlagClicked() {
    resetTimer();
    waitUntil(() -> isTouching("Star"));
    say("You took " + Math.round(timer()) + " seconds");
}
void resetTimer() Sprites & Stage

Sets the timer back to 0.

Scratch blockreset timer
Example
public void whenKeyPressed(String key) {
    if (key.equals("r")) resetTimer();
}
double xPositionOf(String sprite) Sprites & Stage

Reports another sprite's x position.

Scratch block([x position] of [Sprite1])
Parameters
spritethe sprite's name
Returnsdouble
Example
public void whenFlagClicked() {
    forever(() -> {
        // follow the Bean, staying 50 pixels behind it
        goTo(xPositionOf("Bean") - 50, yPositionOf("Bean"));
    });
}
double yPositionOf(String sprite) Sprites & Stage

Reports another sprite's y position.

Scratch block([y position] of [Sprite1])
Parameters
spritethe sprite's name
Returnsdouble
Example
public void whenFlagClicked() {
    if (yPositionOf("Bean") > 0) say("Bean is up high!", 2);
}
double directionOf(String sprite) Sprites & Stage

Reports another sprite's direction.

Scratch block([direction] of [Sprite1])
Parameters
spritethe sprite's name
Returnsdouble
Example
public void whenFlagClicked() {
    forever(() -> pointInDirection(directionOf("Bean")));   // copy the Bean's direction
}
int costumeNumberOf(String sprite) Sprites & Stage

Reports another sprite's costume number.

Scratch block([costume #] of [Sprite1])
Parameters
spritethe sprite's name
Returnsint
Example
public void whenFlagClicked() {
    forever(() -> switchCostumeTo(costumeNumberOf("Bean")));
}
void setDraggable(boolean draggable) Sprites only

Lets the user drag the sprite with the mouse in full-screen mode (in the editor every sprite can be dragged).

Scratch blockset drag mode [draggable]
Parameters
draggabletrue to allow dragging
Example
public void whenFlagClicked() {
    setDraggable(true);
}

Operators

Random numbers and text helpers. Everything else (+, -, *, /, %, <, >, ==, &&, ||, Math.*) is plain Java.

int pickRandom(int from, int to) Sprites & Stage

Picks a random whole number.

Scratch block(pick random (1) to (10))
Parameters
fromsmallest possible value
tolargest possible value
Returnsint — a random whole number from…to (inclusive)
Example
public void whenClicked() {
    int dice = pickRandom(1, 6);
    say("You rolled " + dice, 1);
}
double pickRandom(double from, double to) Sprites & Stage

Picks a random decimal number. Use it by writing decimal numbers, e.g. pickRandom(0.5, 1.5).

Scratch block(pick random (0.5) to (1.5))
Parameters
fromlower limit
toupper limit
Returnsdouble — a random decimal number
Example
public void whenFlagClicked() {
    forever(() -> {
        move(3);
        waitSeconds(pickRandom(0.1, 0.5));
    });
}
String join(Object... parts) Sprites & Stage

Joins any number of values into one text. Numbers are formatted like Scratch (3.0 becomes 3).

Scratch block(join [hello ] [world])
Parameters
partsthe values to join
ReturnsString — all parts joined together
Example
public void whenClicked() {
    say(join("I am at ", getX(), ", ", getY()), 2);
}
String letterOf(int index, String text) Sprites & Stage

Reports a letter of a text. The first letter is number 1, like in Scratch.

Scratch block(letter (1) of [world])
Parameters
indexletter number, starting at 1
textthe text
ReturnsString — one letter (empty if out of range)
Example
public void whenFlagClicked() {
    String word = "JAVA";
    for (int i = 1; i <= word.length(); i++) {
        say(letterOf(i, word), 0.5);
    }
}
static String str(Object value) Sprites & Stage

Turns any value into text, formatted like Scratch (10.0 → "10").

Parameters
valueany value
ReturnsString
Example
public void whenClicked() {
    say("x = " + str(getX()), 1);     // shows "x = 10", not "x = 10.0"
}
static double toNumber(Object value) Sprites & Stage

Turns text (or anything) into a number, like Scratch does.

Parameters
valueany value
Returnsdouble — the number (0 if it isn't a number)
Example
public void whenFlagClicked() {
    double n = toNumber(ask("Pick a number"));
    say("Twice that is " + str(n * 2), 2);
}
Java operators and Math Sprites & Stage

All of Java is available: + - * / % for arithmetic, < > <= >= == != to compare numbers, && (and), || (or), ! (not), text.equals(…) to compare text, and Math.round, Math.abs, Math.sqrt, Math.floor, Math.sin, Math.pow …

Scratch block( ) + ( ), < >, and / or / not, round, mod, sqrt of …
Example
public void whenFlagClicked() {
    double d = Math.sqrt(getX() * getX() + getY() * getY());
    boolean far = d > 100 && !isTouching("edge");
    int rest = 17 % 5;                       // 2
    say(join("distance ", Math.round(d), "  far=", far, "  17 mod 5 = ", rest), 3);
}

More & Output

Your own methods are JavaScratch's “custom blocks”. Plus printing to the Output panel and sprite information.

custom methods (Scratch's “Make a Block”) Sprites & Stage

Write your own methods and call them from your event methods. Parameters work like custom-block inputs; methods can also return a value (like a reporter).

Scratch blockdefine [polygon (n) (size)]
Example
public void whenFlagClicked() {
    clearPen();
    penDown();
    polygon(6, 60);
    penUp();
}

void polygon(int sides, double size) {
    for (int i = 0; i < sides; i++) {
        move(size);
        turnRight(360.0 / sides);
        nextFrame();
    }
}

double half(double n) {    // a "reporter" block
    return n / 2;
}
void print(Object value) Sprites & Stage

Writes a line to the Output panel below the editor, prefixed with the sprite's name. System.out.println(…) also works.

Parameters
valueanything to print
Example
public void whenFlagClicked() {
    print("Starting at " + str(getX()) + ", " + str(getY()));
    System.out.println("This also goes to the Output panel");
}
String getName() Sprites & Stage

Reports the sprite's name (clones have the same name).

ReturnsString — the sprite's name
Example
public void whenClicked() {
    say("My name is " + getName(), 2);
}

Quick reference

CategoryMethodWhat it doesUse in
Motionvoid move(double steps)Moves the sprite forward in the direction it is pointing.sprite
Motionvoid turnRight(double degrees)Turns the sprite clockwise.sprite
Motionvoid turnLeft(double degrees)Turns the sprite anticlockwise.sprite
Motionvoid pointInDirection(double degrees)Points the sprite in a direction: 90 = right, 0 = up, -90 = left, 180 = down.sprite
Motionvoid pointTowards(String target)Points the sprite towards the mouse pointer or towards another sprite.sprite
Motionvoid goTo(double x, double y)Jumps straight to a position on the stage.sprite
Motionvoid goTo(String target)Jumps to the mouse pointer, a random position or another sprite.sprite
Motionvoid glide(double seconds, double x, double y)Moves smoothly to a position over a number of seconds.sprite
Motionvoid changeXBy(double dx)Moves the sprite right (positive) or left (negative).sprite
Motionvoid setX(double x)Sets the x position, keeping y the same.sprite
Motionvoid changeYBy(double dy)Moves the sprite up (positive) or down (negative).sprite
Motionvoid setY(double y)Sets the y position, keeping x the same.sprite
Motionvoid ifOnEdgeBounce()If the sprite is touching the edge of the stage, it turns around (like a ball bouncing off a wall) and moves back onto the stage.sprite
Motionvoid setRotationStyle(String style)Chooses how the costume turns when the direction changes.sprite
Motiondouble getX()Reports the sprite's x position.sprite
Motiondouble getY()Reports the sprite's y position.sprite
Motiondouble getDirection()Reports the direction the sprite points in.sprite
Looksvoid say(Object message)Shows a speech bubble that stays until the sprite says something else.sprite
Looksvoid say(Object message, double seconds)Shows a speech bubble for some seconds, then removes it.sprite
Looksvoid think(Object message)Shows a thought bubble (with little circles instead of a pointer).sprite
Looksvoid think(Object message, double seconds)Shows a thought bubble for some seconds.sprite
Looksvoid show()Makes the sprite visible.sprite
Looksvoid hide()Makes the sprite invisible.sprite
Looksboolean isVisible()Tells whether the sprite is currently shown.sprite
Looksvoid switchCostumeTo(String name)Switches to the costume with that name (see the Costumes tab).sprite
Looksvoid switchCostumeTo(int number)Switches to a costume by number.sprite
Looksvoid nextCostume()Switches to the next costume (back to the first after the last).sprite
Looksint getCostumeNumber()Reports the current costume number.sprite
LooksString getCostumeName()Reports the current costume's name.sprite
Looksvoid switchBackdropTo(String name)Switches the stage's backdrop by name.all
Looksvoid switchBackdropTo(int number)Switches the backdrop by number (starting at 1).all
Looksvoid nextBackdrop()Switches to the next backdrop.all
LooksString backdropName()Reports the backdrop name.all
Looksint backdropNumber()Reports the backdrop number.all
Looksvoid setEffect(String effect, double value)Sets a graphic effect.all
Looksvoid changeEffect(String effect, double by)Changes a graphic effect by an amount.all
Looksvoid clearGraphicEffects()Removes all graphic effects.all
Looksvoid changeSizeBy(double percent)Grows (positive) or shrinks (negative) the sprite.sprite
Looksvoid setSizeTo(double percent)Sets the size in percent of the costume's normal size (100 = normal).sprite
Looksdouble getSize()Reports the size.sprite
Looksvoid goToFront()Draws this sprite in front of all other sprites.sprite
Looksvoid goToBack()Draws this sprite behind all other sprites (but in front of the backdrop).sprite
Looksvoid goBackLayers(int n)Moves the sprite back by some layers.sprite
Looksvoid goForwardLayers(int n)Moves the sprite forward by some layers.sprite
Soundvoid playSound(String name)Starts playing a sound from the sprite's Sounds tab and continues immediately.all
Soundvoid playSoundUntilDone(String name)Plays a sound and waits until it has finished.all
Soundvoid stopAllSounds()Stops every sound that is playing.all
Soundvoid playNote(double note, double beats)Plays a MIDI note for some beats and waits.all
Soundvoid playDrum(int drum, double beats)Plays a drum sound for some beats.all
Soundvoid rest(double beats)Waits for some beats (a musical pause).all
Soundvoid setInstrument(int instrument)Chooses the General MIDI instrument used by playNote: 1 piano, 13 marimba, 25 nylon guitar, 33 bass, 41 violin, 57 trumpet, 66 saxophone, 74 flute, 81 synth lead ….all
Soundvoid setTempo(double bpm)Sets the tempo in beats per minute (shared by all sprites).all
Soundvoid changeTempo(double by)Changes the tempo.all
Sounddouble tempo()Reports the tempo.all
Soundvoid setVolume(double percent)Sets this sprite's volume, 0–100 %.all
Soundvoid changeVolume(double by)Changes the volume.all
Sounddouble volume()Reports the volume.all
Penvoid penDown()Puts the pen down: from now on the sprite draws a line as it moves.sprite
Penvoid penUp()Lifts the pen: the sprite stops drawing.sprite
Penvoid clearPen()Erases all pen lines and stamps from the stage.all
Penvoid stamp()Prints a picture of the sprite onto the stage, like a rubber stamp.sprite
Penvoid setPenColor(Color color)Sets the pen colour.sprite
Penvoid setPenHue(double hue)Sets the pen colour as a number like Scratch 2: 0 red, 35 yellow, 70 green, 130 blue, 170 purple, 200 red again.sprite
Penvoid changePenHue(double by)Shifts the pen colour around the rainbow.sprite
Penvoid setPenSize(double size)Sets the pen thickness in pixels.sprite
Penvoid changePenSize(double by)Makes the pen thicker or thinner.sprite
Variablesfields: int score = 0;A variable “for this sprite only” is simply a Java field: declare it outside any method.all
Variablesvoid setVariable(String name, Object value)Sets a global variable that every sprite and the stage can read.all
Variablesvoid changeVariable(String name, double by)Adds a number to a global variable (a variable that doesn't exist yet starts at 0).all
VariablesObject getVariable(String name)Reads a global variable.all
Variablesdouble getNumber(String name)Reads a global variable as a number (text that isn't a number gives 0).all
Variablesvoid showVariable(String name)Shows a monitor for a global variable at the top-left of the stage.all
Variablesvoid hideVariable(String name)Hides a variable monitor.all
Variablesvoid watch(String label, Supplier<Object> value)Shows a monitor for any value — for example one of your fields.all
Variablesvoid unwatch(String label)Removes a monitor created with watch() or showVariable().all
Eventsvoid whenFlagClicked()Runs when the green flag is clicked (or F5 / Ctrl+Enter).all
Eventsvoid whenKeyPressed(String key)Runs when any key is pressed.all
Eventsvoid whenClicked()Runs when this sprite is clicked (on the stage: when the stage is clicked).all
Eventsvoid whenIReceive(String message)Runs when any message is broadcast with broadcast() or broadcastAndWait().all
Eventsvoid whenBackdropSwitchesTo(String backdrop)Runs when the stage switches backdrop.all
Events@WhenFlagClicked @WhenKeyPressed("key") @WhenThisSpriteClicked @WhenIReceive("message") @WhenIStartAsClone @WhenBackdropSwitchesTo("name")Annotations let a method with any name react to an event — and let one sprite have several scripts for the same event, like several hat blocks in Scratch.all
Eventsvoid broadcast(String message)Sends a message to every sprite and the stage, starting their whenIReceive methods.all
Eventsvoid broadcastAndWait(String message)Sends a message and waits until every script started by it has finished.all
Controlvoid waitSeconds(double seconds)Pauses this script for some seconds.all
Controlvoid forever(Runnable body)Repeats the body forever, waiting one frame (1/30 s) after each repetition.all
Controlvoid repeat(int times, Runnable body)Repeats the body a number of times, one repetition per frame.all
Controlvoid repeatUntil(BooleanSupplier condition, Runnable body)Repeats the body until the condition becomes true.all
Controlvoid waitUntil(BooleanSupplier condition)Waits until the condition becomes true.all
Controlvoid nextFrame()Waits until the next screen refresh (1/30 s).all
Controlif / elsePlain Java if-statements work like Scratch's if and if-else blocks.all
Controlvoid stopAll()Stops every script of every sprite, like the red stop sign.all
Controlvoid stopThisScript()Stops the method (script) that is running this line.all
Controlvoid stopOtherScriptsInSprite()Stops all other running methods of this sprite.all
Controlvoid whenIStartAsClone()Event method: runs in a new clone right after createClone().sprite
Controlvoid createClone()Creates a copy of this sprite (position, costume, size, effects and field values are copied).sprite
Controlvoid createCloneOf(String spriteName)Creates a clone of another sprite (or of this sprite with "myself").all
Controlvoid deleteThisClone()Deletes this clone and stops its scripts.sprite
Controlboolean isClone()Tells whether this is a clone.sprite
Sensingboolean isTouching(String what)Checks pixel-perfectly whether the sprite touches the edge of the stage, the mouse pointer or another sprite (including that sprite's clones).sprite
Sensingboolean isTouchingColor(Color color)Checks whether the sprite touches a colour drawn on the stage (backdrop, pen lines or other sprites).sprite
Sensingdouble distanceTo(String target)Reports the distance to the mouse pointer or to another sprite.sprite
SensingString ask(Object question)Shows the question (as a speech bubble for a visible sprite) and an input box under the stage, and waits until the user presses Enter.all
SensingString answer()Reports the most recent answer to ask().all
Sensingboolean isKeyPressed(String key)Checks whether a key is held down right now.all
Sensingboolean isMouseDown()Checks whether the mouse button is down.all
Sensingdouble mouseX()Reports the mouse x position.all
Sensingdouble mouseY()Reports the mouse y position.all
Sensingdouble timer()Reports the timer in seconds.all
Sensingvoid resetTimer()Sets the timer back to 0.all
Sensingdouble xPositionOf(String sprite)Reports another sprite's x position.all
Sensingdouble yPositionOf(String sprite)Reports another sprite's y position.all
Sensingdouble directionOf(String sprite)Reports another sprite's direction.all
Sensingint costumeNumberOf(String sprite)Reports another sprite's costume number.all
Sensingvoid setDraggable(boolean draggable)Lets the user drag the sprite with the mouse in full-screen mode (in the editor every sprite can be dragged).sprite
Operatorsint pickRandom(int from, int to)Picks a random whole number.all
Operatorsdouble pickRandom(double from, double to)Picks a random decimal number.all
OperatorsString join(Object... parts)Joins any number of values into one text.all
OperatorsString letterOf(int index, String text)Reports a letter of a text.all
OperatorsString str(Object value)Turns any value into text, formatted like Scratch (10.0 → "10").all
Operatorsdouble toNumber(Object value)Turns text (or anything) into a number, like Scratch does.all
OperatorsJava operators and MathAll of Java is available: + - * / % for arithmetic, < > <= >= == != to compare numbers, && (and), || (or), ! (not), text.equals(…) to compare text, and Math.round, Math.abs, Math.sqrt, Math.floor, Math.sin, Math.pow ….all
More & Outputcustom methods (Scratch's “Make a Block”)Write your own methods and call them from your event methods.all
More & Outputvoid print(Object value)Writes a line to the Output panel below the editor, prefixed with the sprite's name.all
More & OutputString getName()Reports the sprite's name (clones have the same name).all