Keeping Score

Keeping Score - Count those Cupcakes!

Now that you’re smashing cupcakes like a pro, it’s time to keep track of your epic cupcake-smashing score! Every time you whack a cupcake, you earn a point. Let’s add a scoring system that updates in real-time on your scoreboard.

Tip

Remember, right at the start we set the variable scoreBoard.

Now we’re going to create another variable (this time called score).

Before - Replace this code
let scoreBoard = document.querySelector('.score');
After - Updated code
let scoreBoard = document.querySelector('.score');
let score = 0;

Now let’s add our score variable to our smashing function so that it starts at zero, and increases by one each time a cupcake is successfully smashed. This is your personal cupcake smash counter!

Before - Replace this code
function smash(cupcake) {
	console.log('smashed!');
	cupcake.parentNode.classList.remove('up');
}
After - Updated code
function smash(cupcake) {
	console.log('smashed!');
	cupcake.parentNode.classList.remove('up');
	score = score + 1;
}

We’re also going to tell our scoreBoard variable to show score whenever it is increased. To update scoreBoard we will use the textContent property.

Before - Replace this code
function smash(cupcake) {
	console.log('smashed!');

	cupcake.parentNode.classList.remove('up');
	score = score + 1;
}
After - Updated code
function smash(cupcake) {
	console.log('smashed!');

	cupcake.parentNode.classList.remove('up');
	score = score + 1;
	scoreBoard.textContent = score;
}

Start the game and watch your score increase everytime you smash a cupcake!

Resetting the score: Each time we restart the game, we also want to reset the score back to zero, so we can start again from scratch.

Before - Replace this code
function startGame() {
	timeUp = false;
	popUp();
	setTimeout(endGame, 10000);
}
After - Updated code
function startGame() {
	timeUp = false;
    score = 0;
    scoreBoard.textContent = score;
	popUp();
	setTimeout(endGame, 10000);
}

Now each time you click Start you should see the score reset to zero.

Check your code!

This is what you should have in CodePen so far:

let timeUp = false;
let holes = document.querySelectorAll('.hole');
let scoreBoard = document.querySelector('.score');
let score = 0;

function startGame() {
    timeUp = false;
    score = 0;
    scoreBoard.textContent = score;
    popUp();
    setTimeout(endGame, 10000);
}

function endGame() {
    timeUp = true;
}

function popUp() {
    console.log('Here I am!');
    let hole = holes[0];
    let time = 500;
    hole.classList.add('up');
    setTimeout(function () {
        hole.classList.remove('up');
        if (timeUp == false) {
            popUp();
        }
    }, time);
}


function smash(cupcake) {
    console.log('smashed!');
    cupcake.parentNode.classList.remove('up');
    score = score + 1;
    scoreBoard.textContent = score;
}