Building logic-based games like Simon Says is the ultimate test of your JavaScript array and state management skills.

Game State Variables

let gameSequence = [];
let userSequence = [];
let level = 0;
let playing = false;

const colors = ["green", "red", "yellow", "blue"];

Next Sequence Check

function nextSequence() {
  userSequence = [];
  level++;
  document.getElementById("level-title").innerText = `Level ${level}`;

  // Generate random color
  const randNum = Math.floor(Math.random() * 4);
  const randomColor = colors[randNum];
  gameSequence.push(randomColor);

  // Play animation for sequence
  setTimeout(() => {
    playSound(randomColor);
    animatePress(randomColor);
  }, 500);
}

function checkAnswer(currentLevel) {
  if (gameSequence[currentLevel] === userSequence[currentLevel]) {
    // Check if the user finished the whole sequence
    if (userSequence.length === gameSequence.length) {
      setTimeout(nextSequence, 1000);
    }
  } else {
    // Wrong answer
    playSound("wrong");
    document.body.classList.add("game-over");
    document.getElementById("level-title").innerText = "Game Over, Press Any Key to Restart";

    setTimeout(() => {
      document.body.classList.remove("game-over");
    }, 200);

    startOver();
  }
}

function startOver() {
  level = 0;
  gameSequence = [];
  playing = false;
}

Try to beat level 10 in the Live Demo!