Scratch for Java

Time and events

Your code runs at two kinds of moments: every frame, in run(), and when something happens, in the when… methods.

Every frame: run()

run() is called about 60 times a second, for the stage and for every sprite. It is Scratch's forever loop:

public void run() {
  this.move(2);   // 2 steps per frame, about 120 steps per second
}

Each call does one frame's work and then ends. Never write while (true) in run(): the next frame would never be drawn, and the game freezes.

Timers instead of wait

A sprite cannot wait, because run() has to end every frame. Ask a timer instead whether enough time has passed. Every sprite and stage has one:

Timer method is true
every(1) once every second, false in the frames between
after(3) from 3 seconds on
during(3) for the first 3 seconds, then never again
interval(0.5) half a second true, half a second false, and so on
getSeconds() (gives the seconds since the start or the last reset())

reset() starts the timer again from 0. For several timers in one sprite, make your own with new Timer().

Times are in seconds, as in Scratch. Timers count game time, so they stop while the game is paused.

Things that take time

say("Hi!", 2), glide(1, 100, 0) and ask("Name?") start something and return at once. The next line does not wait. To do things one after another, remember which step you are at in a variable:

When something happens

Write one of these methods in a sprite or stage, and the library calls it at the right moment:

Scratch Java
when [space v] key pressed whenKeyPressed(KeyCode key)
when this sprite clicked whenClicked()
when I receive [message v] whenIReceive(String message)
when backdrop switches to [night v] whenBackdropSwitches(String name)
when I start as a clone whenStartsAsClone()

The name and the parameter must be exactly right. Otherwise Java sees a new method of yours, and nobody calls it. Write @Override on the line above: then Java tells you when the name is wrong.

Messages

broadcast("start") sends a message to the stage and every sprite on it. Their whenIReceive runs at once:

Compare texts with equals, not with ==.

Often you do not need a message. A sprite can call a method of another object directly, like this.getStage(), or a method of a sprite it keeps in a variable.

Asking a question

ask shows a box to type in. isAsking() is true until the player presses Enter, then getAnswer() has the text:

Integer.parseInt(this.getAnswer()) turns the answer into a number. Guess the Number builds a game on it.

Next

Time and events

Create Shareable URL

Select Sections