Right now a miss costs nothing. Let’s add three lives and a game-over. First, a lives variable at the top:
let lives = 3;When the ball is missed we need to put it back in the middle. We’ll do that in two places, so let’s make a function for it — add serve() above update():
function serve() {
bx = 64;
by = 64;
bdx = 1.5;
bdy = rnd(2) - 1; // a slightly random up/down angle
}Now lose a life when the ball slips off the left edge. At the bottom of update(), add:
if (bx < 0) {
lives = lives - 1;
serve();
}And stop the game when lives run out. At the very top of update(), add:
if (lives <= 0) {
return;
}return here is an early exit — when lives reaches 0, the rest of update() is skipped, so the paddle and ball freeze. draw() still runs, so we can show a message.
Finally, show the lives and a game-over message. In draw(), add print('Lives: ' + lives, 78, 4, 8); near the top, and at the bottom add:
if (lives <= 0) {
print('GAME OVER', 36, 56, 8);
}Your whole program now — a real game with stakes:
let paddleY = 54;
const PH = 20;
let bx = 64;
let by = 64;
let bdx = 1.5;
let bdy = 1;
let hits = 0;
let lives = 3;
function serve() {
bx = 64;
by = 64;
bdx = 1.5;
bdy = rnd(2) - 1;
}
function update() {
if (lives <= 0) {
return;
}
if (key('ArrowUp')) {
paddleY -= 2;
}
if (key('ArrowDown')) {
paddleY += 2;
}
paddleY = mid(0, paddleY, 128 - PH);
bx += bdx;
by += bdy;
if (by < 2 || by > 125) {
bdy = -bdy;
}
if (bx > 122) {
bdx = -bdx;
}
if (bx < 10 && by > paddleY && by < paddleY + PH && bdx < 0) {
bdx = -bdx;
hits = hits + 1;
}
if (bx < 0) {
lives = lives - 1;
serve();
}
}
function draw() {
cls(0);
rectfill(124, 0, 127, 127, 6);
print('Hits: ' + hits, 4, 4, 7);
print('Lives: ' + lives, 78, 4, 8);
rectfill(6, paddleY, 8, paddleY + PH, 7);
circfill(bx, by, 2, 7);
if (lives <= 0) {
print('GAME OVER', 36, 56, 8);
}
}