CodeX Academy · Level 1 — App Lab · Week 6 Day 1

Lives Tracker

Optional extra practice. Same shape as the Score Tracker demo: one state variable, one function that accepts a value and updates the display, called from more than one event. Different scenario, on your own.

1. Build this in Design Mode first

STEP 1

Create these elements on screen1 with these exact IDs and starting text.

TypeIDText
LabellivesLabelLives: 3
LabelstatusLabelStatus: --
ButtonloseLifeBtnLose a Life
ButtongainLifeBtnGain a Life
ButtonrestartBtnRestart

2. Switch to Code Mode

STEP 2

Three handlers already update lives and echo it into livesLabel. Your job: pull the two shared display lines out of all three into one named function that takes the status message as a parameter, the way updateScoreDisplay did in the demo.

// SETUP (already works - do not edit the lives math)
var lives = 3;

onEvent("loseLifeBtn", "click", function() {
  lives = lives - 1;
  setText("livesLabel", "Lives: " + lives);
  setText("statusLabel", "Status: Ouch");
  // (pull the two lines above into your function once it exists)
});

onEvent("gainLifeBtn", "click", function() {
  lives = lives + 1;
  setText("livesLabel", "Lives: " + lives);
  setText("statusLabel", "Status: Bonus!");
  // (pull the two lines above into your function once it exists)
});

onEvent("restartBtn", "click", function() {
  lives = 3;
  setText("livesLabel", "Lives: " + lives);
  setText("statusLabel", "Status: --");
  // (pull the two lines above into your function once it exists)
});

// STEP 1: Write ONE function here that accepts a status message and
// updates both labels:
//   function updateLivesDisplay(statusText) { ... }

3. Check yourself — predict before you click

STEP 3
ClicklivesLabelstatusLabel
Lose a LifeLives: 2Status: Ouch
Gain a LifeLives: 3Status: Bonus!
Lose a Life againLives: 2Status: Ouch
RestartLives: 3Status: --

If a button still shows the old text after you wire up the function, its handler is still calling setText directly. Replace those two lines with one call to your new function.

Try it for real before checking the answer key.

Answer key
var lives = 3;

function updateLivesDisplay(statusText) {
  setText("livesLabel", "Lives: " + lives);
  setText("statusLabel", "Status: " + statusText);
}

onEvent("loseLifeBtn", "click", function() {
  lives = lives - 1;
  updateLivesDisplay("Ouch");
});

onEvent("gainLifeBtn", "click", function() {
  lives = lives + 1;
  updateLivesDisplay("Bonus!");
});

onEvent("restartBtn", "click", function() {
  lives = 3;
  updateLivesDisplay("--");
});