Adding a Button
UI.showButton(label, onClick) shows a real clickable button — good for "Restart," "Play Again," or "Next Level," paired with UI.showMessage(...) from the last lesson.
export function update(self) {
if (self.health <= 0) {
UI.showMessage("Game Over!", "red");
UI.showButton("Restart", Game.restart);
}
}
Two things worth being careful about here:
- Pass the function, don't call it. Notice it's
Game.restart, notGame.restart(). WritingGame.restart()— with the parentheses — runs it immediately, right there in your code, instead of waiting for a click. Leave the parentheses off soonClickgets the button's job, not the result of already doing it. Game.restart()reloads the whole page. Since every shape starts fresh from its saved position every time the page loads, reloading is "reset everything" — no extra reset code needed. It's not limited to buttons either; callGame.restart()from anywhere you want to start over.
The button hides itself the instant it's clicked, right before running whatever you gave it — so onClick can show a new button afterwards (for a multi-step "Are you sure?" flow, for example) without fighting the old one.
UI.hideButton() hides it without clicking it, if you need to take it away for some other reason.
Want to run something custom instead of restarting? Any function works as
onClick — not just Game.restart.