Coin Game
Lesson 11: Practise sharing a component
Practise checking and sharing a component.
First checkpoint: keep your component working, then prepare a clearly labelled practice contribution.
Reopen the Coin game and continue on the coin-refactor branch from lesson 10. There is no lesson 11 download or new tutorial project. Keep practising in this folder. This lesson shares a tiny CreditsBadge in a separate Tutorial practice area. Copies are expected: you are learning the workflow, not claiming to have invented a new utility. PlayerInput stays in your game; you do not submit it.
1. Retain the displayed value
In ScoreDisplay.java, keep the private Label and Element view from lesson 10.
Add the two fields by replacing the matching line with the copied code:
private final Label label = new Label("Score: 0");
private String caption = "Score";
private int points;
The game Main still owns the score. In ScoreDisplay.java, replace setScore with the copied code:
public void setScore(int points) {
this.points = points;
refresh();
label.setText("Score: " + points);
}
private void refresh() {
label.setText(caption + ": " + points);
}
this.points is the display's field; the parameter points is the value supplied
by the calling class. One refresh method keeps formatting in one place.
2. Add a caption method after refresh()
In ScoreDisplay.java, add setCaption between refresh() and view(); replace the matching lines with the copied code:
label.setText(caption + ": " + points);
}
public void setCaption(String caption) {
if (caption == null) {
throw new IllegalArgumentException("Score caption must not be null.");
}
this.caption = caption;
refresh();
}
public Element view() {
Changing the caption refreshes the existing label without losing its displayed points. The null check runs before either field changes, so a bad argument gives a useful error and leaves the previous caption and value intact. No Zero core change or access to the private Label is needed.
In the game's Main setup(), add the caption by replacing the matching line with the copied code. Keep the scoring rules and setScore calls in Main:
score = new ScoreDisplay();
score.setCaption("Score");
3. Run the game and check the component
Try a different caption in setup by replacing the matching line with the copied code:
score.setCaption("Score");
score.setCaption("Coins");
Run and collect a coin; the display
should read Coins: 1. Finish and restart the game twice. Restore the setup caption by replacing the matching line with the copied code:
score.setCaption("Coins");
score.setCaption("Score");
To check changing a caption after a value, temporarily replace the matching line inside the game's coin-collection block with the copied code:
score.setScore(points);
score.setCaption("Coins");
Collect one coin: the display should show Coins: 1,
proving the caption change kept that value. Stay on the coin and check it still
shows 1.
Remove that experimental line and restore score.setCaption("Score") in the
game's Main setup() before continuing. Keep view() and setScore(int) as the
public ways to mount and update the display.
Run once more and check that collecting one coin shows Score: 1. Save your
files on coin-refactor, enter Let ScoreDisplay change its caption, and choose:
Commit
4. Optionally improve PlayerInput with WASD
The game now has one place to improve keyboard input. As an optional feature,
let A/D and W/S work alongside the arrow keys. In PlayerInput.java, replace both methods with the copied code:
public int horizontal() {
int direction = 0;
if (game.keyDown(Key.LEFT)) direction--;
if (game.keyDown(Key.LEFT) || game.keyDown(Key.A)) direction--;
if (game.keyDown(Key.RIGHT)) direction++;
if (game.keyDown(Key.RIGHT) || game.keyDown(Key.D)) direction++;
return direction;
}
public int vertical() {
int direction = 0;
if (game.keyDown(Key.UP)) direction--;
if (game.keyDown(Key.UP) || game.keyDown(Key.W)) direction--;
if (game.keyDown(Key.DOWN)) direction++;
if (game.keyDown(Key.DOWN) || game.keyDown(Key.S)) direction++;
return direction;
}
|| means “or.” Right + D contributes +1 once, rather than +2. Left or A
opposes Right or D, so A + Right cancels just as Left + Right does. Main still
asks for two directions; Player still owns movement. Keep the constructor and
GameApp game field from lesson 10. No Zero framework change is needed.
Run and check all arrows still work, each WASD direction, W + D diagonally, Right + D at the same speed as Right, A + Right cancelling horizontal motion, and W + Down cancelling vertical motion. Try both opposing arrows too. Preserve Player's existing diagonal speed rule. Release all keys, switch windows while holding a key, return and click the canvas, and test Restart during play and after winning. Input should clear on focus loss and Restart; all three coins, scoring and reset behaviour should still work. Update Main's drawn help text by replacing the matching line with the copied code so the player can discover the keys:
text("Click the canvas, then hold the arrow keys.", 20, 30);
text("Click the canvas, then hold arrows or WASD.", 20, 30);
Run and check that the new help text appears and the keys work. If you made
this change, save your files, enter Add WASD controls, and choose:
Commit
5. Record the API and finish the refactor branch
Record what you checked in README, including the expected result and what you
observed. Record this API in a comment: view() gives the calling class an
Element; setScore(int) displays the supplied score; setCaption(String) changes
the caption while retaining that displayed value. Existing new ScoreDisplay()
calls still work, as do view() and setScore(int); this is a compatible improvement.
A separate instance can use a different caption without changing this one. When
you reuse the class in another project, test that caller too.
After adding the badge in the next steps, compare your game Main and ScoreDisplay.java with checkpoint 11 (shown before library extraction). Its PlayerInput.java includes the optional WASD change; checkpoint 10 is the arrow-only comparison if you skipped it. Checkpoint 12 carries that same WASD helper forward.
Save your notes, enter Document ScoreDisplay checks, and choose:
Commit
Stop the game. With coin-refactor selected, choose:
Sync
Wait for Sync to finish, then choose Merge beside the branch name and confirm Merge coin-refactor into main?
Check that main is selected. Run the merged game and check movement, scoring and Restart. Stop the game before starting the next branch.
6. Add a harmless practice badge
After the merge, check that main is current. Click its name in the Project panel, then choose:
New branch…
Enter coin-badge and press Enter. Check that coin-badge is current before
adding the badge.
In the Coin game's java folder, create CreditsBadge.java:
import zero.ui.Label;
/** Tutorial practice: copies are expected, not original community utilities. */
public class CreditsBadge {
private final String message;
public CreditsBadge(String message) {
if (message == null) {
throw new IllegalArgumentException("Badge message must not be null.");
}
this.message = message;
}
public String text() {
return "Made with Zero: " + message;
}
public Label view() {
return new Label(text());
}
}
In the game’s Main.java, add the import by replacing the matching line with the copied code:
import zero.ui.Button;
import zero.ui.Column;
In setup(), create the badge; replace the matching lines with the copied code:
message = new Label("");
var badge = new CreditsBadge("Coin game");
var restartButton = new Button("Restart");
In setup(), replace the matching call with the copied code:
controls(new Row(12, score.view(), message, restartButton));
controls(new Column(8,
new Row(12, score.view(), message, restartButton), badge.view()));
Run. You should see Made with Zero: Coin game under the controls. Change the
message, run again, then restore Coin game for the checkpoint comparison. Check
movement, coins, win and Restart still work. The badge has no game-state job.
Save your files on coin-badge, enter Add CreditsBadge to the game, and choose:
Commit
7. Extract the practice library
Keep this same tutorial repository. Open the Command Palette, run:
Zero: Libraries and Games
Then choose:
Extract library
Select only CreditsBadge.java, choose UI component, and use the
exact library name tutorial-credits-badge, version 0.1.0. Give it the
title Tutorial practice: CreditsBadge and a short description saying it is
from this lesson. Retain the supplied MIT licence and credit Zero's tutorial.
Review the preview: CreditsBadge moves to Libraries → Tutorial practice: CreditsBadge → java, its package gains your numeric repository ID, and Main imports that package. Zero updates the build source roots. Keep Main, PlayerInput, Player, Coin and ScoreDisplay in the game. Accept the reviewed extraction, Run again, and check the badge and game still work.
The reserved library name is the practice marker. Keep it unchanged; using an ordinary library name would place a copied exercise in the wrong category. There is one practice library identity per repository. Later versions update that entry; they do not create a new library for each attempt. Accepted version bytes remain unchanged, so a later submitted revision uses a new exact version.
8. Check the library
Extraction creates deliberately failing check/example placeholders. Replace them with the small practice sources below, retaining each filename:
- LibraryCheck.java goes in Libraries → Tutorial practice: CreditsBadge → Checks.
- FirstExample.java goes in Libraries → Tutorial practice: CreditsBadge → Examples → first.
- SecondExample.java goes in Libraries → Tutorial practice: CreditsBadge → Examples → second.
Replace the import in all three files with the exact CreditsBadge import that extraction added to your Main. The reference uses a made-up repository ID; your own package will differ. Do not copy Zero framework source into the library.
In the project tree, open:
Libraries → Tutorial practice: CreditsBadge
Choose Check library…. The checks verify independent messages, correct label text, a fresh view for each mounting and a useful null-message error. The two finite examples use different caller messages. They compile separately against the actual library JAR. This is a local result, not a public listing or browser acceptance. Record the checked version and result in the generated library README, replacing its placeholder instructions.
For browser use, export and try the Coin game using Zero's supported WebFX path. Confirm the badge, controls, movement and Restart in the browser. A successful compile and an actual working page are different checks. Keep publication an explicit separate action; local browser preview is enough to practise checking.
Save the checked library, examples and README. Enter
Extract and check the badge library and choose:
Commit
Stop the game and choose Sync on coin-badge. Wait for Sync to finish,
then choose Merge beside the branch and confirm
Merge coin-badge into main?
Check that main is selected. Run the merged game and verify the badge, movement, scoring and Restart. Run Check library… again on main before preparing a submission.
9. Practise submitting and using a classmate's badge
The hosted library service must be enabled by the maintainers before a submission can be accepted. Library publication is currently paused. While it is paused, finish extraction and Check locally, save the README, and prepare the submission; an opened form is not a listing. Do not rename the badge or use the ordinary community path to bypass that state.
When practice sharing is enabled, use your own GitHub account and this same public tutorial repository. Confirm the reviewed badge changes are committed and merged to main. Choose Share library, select the practice badge, review its exact committed folder/version and submit the prefilled official GitHub form. Requests are public; keep private information out of the source and metadata. The usual ownership, licence, source and library checks still apply. Practice does not skip checking.
Browse practice badges to find accepted badges in ZeroHub. They are labelled tutorial copies and excluded from ordinary Projects/Libraries search. Everyone is expected to have a similar badge. Completing the workflow is the achievement; these are not candidates for automatic inclusion in Zero.
To try a classmate's accepted version, stop the game. In the Project panel, click main and choose:
New branch…
Enter try-classmate-badge and press Enter. Check that the new branch is
selected. Open the Command Palette and run:
Zero: Libraries and Games
Then choose:
Browse tutorial practice
Select their badge, deliberately choose a version if offered, then choose:
Add library → Apply
Use the exact import shown for their package. In Main, replace only the badge construction with their fully qualified class name and the same message argument; keep your own library in local mode and keep the game rules unchanged. Run and check the displayed message. Use a new exact version for an improvement and review Update/Revert deliberately; editor updates never replace it automatically.
Stop the game, save your files, enter Try a classmate's badge, and choose
Commit. Select main from the branch menu before lesson 12. Your
experiment stays on try-classmate-badge.
Maintainers may periodically clear practice listings. That removes them from practice discovery. Your GitHub source, local extracted source and already added JARs are not deleted. Keep your project and its version records. Re-fetching or checking a withdrawn dependency follows Zero's normal availability rules; clearing the gallery is not a promise that every later dependency operation will succeed. Coursework repository links still go separately to Pika.
10. Optional extension: contribute an original idea
After practising the workflow, look for a capability your own app actually needs:
a configurable input mapping, a useful animation helper or another component you
can explain. Keep PlayerInput and copied CreditsBadge out of the ordinary
community catalogue. Build an original or meaningfully adapted component in an
original project you own, outside zero.*, and credit sources and licences.
This extension is optional; it is not a required tutorial project.
Document its public methods and ownership, meaningful behaviour checks and two small consumers. Run Check library and record the exact source/version. For browser consumers, also export through WebFX and try the relevant behaviour. Use the ordinary community sharing flow only when hosted acceptance is enabled.
Once the component has helped more than one app, you may propose the proven idea for Zero itself. Include the problem, proposed API, source/version and contributor credit, native/browser evidence, README and licence, and how existing callers would keep working or migrate. A proposal can start in README without publication. Maintainers may adopt or adapt it, keep it as a community library, or defer it. A practice submission, listing or popularity never promotes code automatically. Existing project versions stay unchanged until users deliberately upgrade.
Continue growing your same Coin game with media in lesson 12.
You checked a component and prepared a practice contribution!