Scratch Block → Sparkle API Calls Mapping
Warning: This page has a lot of images. Loading it may use a noticeable amount of internet data.
Before you start
This page shows how to do in Sparkle (with Java) what a certain Scratch block does. It’s meant to help you translate ideas from Scratch into Sparkle.
Important differences you should know:
- Sprites don’t hold code. In Scratch, a sprite can have scripts attached to it. In Sparkle,
Spriteobjects are just visual things (position, costume, etc.). The code that moves them lives in your Java program, not inside the sprite. - Stages manage layers and backdrops. Things like “go to front layer” or “switch backdrop” are actions on the
Stage, not the sprite. - Time is in milliseconds. Many functions that take time (like “glide for 1 second”) expect the time in milliseconds. So 1 second = 1000 milliseconds.
- No automatic timer. Unlike Scratch, Sparkle does not start a timer automatically. If you need a timer, you must create one yourself using Java tools.
Quick glossary
Sprite- A character or object on screen (has position, costume, size, etc.).
Stage- The background area where sprites live. It manages backdrops, layers, and some global behavior.
sprite(variable)- Your Java variable holding a
Spriteinstance. stage(variable)- Your Java variable holding a
Stageinstance. otherSprite- Another
Spriteyou might want to interact with. "spriteId"- The ID string of a sprite, used to identify it on the stage (e.g., for layer operations).
- Clone ID
- An integer that identifies a specific clone of a sprite. The original sprite’s clone ID is always
0.
This mapping was created for Sparkle version 0.1-beta. It may change in the future!
In the code snippets below, replace:
spritewith yourSpritevariable,stagewith yourStagevariable,otherSpritewith anotherSpritevariable,"spriteId"with the sprite’s ID string,cloneIdwith anintrepresenting the clone ID (often0for the original).
| Scratch block | Sparkle API equivalent | Notes / Beginner tips |
|---|---|---|
Motion | ||
sprite.moveSteps(10); |
Moves the sprite forward by 10 steps in its current direction. | |
sprite.rotateRight(15); |
Rotates the sprite clockwise by 15 degrees. | |
sprite.rotateLeft(15); |
Rotates the sprite counter‑clockwise by 15 degrees. | |
double halfWidth = stage.getWidth() / 2d;
double halfHeight = stage.getHeight() / 2d;
sprite.goTo(
Constants.RANDOM.nextDouble(-halfWidth, halfWidth),
Constants.RANDOM.nextDouble(-halfHeight, halfHeight)
);
|
Picks a random X and Y within the stage and moves the sprite there. What's going on here? We first compute half the stage width/height so we can pick positions from negative to positive values. Constants.RANDOM.nextDouble(min, max) gives a random number between those bounds.
| |
sprite.copyPos(otherSprite); |
Copies the position (X and Y) from otherSprite to this sprite. |
|
| No direct equivalent; working on that 😅 | Mouse position isn’t exposed yet in the core API. | |
sprite.goTo(48, 36); |
Sets the sprite’s position to X=48, Y=36. | |
double halfWidth = stage.getWidth() / 2d;
double halfHeight = stage.getHeight() / 2d;
sprite.glide(
Constants.RANDOM.nextDouble(-halfWidth, halfWidth),
Constants.RANDOM.nextDouble(-halfHeight, halfHeight),
1000
);
|
Glides smoothly to a random position over 1000 ms (1 second). The last argument is time in milliseconds. |
|
sprite.glideTo(otherSprite, 1000); |
Glides to the position of otherSprite over 1000 ms.Why milliseconds? Java and Sparkle use smaller time units so you can be more precise. 1000 ms = 1 second. |
|
| No direct equivalent yet | Mouse pointer position isn’t available in the core API right now. | |
sprite.goTo(48, 36, 1000); |
Glides to X=48, Y=36 over 1000 ms. The third argument is the duration in milliseconds. | |
sprite.setDirection(90); |
Sets the sprite’s direction to 90° (straight up in Scratch coordinates). | |
| No direct equivalent yet | Pointing toward the mouse isn’t implemented in the core API yet. | |
sprite.pointTowards(otherSprite); |
Makes the sprite face otherSprite. |
|
sprite.setDirection(Constants.RANDOM.nextDouble(0, 360)); |
Sets a random direction between 0° and 360°. This isn’t a standard Scratch block, but it’s easy to do in code. |
|
sprite.changeX(10); |
Adds 10 to the sprite’s X coordinate. | |
sprite.setX(48); |
Sets the sprite’s X coordinate to 48. | |
sprite.changeY(10); |
Adds 10 to the sprite’s Y coordinate. | |
sprite.setY(36); |
Sets the sprite’s Y coordinate to 36. | |
sprite.bounce(); |
Important: sprite.bounce() doesn’t check whether the sprite is actually at the edge. The edge detection is a separate operation; we’re still working on it.
|
|
sprite.setRotationMode(RotationMode.LEFT_RIGHT); |
Sprite flips horizontally when turning left/right, but doesn’t rotate around its center. What’s going on here? In Java, we pass an enum constant ( RotationMode.LEFT_RIGHT) to tell the sprite how to behave when it changes direction.
|
|
sprite.setRotationMode(RotationMode.NO_ROTATION); |
Sprite keeps facing the same way no matter what direction it moves. | |
sprite.setRotationMode(RotationMode.ALL_AROUND); |
Sprite rotates fully around its center when changing direction. | |
sprite.setRotationMode(RotationMode.UP_DOWN); |
This mode comes from PenguinMod and is not available in vanilla Scratch. It behaves like “left-right” but vertically. |
|
sprite.setRotationMode(RotationMode.LOOK_AT); |
This mode comes from PenguinMod and is not available in Scratch. It rotates the sprite to face the current direction, but flips it vertically when facing left-ish directions — so the sprite always appears upright, like it's "looking" somewhere instead of going upside down. |
|
sprite.getX() |
Returns the current X coordinate as a number. Important: This is an expression, not a statement, so you usually use it inside something else (e.g., double x = sprite.getX();), not on its own with a semicolon as a command.
|
|
sprite.getY() |
Returns the current Y coordinate as a number. | |
sprite.getDirection() |
Returns the sprite’s current direction in degrees (0–360). | |
Looks | ||
sprite.sayFor("Hello!", 2000); |
Shows a speech bubble with “Hello!” for 2000 ms (2 seconds). Beginner tip: Text in Java must be in double quotes ( "Hello!"). Single quotes are for single characters only.Right now, text bubbles exist as data but aren’t rendered — we’re working on that. |
|
sprite.say("Hello!"); |
Shows a speech bubble until something else changes it. | |
sprite.thinkFor("Hmm...", 2000); |
Shows a thought bubble for 2000 ms. | |
sprite.think("Hmm..."); |
Shows a thought bubble until changed. | |
sprite.setCostume("costume1"); |
Switches the sprite to the costume named “costume1”. Make sure the name matches exactly (case-sensitive). | |
sprite.incrementCostume(); |
Moves to the next costume in the list. If it’s already on the last one, it wraps to the first. | |
stage.setBackdrop("backdrop1"); |
Backdrops belong to the Stage, not the sprite.Use your stage variable here.
|
|
stage.setBackdrop("backdrop1", true); |
The second argument true means “wait” before continuing the code. |
|
stage.incrementBackdrop(); |
Switches to the next backdrop on the stage. | |
sprite.changeSize(10); |
Changes the sprite’s size by 10%. Positive makes it bigger, negative smaller. | |
sprite.setSize(100); |
Sets the sprite’s size to 100% (normal size). | |
sprite.setStretchX(100); sprite.setStretchY(50); |
Sets horizontal and vertical stretch independently. This comes from the TurboWarp “Stretch” extension and isn’t in vanilla Scratch. |
|
sprite.changeStretchX(10); sprite.changeStretchY(5); |
Increases horizontal stretch by 10 and vertical by 5. From TurboWarp Stretch extension. | |
sprite.setStretchX(100); |
Sets horizontal stretch to 100%. From TurboWarp Stretch extension. | |
sprite.setStretchY(100); |
Sets vertical stretch to 100%. From TurboWarp Stretch extension. | |
sprite.changeStretchX(10); |
Increases horizontal stretch by 10. From TurboWarp Stretch extension. | |
sprite.changeStretchY(10); |
Increases vertical stretch by 10. From TurboWarp Stretch extension. | |
sprite.getGraphicEffects().increment(GraphicEffect.HUE_SHIFT, 45); |
Scratch’s “color” effect uses a 0–200 scale; Sparkle uses degrees (0–360). To convert: 25 * (360 / 200) = 45. So we use 45 here.What’s going on? We get the effects object ( getGraphicEffects()) and tell it to increase the hue shift by 45 degrees.
|
|
sprite.getGraphicEffects().put(GraphicEffect.HUE_SHIFT, 0); |
Sets the hue shift to 0 degrees (no color shift). | |
sprite.getGraphicEffects().increment(GraphicEffect.BULGE, 25); |
Note: The BULGE effect doesn’t work properly yet. | |
sprite.getGraphicEffects().put(GraphicEffect.BULGE, 0); |
Note: BULGE effect isn’t working reliably yet. | |
sprite.getGraphicEffects().increment(GraphicEffect.WHIRL, 25); |
Note: WHIRL effect isn’t working properly yet. | |
sprite.getGraphicEffects().put(GraphicEffect.WHIRL, 0); |
Note: WHIRL effect isn’t working reliably yet. | |
sprite.getGraphicEffects().increment(GraphicEffect.PIXELATION, 25); |
Note: PIXELATION effect isn’t working properly yet. | |
sprite.getGraphicEffects().put(GraphicEffect.PIXELATION, 0); |
Note: PIXELATION effect isn’t working reliably yet. | |
sprite.getGraphicEffects().increment(GraphicEffect.MOSAIC, 25); |
Note: MOSAIC effect isn’t working properly yet. | |
sprite.getGraphicEffects().put(GraphicEffect.MOSAIC, 0); |
Note: MOSAIC effect isn’t working reliably yet. | |
sprite.getGraphicEffects().increment(GraphicEffect.BRIGHTNESS, 25); |
Increases brightness by 25 units. | |
sprite.getGraphicEffects().put(GraphicEffect.BRIGHTNESS, 0); |
Resets brightness to normal (0). | |
sprite.getGraphicEffects().increment(GraphicEffect.FADE, 25); |
Increases the “fade” (transparency) effect by 25 units. Higher values make the sprite more transparent. | |
sprite.getGraphicEffects().put(GraphicEffect.FADE, 0); |
Resets the fade effect to 0 (fully visible). | |
sprite.getGraphicEffects().clear(); |
Removes all graphic effects at once (color, fade, brightness, etc.) and resets them to default. | |
sprite.setVisible(true); |
Makes the sprite visible on screen. true is a boolean value meaning "yes". |
|
sprite.setVisible(false); |
Hides the sprite. false is a boolean value meaning "no". |
|
stage.moveToFrontLayer(new SpriteID("spriteId", cloneId)); |
Layers are managed by the Stage, not the sprite itself.What's going on? We create a SpriteID (a pair of sprite name + clone ID) to tell the stage which sprite we mean. The clone ID is an int — the original sprite's clone ID is always 0.
|
|
stage.moveToBackLayer(new SpriteID("spriteId", cloneId)); |
Sends the sprite to the very back layer. Same idea as above — the stage handles it. | |
stage.moveByLayers(new SpriteID("spriteId", cloneId), 1); |
Moves the sprite forward (toward the viewer) by 1 layer. Use a larger number to jump more layers. | |
stage.moveByLayers(new SpriteID("spriteId", cloneId), -1); |
Moves the sprite backward (away from the viewer) by 1 layer. Negative numbers go backward. | |
sprite.getCostumeIndex() |
Returns the current costume's number (index). This is an expression, not a statement. | |
sprite.getCostumeName() |
Returns the current costume's name as text (a String). |
|
stage.getBackdropIndex() |
Returns the current backdrop's number. Note that backdrops belong to a Stage instance, not a sprite. |
|
stage.getBackdropName() |
Returns the current backdrop's name as text. | |
| No direct equivalent |
In Sparkle, a sprite's size isn't stored as a single number — it can have separate X stretch and Y stretch. If you're sure both are always equal, you can query either sprite.getStretchX() or sprite.getStretchY() instead.
|
|
sprite.getStretchX() |
Returns the horizontal stretch value. From TurboWarp Stretch extension., not in vanilla Scratch. | |
sprite.getStretchY() |
Returns the vertical stretch value. From TurboWarp Stretch extension., not in vanilla Scratch. | |
Sound | ||
sprite.startSound("meow", true); |
Plays the sound "meow" and waits for it to finish before continuing. The second argument true means "wait until done". Pass false (or omit it) to keep running your code while the sound plays.
|
|
sprite.startSound("meow"); |
Starts playing "meow" without waiting for it to finish — your code keeps running immediately. | |
| No direct equivalent |
Scratch's "stop all sounds" is a blanket stop. In Sparkle, startSound(...) returns a sound ID — you collect those IDs and stop individual sounds yourself. This gives you more control but requires a bit more code.
|
|
sprite.getSoundEffects().increment(SoundEffect.PITCH, 10); |
Increases the pitch effect by 10. What's going on? getSoundEffects() returns the sound-effects object for this sprite. Then we call increment on it to change one specific effect.
|
|
sprite.getSoundEffects().increment(SoundEffect.PAN, 10); |
Shifts the sound's left/right balance by 10. Positive values pan right, negative pan left. | |
sprite.getSoundEffects().put(SoundEffect.PITCH, 100); |
Sets pitch to an exact value of 100. Use put to set (not change) an effect. |
|
sprite.getSoundEffects().put(SoundEffect.PAN, 100); |
Sets the pan to an exact value of 100. | |
sprite.getSoundEffects().decrement(SoundEffect.VOLUME, 10); |
Lowers the volume by 10. decrement is the opposite of increment — it subtracts.Note: In Sparkle, VOLUME is just another sound effect, not a separate property. This is different from Scratch.
|
|
sprite.getSoundEffects().put(SoundEffect.VOLUME, 100); |
Sets the volume to 100. Since volume is a sound effect, we use put just like other effects. |
|
sprite.getSoundEffects().clear(); |
Resets all sound effects to default. Important: This also resets volume, since volume is a sound effect in Sparkle! |
|
sprite.getSoundEffects().getDouble(SoundEffect.VOLUME) |
Returns the current volume as a number (double).This is an expression — use it inside something else, not as a standalone statement. |
|
Events | ||
Global.when(StartEvent.class, e -> {
// your code...
});
|
Runs your code when the game starts (like clicking the green flag in Scratch). What's going on? Global.when(...) registers an event handler. It says: "When a StartEvent happens, run this code." The e -> { ... } part is a lambda — a short way to pass code as an argument in Java.This is not the only way to register handlers — see the Global and EventDispatcher classes for more options.
|
|
Global.when(KeyboardEvent.KeyPressedEvent.class, e -> {
if (e.key() == Key.SOME_KEY) {
// your code...
}
});
|
Runs code when a key is pressed. Replace Key.SOME_KEY with the actual key you want (e.g., Key.SPACE, Key.UP, etc.). The if inside checks which key was pressed — one handler fires for any key, so you need to filter.
|
|
Global.when(MouseEvent.MouseClickedEvent.class, e -> {
if (GraphicsUtils.getTargetObject(e) instanceof SpriteID(String thatId, int _) && "spriteId".equals(thatId)) {
// your code...
}
});
|
Runs code when the user clicks this sprite. What's going on? When a click happens, we check whether the clicked object is a sprite with our ID. The instanceof SpriteID(String thatId, int _) part is Java's pattern matching — it checks the type and extracts the ID at the same time. The _ means "we don't care about the clone ID here."
|
|
Global.when(MouseEvent.MouseClickedEvent.class, e -> {
if (GraphicsUtils.getTargetObject(e) == null) {
// your code...
}
});
|
Runs code when the user clicks the stage background (not a sprite). When getTargetObject(e) returns null, it means no sprite was clicked — so it must have been the stage.
|
|
Global.when(BackdropChangeEvent.After.class, e -> {
if (e.newBackdropId() == stage.getAssets().texturesIndexesByName().getInt("backdrop1")) {
// your code...
}
});
|
Runs code after the backdrop changes to a specific one. The code checks whether the new backdrop's ID matches the one we want ("backdrop1"). It looks up the backdrop by name and compares its numeric ID. |
|
| No direct equivalent | Microphone access (loudness sensing) is planned for a separate extension module — it won't be in the core framework. | |
| No direct equivalent | Sparkle doesn't have a built-in timer that auto-starts. You can create one yourself using the Stopwatch classes. |
|
Global.when(MessageEvent.class, e -> {
if (e.messageId().equals("message1")) {
// your code...
}
});
|
Runs code when a broadcast message is received. The if check filters by message name — one handler fires for any message, so you need to check which one arrived.
|
|
Global.fire(new MessageEvent("message1")); |
Sends a message to all listeners. Code continues immediately — it doesn't wait for receivers to finish. | |
Global.fireAndWait(new MessageEvent("message1")); |
Sends a message and waits until all receivers finish before continuing. Use this when you need receivers to complete first. | |
Control | ||
WaitUtils.waitFor(1000); |
Pauses your code for 1000 milliseconds (1 second). Remember: Always specify time in milliseconds! 1 second = 1000 ms, 0.5 seconds = 500 ms, etc. |
|
for (int i = 0; i < 10; i++) {
// your code...
}
|
This is a standard Java for loop — it runs the code inside { } exactly 10 times.Beginner tip: int i = 0 creates a counter, i < 10 means "keep going while i is less than 10", and i++ adds 1 to i each time. Change 10 to however many times you need.
|
|
while (true) {
// your code...
}
|
A while (true) loop runs forever because true is always true.Note: The actual implementation depends on context. For example, for a game loop, you should use a TickEvent handler instead — it's controllable by the framework. |
|
if (something) {
// your code...
}
|
Runs the code only if something is true.Replace something with a condition, e.g., sprite.getX() > 100 or sprite.getCostumeName().equals("jump").
|
|
if (something) {
// code if true...
} else {
// code if false...
}
|
Runs one block if the condition is true, and a different block if it's false. | |
WaitUtils.waitUntil(() -> something); |
Keeps waiting until something becomes true, then continues.What's the () -> part? It's a lambda — a short function that gets re-evaluated each check. If you just wrote WaitUtils.waitUntil(something) without the lambda, Java would evaluate something only once. If it was false at that moment, your program would freeze forever.
|
|
WaitUtils.waitForOrUntil(() -> something, 1000); |
Waits until either the condition becomes true OR 1000 ms passes — whichever comes first. This block comes from PenguinMod and is not available in vanilla Scratch. |
|
while (!something) {
// your code...
}
|
Keeps running the code while the condition is not true yet. The ! (exclamation mark) before the expression means "not" — it flips true to false and vice versa. So while (!something) means "keep looping while something is false."
|
|
while (something) {
// your code...
}
|
Keeps looping while the condition is true. This block isn't in vanilla Scratch but works in Scratch mods like TurboWarp. |
|
stage.stop(); return; |
Stopping depends on context. To stop a specific Stage: stage.stop();To stop the entire program (closes all windows): System.exit(0);The return; exits the current method so no more code runs after stopping.
|
|
return; |
Exits the current method immediately — no more code in this method runs. Beginner tip: In Java, return means "leave this method now." It's the closest equivalent to stopping a single script.
|
|
| No direct equivalent | In Sparkle, sprites don't store code, and managing multiple running scripts is up to your application. This Scratch block doesn't have a direct equivalent. | |
| No direct equivalent |
In Sparkle, sprites don't hold code and no event fires when a clone is created. Instead, when you create a clone, you get the clone's Sprite instance back — you can customize it right there.
|
|
int cloneId = stage.createClone("spriteId");
Sprite cloneSprite = stage.getSprite("spriteId", cloneId);
|
Creates a clone and gives you access to it. Line 1: creates the clone, returns its clone ID. Line 2: gets the Sprite object for that clone so you can manipulate it.Note: The clone starts on the front layer in Sparkle (in Scratch it starts at the back). |
|
stage.deleteAllClones("spriteId"); |
Deletes all clones of the specified sprite. From PenguinMod, not in vanilla Scratch. | |
stage.deleteClone("spriteId", cloneId); |
Deletes one specific clone, identified by its sprite ID and clone ID. | |
cloneId != 0 |
!= means "not equal to". The original sprite has clone ID 0, so if the clone ID is not 0, it's a clone. From PenguinMod, not in vanilla Scratch.
|
|
Sensing | ||
| No direct equivalent yet | Mouse pointer collision detection isn't available in the core API yet. | |
| Too complex | Edge and sprite collision detection is possible in Sparkle, but it requires too much setup code to show here. Working on simplifying it! | |
| Too complex | ||
| Not possible yet | Can't read color data from the screen yet — this feature is still being worked on. | |
| Not possible yet | ||
| No direct equivalent yet | Mouse position isn't available in the core API yet. | |
Math.hypot(sprite.getX() - otherSprite.getX(), sprite.getY() - otherSprite.getY()) |
Calculates the straight-line distance between two sprites. What's going on? Math.hypot(a, b) computes sqrt(a*a + b*b) — the Pythagorean theorem. Here, a is the difference in X and b is the difference in Y.
|
|
| No direct equivalent | Text input ("ask and wait") is planned for a UI extension module — it won't be in the core framework. | |
| No direct equivalent | ||
| No direct equivalent yet | Checking whether a key is currently held down isn't available in the core API yet. | |
| No direct equivalent yet | Checking whether the mouse button is held down isn't available yet. | |
| No direct equivalent yet | Mouse position isn't exposed in the core API yet. | |
| No direct equivalent yet | Mouse position isn't exposed in the core API yet. | |
| No direct equivalent | Scratch's dragging system doesn't let you customize how the sprite follows the cursor. In Sparkle, if you need dragging, you implement it yourself in your app. Most applications don't need it. | |
| No direct equivalent | Microphone access is planned for a separate extension module, not the core. | |
| No direct equivalent |
Sparkle doesn't start a timer automatically like Scratch does. You can create your own using the Stopwatch classes when you need timing.
|
|
stage.getBackdropIndex() |
Returns the current backdrop's number on the stage. | |
stage.getBackdropName() |
Returns the current backdrop's name as text. | |
100 |
The stage doesn't have sound effects (at least for now), so its volume is always 100. | |
stage.getVariable("my variable").getValue() |
Gets the value of a variable stored on the stage. You might want to use a different method than getValue() if it's a primitive variable (e.g., getDoubleValue(), getIntValue()).
|
|
sprite.getX() |
Returns the sprite's X coordinate. | |
sprite.getY() |
Returns the sprite's Y coordinate. | |
sprite.getDirection() |
Returns the sprite's current direction in degrees. | |
sprite.getCostumeIndex() |
Returns the sprite's current costume number. | |
sprite.getCostumeName() |
Returns the sprite's current costume name as text. | |
| No direct equivalent | Same as "Size" above — Sparkle uses separate X/Y stretch instead of a single size value. | |
sprite.getSoundEffects().getDouble(SoundEffect.VOLUME) |
Returns the sprite's volume. Since volume is a sound effect in Sparkle, we read it through getSoundEffects(). |
|
sprite.getVariable("private variable").getValue() |
Gets a variable stored on this sprite. As with stage variables, you might use a different method than getValue() for primitive types. |
|
LocalDate.now().getYear() |
Returns the current year (e.g., 2026). These use Java's built-in java.time package. There may be better options depending on your needs — check the java.time documentation.
|
|
LocalDate.now().getMonthValue() |
Returns the current month as a number (1–12). | |
LocalDate.now().getDayOfMonth() |
Returns the current day of the month (1–31). | |
Math.floorMod(LocalDate.now().toEpochDay() + 5, 7) |
Returns the day of the week as a number (0 = Sunday, 1 = Monday, etc.). What's going on? toEpochDay() counts days since 1970-01-01 (a Thursday). Adding 5 and taking floorMod by 7 shifts it so Sunday = 0.
|
|
LocalTime.now().getHour() |
Returns the current hour (0–23). | |
LocalTime.now().getMinute() |
Returns the current minute (0–59). | |
LocalTime.now().getSecond() |
Returns the current second (0–59). | |
Duration.between(LocalDateTime.of(2000, 1, 1, 0, 0), LocalDateTime.now()).toNanos() / 86400000000000d |
Calculates the number of days since January 1, 2000. Tip: In Scratch this is often used to measure elapsed time. In Java, it's usually better to use the Duration class directly for measuring time spans — no need to convert to "days since 2000" first.
|
|
| No direct equivalent | Sparkle is a graphics framework, not an account system. If your app needs usernames, you implement that yourself. | |
Operators | ||
expr1 + expr2 |
Adds two numbers. Replace expr1 and expr2 with your numeric expressions. |
|
expr1 - expr2 |
Subtracts the second number from the first. | |
expr1 * expr2 |
Multiplies two numbers. In Java, the multiplication sign is *. |
|
(double) expr1 / expr2 |
Divides two numbers. Why (double)? In Java, dividing two integers gives you a whole-number result (e.g., 7 / 2 gives 3, not 3.5). Adding (double) in front forces "real number" division so you get 3.5. Remove it if you actually want integer division.
|
|
Constants.RANDOM.nextDouble(expr1, expr2) |
Picks a random number between expr1 and expr2. The result includes both endpoints. |
|
expr1 > expr2 |
Returns true if the first value is greater than the second, false otherwise. |
|
expr1 < expr2 |
Returns true if the first value is less than the second. |
|
expr1 == expr2 |
Returns true if both values are equal.Important: == checks if two things are the same object in memory. For comparing text or other objects by their content, use .equals() instead (e.g., sprite.getCostumeName().equals("jump")).
|
|
expr1 && expr2 |
Returns true only if both conditions are true. && is Java's "and" operator. Both expressions must be boolean (true/false).
|
|
expr1 || expr2 |
Returns true if either condition is true. || is Java's "or" operator. |
|
!expr |
Flips a boolean value: true becomes false, false becomes true. The ! is Java's "not" operator.
|
|
String.valueOf(expr1) + String.valueOf(expr2) |
Joins two values together as text. String.valueOf(...) converts anything to text first, then + concatenates them.Here, expr1 and expr2 can be of any type (numbers, text, etc.).
|
|
String.valueOf(expr2).charAt(expr1) |
Gets a single character at position expr1 from the text expr2.Remember: Java counts from 0, so the first character is at index 0 (unlike Scratch, where it's 1). ⚠️ Important for emojis & special symbols: This method only works reliably for basic letters and numbers. Some symbols (like many emojis) are “double-width” internally, so charAt might give you half a symbol or the wrong character.If you need to safely handle those, use: Character.toString(String.valueOf(expr2).codePointAt(expr1)). Note: this returns a String (text), not a char (single character), so treat it as text in your code.
|
|
String.valueOf(expr).length() |
Returns the number of characters in the text. expr can be any type — it gets converted to text first. |
|
String.valueOf(expr1).contains(String.valueOf(expr2)) |
Returns true if expr1 (as text) contains expr2 (as text) somewhere inside it.Both can be any type — they're converted to text first. |
|
expr1 % expr2 |
Returns the remainder of dividing expr1 by expr2. The % symbol is Java's "modulo" operator.Example: 10 % 3 gives 1 (because 10 ÷ 3 = 3 with remainder 1).
|
|
Math.round(expr) |
Rounds a number to the nearest whole number. E.g., Math.round(3.7) gives 4. |
|
Math.abs(expr) |
Returns the absolute (positive) value. Math.abs(-5) gives 5. |
|
Math.floor(expr) |
Rounds down to the nearest whole number. Math.floor(3.9) gives 3.0. |
|
Math.ceil(expr) |
Rounds up to the nearest whole number. Math.ceil(3.1) gives 4.0. |
|
Math.sqrt(expr) |
Returns the square root. Math.sqrt(9) gives 3.0. |
|
Math.sin(expr) |
Returns the sine. Note: Java uses radians, not degrees! To convert degrees to radians: multiply by Math.PI / 180. |
|
Math.cos(expr) |
Returns the cosine. Same as above — Java uses radians. | |
Math.tan(expr) |
Returns the tangent. Also in radians. | |
Math.asin(expr) |
Returns the arc sine (inverse of sine). Result is in radians. | |
Math.acos(expr) |
Returns the arc cosine. Result is in radians. | |
Math.atan(expr) |
Returns the arc tangent. Result is in radians. | |
Math.log(expr) |
Returns the natural logarithm (log base e). Not to be confused with Math.log10. |
|
Math.log10(expr) |
Returns the logarithm base 10. | |
Math.exp(expr) |
Returns e raised to the given power. The inverse of Math.log. |
|
Math.pow(10, expr) |
Returns 10 raised to the given power. The inverse of Math.log10. |
|
Variables | ||
To create a variable or list, call | ||
See the classes in the | ||
target.getVariable("my variable").getValue() |
Gets the current value of a variable. Replace target with your sprite or stage variable. You might want a different method than getValue() for primitive variables (e.g., getDoubleValue()).
|
|
target.getVariable("my variable").setValue(expr); |
Sets the variable to a new value. expr must be the same type as the variable (e.g., a number variable needs a number).As above, you might use a different method for primitive types. |
|
Variable<Type> v = target.getVariable("my variable");
v.setDoubleValue(v.getValueAsDouble() + 1);
|
Increases the variable by 1 (like Scratch's "change by 1"). Replace Type with the variable's actual type (e.g., Double). This only works for numeric variables. Line 1 gets the variable, line 2 reads its current value, adds 1, and writes it back.
|
|
| No direct equivalent | Showing/hiding variables on screen is planned for a UI extension module — it won't be in the core framework. | |
| No direct equivalent | ||
Lists | ||
Common first step: Get the list object with List<Type> list = target.<List<Type>>getVariable("my list").getValue();, where Type is the type of elements in the list. Then use the methods below. | ||
list.add(expr); |
Adds a new item to the end of the list. expr must match the list's element type. |
|
list.remove(0); |
Removes the item at position 0 (the first item). Important: Java lists start at index 0, not 1 like Scratch. So "item 1" in Scratch is list.get(0) in Java.
|
|
list.clear(); |
Removes all items from the list. | |
list.add(0, expr); |
Inserts a new item at position 0, pushing everything else to the right. | |
list.set(0, expr); |
Replaces the item at position 0 with a new value. The old value is gone. | |
list.get(0) |
Returns the item at position 0 without removing it. This is an expression, not a statement. | |
list.indexOf(expr) |
Returns the position of the first matching item, or -1 if not found. Remember: positions start at 0 in Java. | |
list.size() |
Returns how many items are in the list. | |
list.contains(expr) |
Returns true if the list has an item equal to expr, false otherwise. |
|
| No direct equivalent | Showing/hiding lists on screen is planned for a UI extension module — not in the core framework. | |
| No direct equivalent | ||
My Blocks | ||
Java has a similar feature — methods. You define a method once, then call it from anywhere in your code. | ||
| Run without screen refresh |
GraphicsUtils.runWithoutStageRedraw(stage, () ->
// your code...
);
|
Runs your code without updating the screen while it executes — the screen only updates when the code finishes. In Scratch this is only available for custom blocks, but in Sparkle you can do it anywhere. |