<div class="title">Current Score:</div>
<div class="score" id="js-score"></div>

<p>Let's add a "New Game" button that resets the score to 0 and updates it</p>

<button onClick="game.newGame()">New Game</button>

<p>Let's simulate an allowed way of updating the game score, using the button to represent the user action .</p>
<button onClick="game.incrementScore()">Increment score (game mechanic)</button>

<p>Let's add an action that simulates end of the game state where we submit the current score to leaderboards</p>

<button onClick="game.gameOver()">Game Over</button>

<div class="explanation">
  <p>Open the Console by clicking the button below below. Try using <code>setScore(500)</code> function to manipulate the score and <code>gameOver()</code> function to submit the score.</p>
</div> 
body {
  font-family: sans-serif;
  font-size: 1.25rem;
  max-width: 768px;
  margin: 0 auto;
  padding: 1rem;
  line-height: 1.333;
}

.score {
    font-size: 3rem;
  text-align: center;
}

.title {
  font-size: 1.5rem;
    text-align: center;
}
const game = (() => {
  let score = 0;
  let scoreContainer;

  const updateScore = newScore => {
    if (isNaN(newScore)) return;
    score = newScore;
    scoreContainer.innerHTML = score;
  };

  const incrementScore = () => {
    updateScore(score + 1);
  };

  const submitScore = () => alert("Submitting Score: " + score);

  const gameOver = () => submitScore();

  const newGame = () => {
    updateScore(0);
  };

  const init = () => {
    scoreContainer = document.getElementById("js-score");
    newGame();
  };

  init();

  return {
    incrementScore,
    newGame,
    gameOver
  };
})();

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.