App startup

Runs once before content creation. Configure the initial window here.

void settings()

Example

@Override
public void settings() {
    size(800, 500);
    title("My app");
}

Override this callback. Call size, title and optional padding here.

Runs once after content creation, before the window is shown. Create controls and call show here.

void setup()

Example

@Override
public void setup() {
    show(new Label("Hello"));
}

Override this callback. On GameApp the canvas already exists. An uncaught startup error stops owned activity and preserves its cause.

update()

GameApp

Runs before draw() while gameplay is visible and not explicitly paused. Update your state and objects explicitly. Default: no action.

void update(double seconds)
seconds
Elapsed seconds; non-negative and finite. GameApp supplies first 0, then at most 0.1.

Example

@Override
public void update(double seconds) {
    x += 100 * seconds;
}

While gameplay is visible and not explicitly paused. The example assumes a double field named x. First-frame seconds is 0; later values are capped at 0.1.

draw()

GameApp

Runs while gameplay is visible, after update() when not paused. Draw the current state. Default: no action.

void draw()

Example

@Override
public void draw() {
    background(Color.WHITE);
    circle(100, 80, 40);
}

Runs only while gameplay is visible, including during explicit pause. The canvas is not cleared automatically. Drawing styles persist between frames. An uncaught game-frame error stops owned activity and preserves its cause.

More about app startup

public abstract class App extends javafx.application.Application

Extend zero.App for event-driven interfaces. It has an implicit public no-argument constructor. The default window is resizable, 800 × 500 pixels, with title "Zero" and zero content-edge padding. Use zero.ui.Element for normal Zero UI content. JavaFX Node from javafx.scene remains an advanced bridge.

Normal Run builds and opens a native JavaFX window. Publishing for the browser checks the supported Java/JavaFX subset; unsupported calls produce source diagnostics. Availability in native JavaFX does not imply browser support. See running and browser compatibility.

An uncaught startup, game update/draw or UI callback error stops the app's owned loop, input and audio, preserving the original error and any cleanup failures. Managed runs report readiness and local errors; opening a window alone does not prove a successful game frame. Pause and title screens are valid states.

Override these public methods. Their default bodies do nothing.

public abstract class GameApp extends App

Extend zero.GameApp for animation and canvas input. It has an implicit public no-argument constructor and inherits all App public methods above. Its canvas exists before setup(). It starts frames after showing the window.

The first frame receives 0 seconds; later elapsed times are capped at 0.1. Frame rate is variable. While gameplay is visible, draw continues during an explicit pause, but update is skipped. Navigating away with show suspends both callbacks. The canvas is not automatically cleared; drawing styles persist. Resizing the window does not scale its fixed canvas. Native controls around the canvas can enlarge the initial window.

Window and interface

Set initial content dimensions in pixels, inside settings() only. Dimensions must be positive and finite. On GameApp, these are fixed canvas dimensions.

void size(double width, double height)
width
Initial content width in pixels; positive and finite.
height
Initial content height in pixels; positive and finite.

Example

size(800, 500);

Call inside settings() only. Dimensions must be positive and finite.

Set a non-null initial window title, inside settings() only.

void title(String title)
title
Initial window title; must not be null.

Example

title("My app");

Call inside settings() only. The title must not be null.

Set space around all four content edges in settings(), setup() or later JavaFX handlers. The number must be non-negative and finite. Default: 0. GameApp keeps its fixed canvas size.

void padding(double pixels)
pixels
Space around each content edge in pixels; non-negative and finite.

Example

padding(20);

Inherited by GameApp from App. Call in settings(), setup() or a JavaFX event handler. The default is 0; padding(0) removes it and repeated calls replace the amount. GameApp keeps its canvas dimensions. Later calls rearrange content without resizing the window.

Replace the root's centre with a non-null Zero element in setup() or later. On GameApp, navigate away from its retained canvas/HUD and suspend gameplay update, draw and canvas input until showGame(). No history stack is stored.

void show(zero.ui.Element content)
content
Non-null Zero element; uses ordinary JavaFX node ownership.

Example

show(new zero.ui.Column(new zero.ui.Label("Ready")));

Inherited by GameApp. Navigating away suspends gameplay update, draw and canvas input. showGame returns to the retained canvas/HUD. Frame requests commit after the current draw; idle UI callbacks commit immediately.

Replace the root's centre with a non-null JavaFX node, in setup() or later. No screen history is stored. On GameApp this navigates away from the retained canvas/HUD and suspends gameplay update, draw and canvas input until showGame().

void show(Node content)
content
JavaFX node to display; must not be null.

Example

show(new Label("Hello"));

On GameApp, suspends gameplay update, draw and canvas input while another view is shown. showGame restores the retained canvas/HUD. Requests during a frame commit after its successful draw.

More about window and interface

These methods are public and final; call them without overriding them.

size and title throw IllegalStateException outside settings(); invalid dimensions or padding throw IllegalArgumentException. show throws IllegalStateException before content creation. Null title/content throws NullPointerException. size and title do not change an already-open window.

GameApp inherits padding from App. padding(20) sets 20 pixels on every edge; repeated calls replace the amount, and padding(0) removes it. Invalid padding leaves the previous amount unchanged. App keeps its configured initial window content size, leaving less room for controls. GameApp's initial window includes padding around its fixed canvas and controls; canvas dimensions and drawing coordinates stay unchanged. Later padding changes rearrange content within the current window without resizing it.

Game flow

showGame()

GameApp

Return to the retained gameplay canvas and HUD, clearing input and elapsed time. Preserve explicit pause state.

void showGame()

Example

showGame();

Unreleased GameApp navigation/pause addition. Main owns game state and view choices; no zero.Screen class or automatic screen lifecycle exists. Call in setup or later on the JavaFX application thread.

pause()

GameApp

Explicitly pause gameplay updates. Visible gameplay still draws and UI callbacks still run.

void pause()

Example

pause();

Unreleased GameApp navigation/pause addition. Main owns game state and view choices; no zero.Screen class or automatic screen lifecycle exists. Call in setup or later on the JavaFX application thread.

resume()

GameApp

Clear explicit pause, input and elapsed time. Resume gameplay updates only when gameplay is visible.

void resume()

Example

resume();
showGame();

Unreleased GameApp navigation/pause addition. Main owns game state and view choices; no zero.Screen class or automatic screen lifecycle exists. Call in setup or later on the JavaFX application thread.

isPaused()

GameApp

Read whether gameplay has been explicitly paused.

boolean isPaused()

Example

boolean paused = isPaused();

Unreleased GameApp navigation/pause addition. Main owns game state and view choices; no zero.Screen class or automatic screen lifecycle exists. Call in setup or later on the JavaFX application thread.

More about game flow

These GameApp methods are public and final. Call them on the JavaFX application thread in setup() or later UI/game callbacks. They require the game layout to exist and the app must not have stopped, or they throw IllegalStateException. The canvas and its controls panel are retained when show(Node) or show(Element) displays another view. showGame returns to that same gameplay view; it does not rebuild actors, reset scores or restart a level. Main owns those rules.

Navigation requested inside update or draw takes effect after the current draw, so the current update/draw pair finishes together. The last navigation request in that frame wins; a failed frame or app stop discards pending navigation. A request in an idle UI callback commits immediately. Navigation and pause/resume clear held and edge canvas input; returning with showGame or calling resume clears input and resets elapsed time so the next update gets 0 seconds, with no time accumulated while away. Explicit pause and navigation are separate: returning to gameplay preserves an explicit pause until resume is called. Native button callbacks remain available while paused or on another view. Game pause/navigation does not automatically pause music.

isPaused reports only the explicit pause flag, not whether another view is showing.

A title, help, pause or results screen can be an ordinary student class with a method returning an Element. There is no zero.Screen class, automatic screen lifecycle or navigation history in this API.

Zero UI

Element()

zero.ui.Element

Wrap a non-null JavaFX node in a custom Element subclass.

protected Element(Node node)
node
Non-null backing JavaFX node for advanced interoperability.

Example

public class ScoreDisplay extends Element {
    public ScoreDisplay() {
        super(new Label("Score: 0").fxNode());
    }
}

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setEnabled()

zero.ui.Element

Set this element's own enabled flag while preserving values and callbacks. False blocks interaction; true allows interaction unless an ancestor remains disabled. Inherited by Label, Button, TextField, Column and Row.

final void setEnabled(boolean enabled)
enabled
True to allow interaction unless an ancestor is disabled; false to disable this element while preserving its state.

Example

button.setEnabled(false); // Keep the action for later reuse

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

fxNode()

zero.ui.Element

Return the underlying JavaFX node for advanced interoperability. Inherited by Label, Button, TextField, Column and Row.

final Node fxNode()

Example

Node node = score.fxNode(); // Advanced JavaFX bridge

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Label()

zero.ui.Label

Create a text label.

Label(String text)
text
Non-null text to display.

Example

Label label = new Label("Score: 0");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getText()

zero.ui.Label

Read its current text.

String getText()

Example

String text = label.getText();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setText()

zero.ui.Label

Replace its text explicitly.

void setText(String text)
text
Non-null text to display.

Example

label.setText("Ready");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Button()

zero.ui.Button

Create a button with no click callback yet.

Button(String text)
text
Non-null text to display.

Example

Button button = new Button("Add point");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getText()

zero.ui.Button

Read its current text.

String getText()

Example

String text = button.getText();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setText()

zero.ui.Button

Replace its text explicitly.

void setText(String text)
text
Non-null text to display.

Example

button.setText("Ready");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

onClick()

zero.ui.Button

Replace the click callback with a non-null action.

void onClick(Runnable action)
action
Non-null Runnable action; replaces the previous click callback.

Example

button.onClick(() -> score.setScore(1));

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

TextField()

zero.ui.TextField

Create an empty single-line text field with an empty prompt.

TextField()

Example

TextField textfield = new TextField();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getText()

zero.ui.TextField

Read the current text, including edits typed by the user.

String getText()

Example

String text = textfield.getText();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setText()

zero.ui.TextField

Replace the text with a non-null string; an empty string removes entered text.

void setText(String text)
text
Non-null text to display.

Example

textfield.setText("Ready");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getPromptText()

zero.ui.TextField

Read the current prompt hint.

String getPromptText()

Example

String hint = textfield.getPromptText();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setPromptText()

zero.ui.TextField

Replace the prompt with a non-null string; this does not change entered text.

void setPromptText(String text)
text
Non-null text to display.

Example

textfield.setPromptText("Your name");

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Column()

zero.ui.Column

Create a vertical column with 8-pixel spacing and the supplied children in order.

Column(Element... children)
children
Elements in order; non-null, distinct and not already attached to a parent or scene.

Example

Column column = new Column(label, button);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Column()

zero.ui.Column

Create a vertical column with finite non-negative pixel spacing.

Column(double spacing, Element... children)
spacing
Vertical spacing in pixels; non-negative and finite.
children
Elements in order; non-null, distinct and not already attached to a parent or scene.

Example

Column column = new Column(12, label, button);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getSpacing()

zero.ui.Column

Read spacing in pixels.

double getSpacing()

Example

double gap = column.getSpacing();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setSpacing()

zero.ui.Column

Replace finite non-negative spacing; invalid values leave the old value unchanged.

void setSpacing(double spacing)
spacing
Vertical spacing in pixels; non-negative and finite.

Example

column.setSpacing(12);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Row()

zero.ui.Row

Create a horizontal row with 8-pixel spacing and the supplied children in order.

Row(Element... children)
children
Elements in order; non-null, distinct and not already attached to a parent or scene.

Example

Row row = new Row(label, button);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

Row()

zero.ui.Row

Create a horizontal row with finite non-negative pixel spacing.

Row(double spacing, Element... children)
spacing
Vertical spacing in pixels; non-negative and finite.
children
Elements in order; non-null, distinct and not already attached to a parent or scene.

Example

Row row = new Row(12, label, button);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

getSpacing()

zero.ui.Row

Read horizontal spacing in pixels.

double getSpacing()

Example

double gap = row.getSpacing();

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

setSpacing()

zero.ui.Row

Replace finite non-negative horizontal spacing; invalid values leave the old value unchanged.

void setSpacing(double spacing)
spacing
Vertical spacing in pixels; non-negative and finite.

Example

row.setSpacing(12);

Unreleased Zero UI addition. Use zero.ui imports; Label, Button, TextField, Column and Row inherit setEnabled(boolean) and fxNode() from Element. JavaFX remains available through the advanced bridge.

More about zero ui

public abstract class Element is the base for the small Zero UI layer. Import zero.ui.Element, zero.ui.Label, zero.ui.Button, zero.ui.TextField, zero.ui.Column and zero.ui.Row as needed. These are additional, unreleased APIs; existing JavaFX controls remain available. Use App.show(element) for an interface or GameApp.controls(element) for a live game HUD. Each element wraps one node and can belong to only one parent at a time. Create, change and mount elements on the JavaFX application thread (in setup or callbacks). A Column's children are supplied only in its constructor; there is no public add/remove/reparent API in this slice.

Elements start enabled. Call setEnabled(false) to block user interaction without removing the element or discarding its text, prompt or callback. setEnabled(true) clears the element's own disabled flag; a disabled ancestor still prevents its interaction. A disabled Column also disables interaction with its children; a child disabled separately remains disabled when the Column is enabled. The UI state reflects your app's rules. Keep rules such as whether an answer was already scored in ordinary Java fields rather than relying on a disabled button.

The protected constructor and fxNode are an advanced JavaFX interoperability bridge for custom elements, not a requirement for using Label/Button/TextField/Column. Subclasses wrap their own node or a newly created Column's node. Null backing nodes throw NullPointerException; the bridge exposes the actual node rather than a copy. Advanced code must preserve JavaFX ownership/thread rules.

public class Label extends Element displays text. Import zero.ui.Label. Text must be non-null; constructors/setters throw NullPointerException for null. It inherits fxNode() from Element.

public class Button extends Element is a clickable button. Import zero.ui.Button. It inherits fxNode(). Text and callbacks must be non-null or NullPointerException is thrown. The callback is an ordinary java.lang.Runnable: write button.onClick(() -> score.setScore(1)), with no event argument. Calling onClick again replaces the previous callback; it does not accumulate handlers.

public class TextField extends Element accepts one line of text. Import zero.ui.TextField. It inherits fxNode(). Text and prompt start empty. Read getText inside a Button.onClick callback to use the text entered at that moment. A prompt is a hint shown when the field is empty; it is not entered text. In the browser, focusing the empty field hides its hint; leaving it restores the hint. Typing and Tab navigation retain the native control's focus behavior. Both setters reject null with NullPointerException and keep the previous value. Use an empty string to remove text or a prompt. Create and change it in setup or UI callbacks on the application thread, like the other elements.

public class Column extends Element arranges child elements vertically. Import zero.ui.Column. It inherits fxNode(). The no-spacing constructor uses 8 pixels. Spacing must be finite and non-negative or IllegalArgumentException is thrown. Null children/child array throw NullPointerException; duplicate children or children whose nodes already have a parent or scene throw IllegalArgumentException. The complete list is validated before any child is attached. Children are fixed at construction; create fresh elements for a different composition instead of trying to attach one child to two parents. Empty columns are allowed.

public class Row extends Element arranges child elements horizontally. Import zero.ui.Row. It has the same ownership, availability and validation rules as Column: children must be distinct, non-null and unowned; validation completes before attachment. Children are fixed at construction. Empty rows are allowed. It inherits setEnabled(boolean) and fxNode().

Zero colours

WHITE

Color

Opaque white.

static final Color WHITE

Example

fill(zero.Color.WHITE);

Import zero.Color for this wrapper. Existing javafx.scene.paint.Color overloads remain available.

BLACK

Color

Opaque black.

static final Color BLACK

Example

fill(zero.Color.BLACK);

Import zero.Color for this wrapper. Existing javafx.scene.paint.Color overloads remain available.

BLUE

Color

Opaque blue.

static final Color BLUE

Example

fill(zero.Color.BLUE);

Import zero.Color for this wrapper. Existing javafx.scene.paint.Color overloads remain available.

GOLD

Color

Opaque gold.

static final Color GOLD

Example

fill(zero.Color.GOLD);

Import zero.Color for this wrapper. Existing javafx.scene.paint.Color overloads remain available.

rgb()

Color

Create an opaque colour from integer channels, each from 0 through 255.

static Color rgb(int red, int green, int blue)
red
Red channel, an integer from 0 through 255.
green
Green channel, an integer from 0 through 255.
blue
Blue channel, an integer from 0 through 255.

Example

fill(zero.Color.rgb(80, 120, 200));

Import zero.Color for this wrapper. Existing javafx.scene.paint.Color overloads remain available.

More about zero colours

public final class Color is a small colour value wrapper. Import zero.Color for these constants and rgb; the platform colour is private. It has no public constructor. Existing overloads taking javafx.scene.paint.Color remain available; the short Color type in their older drawing signatures below means JavaFX Color. The explicitly qualified zero.Color overloads take the new wrapper. Import only one Color class by its short name, or qualify the other where needed. Each rgb channel must be an integer from 0 through 255 inclusive; otherwise IllegalArgumentException is thrown.

Canvas

width()

GameApp

Canvas width in pixels.

double width()

Example

double middleX = width() / 2;

height()

GameApp

Canvas height in pixels.

double height()

Example

double middleY = height() / 2;

graphics()

GameApp

Native drawing context, including transforms and styles.

GraphicsContext graphics()

Example

graphics().strokeOval(20, 20, 80, 40);

controls()

GameApp

Mount a non-null Zero HUD/control panel at the bottom of the game layout in setup() or later, retaining the canvas and gameplay state. This does not navigate back or resume explicit pause. Replace the previous panel; do not steal nodes from another parent. Throws IllegalStateException before canvas creation, NullPointerException for null, and IllegalArgumentException for content owned by another parent or scene. Reusing the current bottom panel is allowed.

void controls(zero.ui.Element content)
content
Non-null Zero element; uses ordinary JavaFX node ownership.

Example

controls(new zero.ui.Column(new zero.ui.Label("Ready")));

Use for a live game HUD. Retains canvas and gameplay state; does not navigate or clear explicit pause. A different parent or scene is rejected; the current bottom panel can be mounted again.

draw()

GameApp

Draw a non-null actor explicitly through its existing draw(GameApp) entry point. The base Actor entry point provides a scoped local drawing callback; this never updates or registers the actor. Null actor throws NullPointerException; the base Actor entry point throws IllegalStateException before canvas creation.

void draw(Actor actor)
actor
Non-null Actor to draw explicitly; no update or registration.

Example

draw(player);

Calls the existing actor.draw(this) entry point to preserve legacy overrides. The base Actor entry point scopes the local draw() callback. Main owns update calls; no registration.

layout()

GameApp

Layout with the canvas in its centre. Add native controls to its other positions.

BorderPane layout()

Example

layout().setBottom(new Label("Score: 0"));
More about canvas

These GameApp methods are public and final. Call them in setup() or later, after canvas creation. Imports: javafx.scene.canvas.Canvas, javafx.scene.canvas.GraphicsContext, javafx.scene.layout.BorderPane.

Drawing

Clear and fill the entire canvas, restoring the previous styles and transform. Use the new Zero colour wrapper; null throws NullPointerException.

void background(zero.Color color)
color
Non-null zero.Color wrapper; distinct from javafx.scene.paint.Color.

Example

background(zero.Color.WHITE);

Unreleased Zero colour overload. Use import zero.Color, or the qualified name shown here.

Clear and fill the entire canvas using an identity transform, then restore the previous context styles and transform.

void background(Color color)
color
JavaFX Color to use.

Example

background(Color.WHITE);

fill()

GameApp

Set the fill for filled shapes and text. Use the new Zero colour wrapper; null throws NullPointerException.

void fill(zero.Color color)
color
Non-null zero.Color wrapper; distinct from javafx.scene.paint.Color.

Example

fill(zero.Color.BLUE);

Unreleased Zero colour overload. Use import zero.Color, or the qualified name shown here.

fill()

GameApp

Set the fill for filled shapes and text.

void fill(Color color)
color
JavaFX Color to use.

Example

fill(Color.BLUE);

stroke()

GameApp

Set the stroke for lines and outlines. Use the new Zero colour wrapper; null throws NullPointerException.

void stroke(zero.Color color)
color
Non-null zero.Color wrapper; distinct from javafx.scene.paint.Color.

Example

stroke(zero.Color.BLACK);

Unreleased Zero colour overload. Use import zero.Color, or the qualified name shown here.

Set line width.

void strokeWidth(double pixels)
pixels
Stroke width in pixels.

Example

strokeWidth(3);

textSize()

GameApp

Set a default JavaFX font at this size.

void textSize(double pixels)
pixels
Font size in pixels.

Example

textSize(24);

rect()

GameApp

Draw a filled rectangle with its top-left corner at x/y.

void rect(double x, double y, double width, double height)
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

rect(20, 30, 100, 60);

Draw a stroked rectangle with its top-left corner at x/y.

void outlineRect(double x, double y, double width, double height)
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

outlineRect(20, 30, 100, 60);

circle()

GameApp

Draw a filled circle centred at x/y with the supplied diameter.

void circle(double centreX, double centreY, double diameter)
centreX
Horizontal centre of the circle in pixels.
centreY
Vertical centre of the circle in pixels.
diameter
Circle diameter in pixels.

Example

fill(Color.BLUE);
circle(100, 80, 40);

The third argument is the diameter, not the radius.

line()

GameApp

Draw a stroked line between the points.

void line(double x1, double y1, double x2, double y2)
x1
First shape x coordinate, or line start x, in pixels.
y1
First shape y coordinate, or line start y, in pixels.
x2
Second shape x coordinate, or line end x, in pixels.
y2
Second shape y coordinate, or line end y, in pixels.

Example

line(20, 30, 120, 90);

text()

GameApp

Draw filled text. By default y is its baseline.

void text(String value, double x, double y)
value
Text to draw.
x
Horizontal position in pixels (source pixels for a region).
y
Text y in pixels using the current baseline convention.

Example

text("Hello", 20, 40);

By default, y is the text baseline.

Draw text horizontally centred at x, using the current font, fill and text baseline convention at y. Restore the previous text alignment afterward.

void textCentered(String value, double x, double y)
value
Text to draw.
x
Horizontal position in pixels (source pixels for a region).
y
Text y in pixels using the current baseline convention.

Example

textCentered("Ready", width() / 2, 40);
More about drawing

These GameApp methods are public and final. Call them after canvas creation. Coordinates use canvas pixels: (0, 0) is the top left; y increases downward. Import Color from javafx.scene.paint.

Drawing helpers use the native GraphicsContext, including settings changed through graphics(). For other operations, use that context directly.

Images

Load a bundled image as a region covering its full pixel bounds, starting at 0/0. Uses the same app-owned cached backing image as loadImage, including path aliases, without copying pixels. Each call may return a new region wrapper. A null path throws NullPointerException with Image resource path must not be null.; missing or unreadable images throw IllegalArgumentException naming the path.

ImageRegion loadImageRegion(String resourcePath)
resourcePath
Classpath resource path; leading / starts at the resource root.

Example

ImageRegion player = loadImageRegion("/player.png");

Put player.png in src/main/resources. The region covers the full cached image without copying pixels; region wrapper identity is not promised.

Load a bundled classpath image. A leading / starts at the resource root; otherwise the path is relative to your app class's Java package. Throws IllegalArgumentException for missing or unreadable images. Successful loads are cached per app by canonical resolved resource URL, including path aliases. The same resource returns the same Image until shutdown clears the cache; failed loads are not cached.

Image loadImage(String resourcePath)
resourcePath
Classpath resource path; leading / starts at the resource root.

Example

Image player = loadImage("/player.png");

Put player.png in src/main/resources for this example. Successful loads share an app-scoped canonical-resource cache until shutdown.

image()

GameApp

Draw at x/y using the image's natural size.

void image(Image image, double x, double y)
image
Successfully loaded backing JavaFX Image.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).

Example

image(player, 20, 30);

The example assumes player is an Image loaded in setup().

image()

GameApp

Draw at x/y scaled to the supplied dimensions.

void image(Image image, double x, double y, double width, double height)
image
Successfully loaded backing JavaFX Image.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

image(player, 20, 30, 80, 80);

The example assumes player is an Image loaded in setup().

Create a new independent looping animation over the cached image. Grid cells must divide its pixel dimensions exactly.

SpriteAnimation loadAnimation(String resourcePath, int columns, int rows, double fps)
resourcePath
Classpath resource path; leading / starts at the resource root.
columns
Positive number of equal-width columns dividing the image exactly.
rows
Positive number of equal-height rows dividing the image exactly.
fps
Frames per second; positive and finite.

Example

SpriteAnimation walk = loadAnimation("/walk.png", 4, 2, 8);

Create a validated source rectangle in an image without copying pixels.

ImageRegion imageRegion(Image image, double x, double y, double width, double height)
image
Successfully loaded backing JavaFX Image.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

ImageRegion portrait = imageRegion(sheet, 0, 0, 32, 32);

image()

GameApp

Draw the region at top-left x/y at its natural frame size.

void image(ImageRegion region, double x, double y)
region
Immutable source rectangle to draw.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).

Example

image(region, 20, 30);

The example assumes player is an Image loaded in setup().

image()

GameApp

Draw the region at top-left x/y scaled to the supplied dimensions.

void image(ImageRegion region, double x, double y, double width, double height)
region
Immutable source rectangle to draw.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

image(region, 20, 30, 80, 80);

image()

GameApp

Draw the current animation frame without advancing it at top-left x/y at its natural frame size.

void image(SpriteAnimation animation, double x, double y)
animation
Animation whose current frame is drawn without advancing.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).

Example

image(animation, 20, 30);

The example assumes player is an Image loaded in setup().

image()

GameApp

Draw the current animation frame without advancing it at top-left x/y scaled to the supplied dimensions.

void image(SpriteAnimation animation, double x, double y, double width, double height)
animation
Animation whose current frame is drawn without advancing.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

image(animation, 20, 30, 80, 80);

Draw scaled about destination centre x/y, rotating by angleDegrees; positive angles turn clockwise in canvas coordinates. Restore styles and transform afterward; animation does not advance.

void imageCentered(Image image, double x, double y, double width, double height, double angleDegrees)
image
Successfully loaded backing JavaFX Image.
x
Destination centre x in canvas pixels.
y
Destination centre y in canvas pixels.
width
Width in pixels.
height
Height in pixels.
angleDegrees
Rotation about the destination centre, in degrees; positive is clockwise.

Example

imageCentered(player, 100, 80, 64, 64, 30);

Draw scaled about destination centre x/y, rotating by angleDegrees; positive angles turn clockwise in canvas coordinates. Restore styles and transform afterward; animation does not advance.

void imageCentered(ImageRegion region, double x, double y, double width, double height, double angleDegrees)
region
Immutable source rectangle to draw.
x
Destination centre x in canvas pixels.
y
Destination centre y in canvas pixels.
width
Width in pixels.
height
Height in pixels.
angleDegrees
Rotation about the destination centre, in degrees; positive is clockwise.

Example

imageCentered(region, 100, 80, 64, 64, 30);

Draw scaled about destination centre x/y, rotating by angleDegrees; positive angles turn clockwise in canvas coordinates. Restore styles and transform afterward; animation does not advance.

void imageCentered(SpriteAnimation animation, double x, double y, double width, double height, double angleDegrees)
animation
Animation whose current frame is drawn without advancing.
x
Destination centre x in canvas pixels.
y
Destination centre y in canvas pixels.
width
Width in pixels.
height
Height in pixels.
angleDegrees
Rotation about the destination centre, in degrees; positive is clockwise.

Example

imageCentered(animation, 100, 80, 64, 64, 30);

Draw scaled and vertically reflected inside the destination rectangle with top-left x/y. Restore styles and transform afterward; animation does not advance.

void imageFlippedY(Image image, double x, double y, double width, double height)
image
Successfully loaded backing JavaFX Image.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

imageFlippedY(player, 20, 30, 64, 64);

Draw scaled and vertically reflected inside the destination rectangle with top-left x/y. Restore styles and transform afterward; animation does not advance.

void imageFlippedY(ImageRegion region, double x, double y, double width, double height)
region
Immutable source rectangle to draw.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

imageFlippedY(region, 20, 30, 64, 64);

Draw scaled and vertically reflected inside the destination rectangle with top-left x/y. Restore styles and transform afterward; animation does not advance.

void imageFlippedY(SpriteAnimation animation, double x, double y, double width, double height)
animation
Animation whose current frame is drawn without advancing.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

imageFlippedY(animation, 20, 30, 64, 64);
More about images

These GameApp methods are public and final. Drawing requires an existing canvas. Import zero.ImageRegion for ordinary artwork. JavaFX Image from javafx.scene.image remains available for advanced image operations.

Load assets in setup. Cached images remain in memory until app shutdown; regions and animations retain the same backing Image without bitmap copies. Each animation owns a separate clock: call its update(seconds) explicitly once per app update. Drawing never updates it.

Image regions

ImageRegion()

ImageRegion

Construct a validated rectangle sharing the supplied image.

ImageRegion(Image image, double x, double y, double width, double height)
image
Successfully loaded backing JavaFX Image.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

ImageRegion frame = new ImageRegion(sheet, 0, 0, 32, 32);

image()

ImageRegion

Original backing image, with identity preserved.

Image image()
More about image regions

public final class ImageRegion is an immutable source rectangle. Import zero.ImageRegion. Coordinates are in source-image pixels. Null image throws NullPointerException; an unloaded/failed image, non-finite coordinates, negative x/y, non-positive dimensions or an out-of-bounds rectangle throw IllegalArgumentException. No pixels are copied.

Sprite animation

SpriteAnimation()

SpriteAnimation

Construct a looping grid animation at frame 0. Positive columns/rows must divide the loaded image dimensions exactly; fps must be positive and finite.

SpriteAnimation(Image image, int columns, int rows, double fps)
image
Successfully loaded backing JavaFX Image.
columns
Positive number of equal-width columns dividing the image exactly.
rows
Positive number of equal-height rows dividing the image exactly.
fps
Frames per second; positive and finite.

Example

SpriteAnimation walk = new SpriteAnimation(sheet, 4, 2, 8);

SpriteAnimation()

SpriteAnimation

Construct a non-empty looping sequence of equal-size regions from the same Image. Positive finite fps is required; columns is the frame count and rows is 1.

SpriteAnimation(double fps, ImageRegion... frames)
fps
Frames per second; positive and finite.
frames
Non-empty sequence of equal-size regions from the same Image.

Example

SpriteAnimation walk = new SpriteAnimation(8, first, second);

update()

SpriteAnimation

Advance and loop this object only. Seconds must be non-negative and finite.

void update(double seconds)
seconds
Elapsed seconds; non-negative and finite. GameApp supplies first 0, then at most 0.1.

Example

walk.update(seconds);

createPlayback()

SpriteAnimation

Create a fresh looping clock at frame zero, sharing immutable frame definitions and backing image. Independent of this object's legacy clock.

AnimationPlayback createPlayback()

Example

AnimationPlayback playback = source.createPlayback();

Return a fresh independent clock with a non-null initial frame; shared immutable definitions do not share mutable time.

reset()

SpriteAnimation

Return this clock to frame 0, including fractional elapsed time.

void reset()

createPlayback()

AnimationSource

Return a fresh, non-null playback with a non-null initial frame. Actor calls this once per assignment, including reassigning the same source to restart.

AnimationPlayback createPlayback()

Example

AnimationPlayback playback = source.createPlayback();

Return a fresh independent clock with a non-null initial frame; shared immutable definitions do not share mutable time.

update()

AnimationPlayback

Advance this clock explicitly by finite, non-negative seconds, including zero. Actor validates time before its behaviour hook and advances the selected playback once afterward.

void update(double seconds)
seconds
Elapsed seconds; non-negative and finite. GameApp supplies first 0, then at most 0.1.

Example

playback.update(seconds);

Playback belongs to one explicit update owner. Drawing does not advance it.

frame()

AnimationPlayback

Read the current non-null frame without advancing. Actor caches a validated frame after assignment and update; drawing only observes that cache.

ImageRegion frame()

Example

ImageRegion current = playback.frame();

Playback belongs to one explicit update owner. Drawing does not advance it.

More about sprite animation

public final class SpriteAnimation implements AnimationSource retains an ordinary explicitly updated legacy clock and can create independent actor-owned playback. Import zero.SpriteAnimation. Regular sheets use equal aligned cells in row-major order, left to right then top to bottom. Trim outer margins and spacing before using a grid; arbitrary artwork is not automatically aligned. For an irregular atlas, supply equal-size ImageRegion frames from one shared Image. The explicit sequence clones the array, retaining its immutable region objects. Null inputs throw NullPointerException; invalid grids, frames, fps or seconds throw IllegalArgumentException. There is no automatic registration or update.

public interface AnimationSource is a student-implementable factory. Import zero.AnimationSource. A definition may share immutable ImageRegion objects and borrowed images, but must return fresh mutable playback on every call. It owns no app timer. Check independent clocks in your component's conformance tests.

public interface AnimationPlayback is one owner's mutable clock. Import zero.AnimationPlayback. Looping, non-looping and state-based implementations can share this contract. Keep frame() observational between explicit updates.

Actor rejects a null returned playback or frame with IllegalStateException naming createPlayback() or frame(). A failed assignment preserves the previous appearance. A failing behaviour/update can have already changed student state; there is no transaction rollback. No global playback registry detects ownership for you. App-owned cached images are borrowed; dropping/replacing a playback does not close shared images or continue ticking the detached clock.

Actors

Actor()

Actor

Create an actor centred at finite x/y with no artwork and logical size 1 × 1.

Actor(double x, double y)
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

Actor actor = new Actor(100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Actor()

Actor

Create an actor centred at x/y using a loaded image's natural dimensions.

Actor(Image image, double x, double y)
image
Successfully loaded backing JavaFX Image.
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

Actor actor = new Actor(image, 100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Actor()

Actor

Create an actor centred at x/y using the region's natural dimensions.

Actor(ImageRegion region, double x, double y)
region
Immutable source rectangle to draw.
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

Actor actor = new Actor(region, 100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Actor()

Actor

Create fresh independent playback at frame zero, using its initial frame's natural dimensions. The source's legacy clock is unchanged.

Actor(SpriteAnimation animation, double x, double y)
animation
Animation whose current frame is drawn without advancing.
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

Actor actor = new Actor(walk, 100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Actor()

Actor

Create independent playback from a non-null source, with initial frame dimensions and centre x/y.

Actor(AnimationSource source, double x, double y)
source
Non-null AnimationSource that creates fresh independent playback.
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

Actor actor = new Actor(source, 100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Test whether centred size rectangles touch or overlap; rotation is ignored. A null actor throws NullPointerException. Override for custom collision rules.

boolean touches(Actor other)
other
Non-null Actor to test for contact.

Example

boolean hit = player.touches(coin);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

x()

Actor

Read the horizontal centre in canvas pixels.

final double x()

Example

double centreX = actor.x();

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

y()

Actor

Read the vertical centre in canvas pixels.

final double y()

Example

double centreY = actor.y();

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

width()

Actor

Read the drawing width in pixels.

final double width()

Example

double left = actor.x() - actor.width() / 2;

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Read the drawing height in pixels.

final double height()

Example

double top = actor.y() - actor.height() / 2;

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Read clockwise degrees in [0, 360), with 0 facing right.

final double rotation()

Example

double facing = actor.rotation();

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Set the centre to finite x/y.

final void setPosition(double x, double y)
x
Finite horizontal centre in canvas pixels.
y
Finite vertical centre in canvas pixels.

Example

actor.setPosition(100, 80);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Set strictly positive finite drawing dimensions.

final void setSize(double width, double height)
width
Drawing dimension in pixels; strictly positive and finite.
height
Drawing dimension in pixels; strictly positive and finite.

Example

actor.setSize(48, 48);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Set finite clockwise degrees, normalized to [0, 360).

final void setRotation(double degrees)
degrees
Finite clockwise degrees; rotation is normalized to [0, 360).

Example

actor.setRotation(90);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

move()

Actor

Add finite offsets to the centre; reject non-finite results before changing either coordinate.

final void move(double dx, double dy)
dx
Finite horizontal movement in pixels.
dy
Finite vertical movement in pixels.

Example

actor.move(100 * seconds, 0);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Move in the facing direction by signed pixels-per-second speed times non-negative seconds. Reject non-finite results atomically.

final void moveForward(double speed, double seconds)
speed
Signed pixels per second; finite. Negative moves backward.
seconds
Elapsed seconds; non-negative and finite. Main passes this explicitly.

Example

actor.moveForward(100, seconds);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Add finite clockwise degrees and normalize to [0, 360).

final void rotate(double degrees)
degrees
Finite clockwise degrees; rotation is normalized to [0, 360).

Example

actor.rotate(90 * seconds);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

face()

Actor

Face a finite target point; a target at the centre leaves rotation unchanged.

final void face(double targetX, double targetY)
targetX
Finite target horizontal centre in canvas pixels.
targetY
Finite target vertical centre in canvas pixels.

Example

actor.face(mouseX(), mouseY());

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Face and approach a finite target at non-negative pixels-per-second speed for non-negative seconds. Stop exactly at the target without overshooting; reject non-finite results atomically.

final void moveToward(double targetX, double targetY, double speed, double seconds)
targetX
Finite target horizontal centre in canvas pixels.
targetY
Finite target vertical centre in canvas pixels.
speed
Pixels per second; non-negative and finite.
seconds
Elapsed seconds; non-negative and finite. Main passes this explicitly.

Example

enemy.moveToward(player.x(), player.y(), 70, seconds);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Replace the sprite with a loaded image, keeping size, position and rotation.

final void setImage(Image image)
image
Successfully loaded backing JavaFX Image.

Example

actor.setImage(image);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Replace the sprite with a region, keeping size, position and rotation.

final void setImage(ImageRegion region)
region
Immutable source rectangle to draw.

Example

actor.setImage(region);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Create fresh playback, preserving actor size, position and rotation and leaving the source's legacy clock unchanged.

final void setImage(SpriteAnimation animation)
animation
Animation whose current frame is drawn without advancing.

Example

actor.setImage(walk);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Validate fresh playback and its initial frame before replacing the appearance; preserve size, position and rotation.

final void setImage(AnimationSource source)
source
Non-null AnimationSource that creates fresh independent playback.

Example

actor.setImage(source);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Validate finite non-negative time, run onUpdate(seconds), then advance the selected playback once and cache its non-null frame.

final void update(double seconds)
seconds
Elapsed seconds; non-negative and finite. Main passes this explicitly.

Example

actor.update(seconds);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

Override for ordinary behaviour; default does nothing. Receives validated time before playback advancement; no super call is needed.

protected void onUpdate(double seconds)
seconds
Elapsed seconds; non-negative and finite. Main passes this explicitly.

Example

@Override
protected void onUpdate(double seconds) {
    move(60 * seconds, 0);
}

Override this validated behaviour hook without a super call. Final update advances the currently selected playback once after this returns.

draw()

Actor

Existing overridable drawing entry point, called by GameApp.draw(actor). The base implementation establishes this actor/app drawing scope, translates to x/y, rotates, invokes draw(), and restores the prior drawing context, styles and transform in finally. Legacy overrides still run.

void draw(GameApp app)
app
GameApp canvas to draw on; must not be null.

Example

actor.draw(this);

Actor is an unreleased local source addition. Main calls actor.update(seconds) and draw(actor) explicitly. Position is the centre; creating an actor does not register it with the app.

draw()

Actor

Override to draw in actor-local coordinates, with (0, 0) at its centre and the actor rotation already applied. Default: draw its sprite centred and scaled to width/height, or do nothing when there is no artwork. Never advances animation.

void draw()

Example

@Override
public void draw() {
    fill(zero.Color.BLUE);
    circle(0, 0, 24);
}

Override in an Actor subclass. The base draw(GameApp) establishes local translation/rotation and restores styles/transform/context in finally. Main calls draw(actor); drawing never updates the actor.

fill()

Actor

Set local shape/text fill using a non-null zero.Color.

protected final void fill(zero.Color color)
color
Non-null zero.Color, not javafx.scene.paint.Color.

Example

fill(zero.Color.BLUE);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Set local outline/line stroke using a non-null zero.Color.

protected final void stroke(zero.Color color)
color
Non-null zero.Color, not javafx.scene.paint.Color.

Example

stroke(zero.Color.BLACK);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Set line width through the active drawing app.

protected final void strokeWidth(double pixels)
pixels
Stroke width in pixels.

Example

strokeWidth(3);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Set text size through the active drawing app.

protected final void textSize(double pixels)
pixels
Font size in pixels.

Example

textSize(24);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

rect()

Actor

Draw a filled rectangle from its local top-left x/y.

protected final void rect(double x, double y, double width, double height)
x
Actor-local canvas coordinate before its rotation.
y
Actor-local canvas coordinate before its rotation.
width
Local drawing dimension in canvas pixels.
height
Local drawing dimension in canvas pixels.

Example

rect(20, 30, 100, 60);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Draw an outlined rectangle from its local top-left x/y.

protected final void outlineRect(double x, double y, double width, double height)
x
Actor-local canvas coordinate before its rotation.
y
Actor-local canvas coordinate before its rotation.
width
Local drawing dimension in canvas pixels.
height
Local drawing dimension in canvas pixels.

Example

outlineRect(20, 30, 100, 60);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Draw a filled circle with a local centre and a diameter, not a radius.

protected final void circle(double centreX, double centreY, double diameter)
centreX
Actor-local canvas coordinate before its rotation.
centreY
Actor-local canvas coordinate before its rotation.
diameter
Circle diameter in pixels.

Example

fill(zero.Color.BLUE);
circle(0, 0, 24);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

line()

Actor

Draw a line between local endpoints.

protected final void line(double x1, double y1, double x2, double y2)
x1
Actor-local canvas coordinate before its rotation.
y1
Actor-local canvas coordinate before its rotation.
x2
Actor-local canvas coordinate before its rotation.
y2
Actor-local canvas coordinate before its rotation.

Example

line(20, 30, 120, 90);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

text()

Actor

Draw text at local x/y using the current baseline convention.

protected final void text(String value, double x, double y)
value
Text to draw.
x
Actor-local canvas coordinate before its rotation.
y
Actor-local canvas coordinate before its rotation.

Example

text("Hello", 20, 40);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

Centre text horizontally about local x using the current baseline convention.

protected final void textCentered(String value, double x, double y)
value
Text to draw.
x
Actor-local canvas coordinate before its rotation.
y
Actor-local canvas coordinate before its rotation.

Example

textCentered("Ready", width() / 2, 40);

Protected final Actor helper. Call only in this actor’s active base draw(GameApp) scope, normally from draw(); otherwise IllegalStateException. Coordinates are actor-local; setSize does not automatically scale custom drawing.

More about actors

public class Actor is an optional ordinary Java object you can extend. Import zero.Actor. Its x/y position is the actor's centre. With artwork, its initial size is the image/frame's natural size. Actor(x, y) has no artwork and starts with logical width/height 1; override draw() to draw shapes. Rotation starts at 0 (facing right); positive degrees turn clockwise and rotation is normalized to [0, 360).

Main explicitly calls actor.update(seconds) and draw(actor); there is no registration or automatic lifecycle. Final update validates seconds, calls the protected onUpdate(seconds) behaviour hook, then advances the currently selected playback once. Override onUpdate without a super call. A hook may switch image or animation; its selected playback receives that frame's elapsed time. Drawing never advances animation. Sharing one AnimationSource creates independent clocks for each actor; updating the source's legacy SpriteAnimation clock does not advance actor clocks.

Numeric arguments for construction, position, size, movement, rotation and elapsed time must be finite; sizes must be strictly positive, seconds must be non-negative, and moveToward speed must be non-negative. moveForward accepts signed speed (negative moves backward). Null references throw NullPointerException; invalid arguments, unloaded/failed images and non-finite movement results throw IllegalArgumentException without changing actor state. Image replacements keep position, size and rotation. Assigning an animation source creates fresh playback at its initial frame; a static image detaches playback. A target at the current position leaves rotation unchanged.

touches(other) checks centred, axis-aligned rectangles using each actor’s size. Touching edges count; rotation and artwork shape are ignored. It returns a boolean and does not move actors or resolve collisions. Override it for custom behavior, or use Collisions directly for other shapes. This class is an unreleased local source addition; older kits are unchanged.

These protected final methods are available inside an Actor subclass. Call them only during that actor's active base draw(GameApp) scope, normally from its draw() callback; otherwise they throw IllegalStateException with useful guidance. They delegate to the supplied app without a static current-app field. Exceptions restore the previous context, styles and transform. Main.draw(actor) uses canvas coordinates; drawing another actor inside an actor callback composes the current parent transform, so that nested actor's position is relative to it. Each nested scope restores its caller's state.

Import zero.Color for fill/stroke. Coordinates are local canvas pixels: positive x points right and positive y points down before the actor's clockwise rotation. setSize changes logical dimensions and default sprite size; it does not scale custom drawing coordinates. Use width()/height() explicitly if your shapes should follow logical size. Shapes add no collision geometry.

GameApp.draw(actor) deliberately calls actor.draw(app), preserving old overrides. An override of draw(GameApp) that does not call super controls its own drawing; the scoped callback/helpers are supplied by the base implementation. Prefer no-argument draw() for new Actor subclasses. Main still explicitly updates and draws each object, with no implicit registration or lifecycle.

Audio

Load a short sound effect. Successful loads are cached per app by canonical resource URL: aliases return the same live Sound, including its volume/mute state. Loading after manually closing that Sound creates a fresh one.

Sound loadSound(String resourcePath)
resourcePath
Classpath resource path; leading / starts at the resource root.

Example

Sound chime = loadSound("/chime.wav");

Create an independent buffered music player. Each call owns its own position, volume and mute state, even for the same resource.

Music loadMusic(String resourcePath)
resourcePath
Classpath resource path; leading / starts at the resource root.

Example

Music music = loadMusic("/music.wav");
music.loop();

play()

Sound

Play the short effect unless muted; repeated calls can overlap.

void play()

Example

chime.play();

stop()

Sound

Stop all playback of this sound.

void stop()

Example

chime.stop();

Set the volume for subsequent plays from 0 (silent) to 1 (full).

void setVolume(double volume)
volume
Volume from 0 to 1 inclusive; finite.

Example

chime.setVolume(0.5);

Return the chosen volume, independent of mute.

double getVolume()

Example

chime.getVolume();

Muting stops active effects and silences new plays, without changing the chosen volume. Unmuting does not replay stopped effects.

void setMuted(boolean muted)
muted
True to mute; false to restore the chosen volume.

Example

chime.setMuted(true);

Whether this sound is muted.

boolean isMuted()

Example

chime.isMuted();

Whether this sound currently has active playback.

boolean isPlaying()

Example

chime.isPlaying();

close()

Sound

Stop playback and mark this sound closed.

void close()

Example

chime.close();

play()

Music

Start or resume playback; after natural completion, start again. Preserve the selected repeat mode.

void play()

Example

music.play();

loop()

Music

Select repeating playback and start or resume it.

void loop()

Example

music.loop();

pause()

Music

Pause playback while preserving its position.

void pause()

Example

music.pause();

stop()

Music

Stop playback and rewind to the beginning, preserving the selected repeat mode.

void stop()

Example

music.stop();

Set the volume from 0 (silent) to 1 (full).

void setVolume(double volume)
volume
Volume from 0 to 1 inclusive; finite.

Example

music.setVolume(0.5);

Return the chosen volume, independent of mute.

double getVolume()

Example

music.getVolume();

Mute or unmute playback without changing the chosen volume.

void setMuted(boolean muted)
muted
True to mute; false to restore the chosen volume.

Example

music.setMuted(true);

Whether this player is muted.

boolean isMuted()

Example

music.isMuted();

Whether this player currently reports active playback.

boolean isPlaying()

Example

music.isPlaying();

close()

Music

Stop playback and dispose the owned player.

void close()

Example

music.close();
More about audio

These App methods are public and final, and are inherited by GameApp. Load in setup() and keep fields for playback from a button or game event. Put audio in src/main/resources; a leading / starts at the resource root, otherwise paths are relative to your app class's Java package. Use supported JavaFX audio formats, such as PCM WAV. Missing or unreadable audio reports the resource path in an IllegalArgumentException; failed loads are not cached.

Sound stores decoded samples in memory for short, overlapping effects. Music uses JavaFX MediaPlayer buffering for longer tracks. Load once rather than once per frame. The app closes owned audio on stop, window close, startup failure and frame failure. Call loaders, controls and close on the JavaFX application thread (setup, update and JavaFX event handlers already do this). Main still explicitly decides when game pause, restart or focus loss should pause/stop music. Raw JavaFX AudioClip and MediaPlayer remain available for advanced needs; the app manages only audio created through these loaders.

public final class Sound implements AutoCloseable has no public constructor. Import zero.Sound and obtain one with loadSound. The default volume is 1 and mute is false. Volume must be finite and between 0 and 1 inclusive, otherwise IllegalArgumentException is thrown. Muting preserves the chosen volume. Closing is idempotent; afterward controls throw a useful IllegalStateException, while getters remain readable.

public final class Music implements AutoCloseable has no public constructor. Import zero.Music and obtain one with loadMusic. Each instance has independent playback. The default volume is 1 and mute is false. Volume must be finite and between 0 and 1 inclusive; invalid values throw IllegalArgumentException. Muting preserves the chosen volume. Readiness and actual playback are asynchronous. Asynchronous player failures report the resource path once and dispose the player; later controls throw a useful failed-player error. Closing is idempotent; after close controls throw IllegalStateException, while getters remain readable.

Collisions

Whether a circle touches or overlaps an axis-aligned rectangle.

static boolean circleHitsRect(double cx, double cy, double radius, double x, double y, double width, double height)
cx
Circle centre x; finite.
cy
Circle centre y; finite.
radius
Circle radius; non-negative and finite.
x
Horizontal position in pixels (source pixels for a region).
y
Vertical position in pixels (source pixels for a region).
width
Width in pixels.
height
Height in pixels.

Example

boolean hit = Collisions.circleHitsRect(100, 80, 20, 90, 70, 40, 50);

rectHitsRect()

Collisions

Whether two axis-aligned rectangles touch or overlap.

static boolean rectHitsRect(double x1, double y1, double width1, double height1, double x2, double y2, double width2, double height2)
x1
First shape x coordinate, or line start x, in pixels.
y1
First shape y coordinate, or line start y, in pixels.
width1
First rectangle width; non-negative and finite.
height1
First rectangle height; non-negative and finite.
x2
Second shape x coordinate, or line end x, in pixels.
y2
Second shape y coordinate, or line end y, in pixels.
width2
Second rectangle width; non-negative and finite.
height2
Second rectangle height; non-negative and finite.

Example

boolean hit = Collisions.rectHitsRect(0, 0, 20, 20, 20, 10, 30, 30);

Whether two circles touch or overlap.

static boolean circleHitsCircle(double x1, double y1, double radius1, double x2, double y2, double radius2)
x1
First shape x coordinate, or line start x, in pixels.
y1
First shape y coordinate, or line start y, in pixels.
radius1
First circle radius; non-negative and finite.
x2
Second shape x coordinate, or line end x, in pixels.
y2
Second shape y coordinate, or line end y, in pixels.
radius2
Second circle radius; non-negative and finite.

Example

boolean hit = Collisions.circleHitsCircle(0, 0, 10, 20, 0, 10);
More about collisions

public final class Collisions has no public constructor. Import zero.Collisions and call its static predicates. Rectangles use top-left x/y; circles use centre x/y and radius (unlike drawing circle, which accepts a diameter). Touching counts as a hit, including zero-size shapes. All values must be finite; dimensions and radii must be non-negative, otherwise IllegalArgumentException is thrown. These tests do not move objects or resolve physics.

Keyboard and mouse

LEFT

Key

The left arrow key.

static final Key LEFT

Example

if (keyDown(Key.LEFT)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

The right arrow key.

static final Key RIGHT

Example

if (keyDown(Key.RIGHT)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

UP

Key

The up arrow key.

static final Key UP

Example

if (keyDown(Key.UP)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

DOWN

Key

The down arrow key.

static final Key DOWN

Example

if (keyDown(Key.DOWN)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

W

Key

The W key.

static final Key W

Example

if (keyDown(Key.W)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

A

Key

The A key.

static final Key A

Example

if (keyDown(Key.A)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

S

Key

The S key.

static final Key S

Example

if (keyDown(Key.S)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

D

Key

The D key.

static final Key D

Example

if (keyDown(Key.D)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

The Space key.

static final Key SPACE

Example

if (keyDown(Key.SPACE)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

The Enter key.

static final Key ENTER

Example

if (keyDown(Key.ENTER)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

The Escape key.

static final Key ESCAPE

Example

if (keyDown(Key.ESCAPE)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

R

Key

The R key.

static final Key R

Example

if (keyDown(Key.R)) { /* Move your object explicitly. */ }

Zero keyboard enum constant; no JavaFX import. Only the documented constants and queries are admitted by the browser profile.

mouseX()

GameApp

Latest tracked mouse x in canvas coordinates. Starts at canvas centre.

double mouseX()

Example

double x = mouseX();

mouseY()

GameApp

Latest tracked mouse y in canvas coordinates. Starts at canvas centre.

double mouseY()

Example

double y = mouseY();

keyDown()

GameApp

Whether an advanced JavaFX key pressed with canvas focus is held.

boolean keyDown(KeyCode key)
key
JavaFX KeyCode to check.

Example

if (keyDown(KeyCode.LEFT)) {
    x -= 100 * seconds;
}

Click the canvas to focus it. This example belongs in update(seconds) and assumes a double field named x.

keyDown()

GameApp

Whether a Zero key pressed with canvas focus is held. Null throws NullPointerException with a useful error.

boolean keyDown(Key key)
key
Non-null Zero Key constant.

Example

if (keyDown(Key.LEFT)) { /* Move your object explicitly. */ }

Shares the existing canvas-owned input state. Focus loss clears held keys and pending edges; controls retain their own keyboard input.

Whether the primary pointer button pressed on the canvas is held, with no JavaFX type needed.

boolean mouseDown()

Example

if (mouseDown()) { /* Use mouseX() and mouseY() for your game. */ }

Primary pointer input without a JavaFX import; shares existing canvas focus and non-consuming edge rules.

Whether a button pressed on the canvas is held.

boolean mouseDown(MouseButton button)
button
JavaFX MouseButton to check.

Example

if (mouseDown(MouseButton.PRIMARY)) {
    circle(mouseX(), mouseY(), 20);
}

Click the canvas to focus it. Losing canvas or window focus clears held input.

Whether an advanced JavaFX key has a new press for the current update/draw frame. Repeated queries do not consume it; holding does not repeat it.

boolean keyPressed(KeyCode key)
key
JavaFX KeyCode to check.

Example

if (keyPressed(KeyCode.SPACE)) {
    jump();
}

Whether a Zero key has a new press for the current update/draw frame. Repeated queries do not consume it and holding does not repeat it. Null throws NullPointerException with a useful error.

boolean keyPressed(Key key)
key
Non-null Zero Key constant.

Example

if (keyPressed(Key.LEFT)) { /* Move your object explicitly. */ }

Shares the existing canvas-owned input state. Focus loss clears held keys and pending edges; controls retain their own keyboard input.

Whether a new primary canvas press occurred this frame. Repeated queries do not consume it; no JavaFX type is needed.

boolean mousePressed()

Example

if (mousePressed()) { /* Use mouseX() and mouseY() for your game. */ }

Primary pointer input without a JavaFX import; shares existing canvas focus and non-consuming edge rules.

Whether a new canvas button press occurred for the current update/draw frame. Repeated queries do not consume it.

boolean mousePressed(MouseButton button)
button
JavaFX MouseButton to check.

Example

if (mousePressed(MouseButton.PRIMARY)) {
    shots++;
}

Whether the app window has focus, including when a native control owns keyboard focus. False before the window exists or after shutdown.

boolean windowFocused()

Example

if (!windowFocused()) {
    return;
}
More about keyboard and mouse

public enum Key supplies common movement and action keys for normal Zero game input. Import zero.Key and use keyDown(Key.LEFT) or keyPressed(Key.LEFT). No constructor or JavaFX key type is needed. The browser profile admits the constants below and queries; implicit enum methods such as values(), valueOf() and name() are not part of the supported browser API. The existing KeyCode overloads remain the advanced JavaFX interoperability path for additional keys.

These GameApp methods are public and final. Use after canvas creation. Use zero.Key for arrows, W/A/S/D, Space, Enter, Escape and R. For advanced JavaFX input, import KeyCode and MouseButton from javafx.scene.input.

keyDown/mouseDown report held state. keyPressed/mousePressed report edges: even a press and release between frames is visible throughout the next real update and draw, then cleared. Pausing your own game logic does not retain an edge beyond that frame. Losing focus clears held, pending and frame input. Window focus does not imply canvas focus and does not automatically pause a game. Click the canvas to focus it. Native controls receive normal typing. Losing canvas or window focus clears held input; owned releases clear it even outside the canvas. Coordinates track canvas events and owned drags, can leave its bounds, and do not continually track other controls. While the canvas is focused, arrow presses are consumed for game input instead of moving focus to another control. Tab still moves focus to native controls; arrows in a focused text field keep their normal caret behavior.

Advanced lifecycle and extension hooks

Advanced

Run settings, create the root/content, run setup, create the scene, configure/show the stage, then call ready. On startup failure, call stop, close the stage and rethrow.

public final void start(Stage stage)
stage
JavaFX application window.

Call shutdown at most once per app and close owned audio on every call. Window hiding and JavaFX application exit can both call stop; the extension hook is not repeated.

public final void stop()

Return configured initial width (default 800). Cannot be overridden.

protected final double initialWidth()

Return configured initial height (default 500). Cannot be overridden.

protected final double initialHeight()

Return initial centre content; default null. Called before setup.

protected Node createContent()

Create a scene containing the root at the configured initial dimensions. Called after setup.

protected Scene createScene(BorderPane content)
content
Root layout containing the app content.

No action. Called after the stage is shown.

protected void ready(Stage stage)
stage
JavaFX application window.

No action. Called at most once by stop, including startup-failure cleanup.

protected void shutdown()

Create the canvas, graphics context, layout and canvas input handlers; initialise mouse coordinates; return the layout.

protected final Node createContent()

Create a scene sized from its content, allowing room for controls around the canvas.

protected final Scene createScene(BorderPane content)
content
Root layout containing the app content.

ready()

GameApp

Install scene/window input handling, request canvas focus when gameplay input is enabled, and start the single frame driver.

protected final void ready(Stage stage)
stage
JavaFX application window.

shutdown()

GameApp

Stop the timer if present, clear all input and the image cache, and forget the window.

protected final void shutdown()
More about advanced

App declares these final JavaFX lifecycle overrides. Let JavaFX call them. Import Stage from javafx.stage.

Use JavaFX's inherited launch(args) in public static void main(String[] args). Other inherited JavaFX APIs remain available; they are outside Zero's own API.

These hooks support framework extension. Students normally override settings, setup, update and draw. Import Scene and Node from javafx.scene, BorderPane from javafx.scene.layout, and Stage from javafx.stage.

GameApp supplies these final overrides; subclasses cannot replace them.

Settings, setup, frames and JavaFX handlers run on the JavaFX application thread. A failed frame stops the timer, clears held input, closes owned audio and reports the exception. Closing the app also stops its timer.

The readable App source and GameApp source are the authority for a locally modified framework. Ordinary JavaFX controls and example classes such as ScoreDisplay, Player and Question have their own APIs; see the object lesson, Player lesson and reusable views lesson for their use.

The source starter includes JavaFX controls, graphics and media. Use loadSound for effects and loadMusic for tracks; see the audio reference. Raw JavaFX AudioClip/MediaPlayer remain available. Persistence, FXML and web need their own dependencies. ZeroHub provides exact-version shared libraries through ordinary Java imports; it does not change this core API or require a component base class. Public managed library admission remains gated; local checks and pinned consumption do not establish public acceptance.