Simon Game JavaScript Code

Simon Game JavaScript Code
Project: Javascript Simon Game
Author: Ben Blood
Edit Online: View on CodePen
License: MIT

This JavaScript code represents the classic Simon Game, a memory-based puzzle that challenges players to repeat a sequence of colors and sounds. The game starts with the power set to “off,” and clicking the power button turns it “on.” The strict button, when clicked, changes its state between “off” and “on,” and this mode adds an extra challenge by resetting the level upon any incorrect response.

The game uses four colored buttons: green, red, yellow, and blue, each with a corresponding sound. The game randomly generates a sequence of colors, adding one more color to the sequence with each increasing level. Players need to memorize the sequence and replicate it by clicking on the corresponding buttons. If the user input matches the sequence, the game advances to the next level, with an increasing tempo to intensify the challenge.

The main functionalities include handling button clicks, managing game states like power, strict mode, and running status. The newMemory() function generates a random color for each level and adds it to the memoryArray, and the playMemory() function plays back the colors and sounds stored in the memoryArray.

The Simon Game is an enjoyable and stimulating memory exercise that offers hours of entertainment, and this JavaScript code provides the core mechanics to play and enjoy the game on any web browser. Have fun testing your memory skills and beat your high score!

How to Create Simon Game in JavaScript

1. First of all, load Font Awesome CSS and Bootstrap CSS by adding the following CDN links to the head tag of your web/app project.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>

2. After that, create the HTML structure for Simon game as follows:

<audio id="soundbuttonGre" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3"></audio>
<audio id="soundbuttonRed" src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3"></audio>
<audio id="soundbuttonYel" src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3"></audio>
<audio id="soundbuttonBlu" src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"></audio>
<audio id="soundbuttonWrong" src="http://www.freesound.org/data/previews/331/331912_3248244-lq.mp3"></audio>

<div class="gameContainer noSelect">
  <div id="buttonGre" class="fourButton"></div>
  <div id="buttonRed" class="fourButton"></div>
  <div id="buttonYel" class="fourButton"></div>
  <div id="buttonBlu" class="fourButton"></div>
  <div id="center">
    <div id="textTitle">Simon</div>
    <div id="countBox">
      <div id="countDisplay">
        <div id="displayText">
          --
        </div>
      </div>
      <div id="countText">Count</div>
    </div>
    <div id="startBox">
      <div id="startButton"></div>
      <div id="startText">Start</div>
    </div>
    <div id="strictBox">
      <div id="strictButton""></div>
      <div id="strictText">Strict</div>
    </div>
    <div id="powerBox">
      <div id="onText">ON</div>
      <div id="powerSwitch">
        <div id="buttonOn"></div
        ><div id="buttonOff"></div
        ></div>
      <div id="offText">OFF</div>
    </div>
  </div>
</div>

3. Style the game interface using the following CSS styles:

body{
  background-image: url(http://braccousa.com/wp-content/uploads/2013/07/Dark-wooden-website-background.jpg) !important;
  background-size: cover;
}
.noSelect {
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
}
.gameContainer {
	position:relative;
	width:440px;
	height:440px;
	margin:0 auto;
  margin-top: 50px;
  border: solid 1px black;
  border-radius: 50%;
  background-color: grey;
}

.fourButton {
	position:absolute;
	width:190px;
	height:190px;
  margin: 20px;
  pointer-events: none;
}
.fourButton:active {
  opacity: .5;
}
.activated {
  opacity: .5;
}
#buttonGre {
	top:0;
	left:0;
	background-color:green;
	border-radius:100% 0 0 0;
}
#buttonRed {
	top:0;
	right:0;
	background-color:red;
	border-radius:0 100% 0 0 ;
}
#buttonYel {
	bottom:0;
	left:0;
	background-color:yellow;
	border-radius:0 0 0 100%;
}
#buttonBlu {
	bottom:0;
	right:0;
	background-color:blue;
	border-radius:0 0 100% 0 ;
}
#center {
  position:absolute;
  background-color:white;
  border: 20px solid grey;
	width:200px;
	height:200px;
	top:120px;
	left:120px;
	border-radius:50%;
}
#textTitle {
  height: 70px;
  line-height: 90px;
  width: 100%;
  text-align: center;
  font-size: 40px;
  color: black;
}
#countBox {
  vertical-align: top;
  display: inline-block;
  height: 50px;
  width: 50.3px;
}
#countDisplay {
  border: solid 3px black;
  border-radius: 20%;
  height: 50%;
  margin: 0px 6px 0px 6px;
  background: red;
  font-size: 20px;
  line-height: 20px;
  text-align: center;
}
#countText {
  height: 30%;
  margin: 4px 6px 0px 6px;
  font-size: 10px;
  color: black;
  font-weight: bold;
  text-align: center;
}
#displayText {
  opacity: 0.3;
}
#startBox {
  vertical-align: top;
  display: inline-block;
  height: 50px;
  width: 50.4px;
}
#startButton {
  border: solid 3px black;
  border-radius: 50%;
  height: 50%;
  margin: 0px 12.7px 0px 12.7px;
  background: red;
  font-size: 20px;
  line-height: 17px;
  text-align: center;
}
#startText {
  height: 30%;
  margin: 4px 6px 0px 6px;
  font-size: 10px;
  color: black;
  font-weight: bold;
  text-align: center;
}
#strictBox {
  vertical-align: top;
  display: inline-block;
  height: 50px;
  width: 50.4px;
}
#strictButton {
  border: solid 3px black;
  border-radius: 50%;
  height: 50%;
  width: 25px;
  margin: 0px 12.5px 0px 12.5px;
  background: yellow;
  color: black;
  font-size: 17px;
  line-height: 20px;
  text-align: center;
}
#strictText {
  height: 30%;
  margin: 4px 6px 0px 6px;
  font-size: 10px;
  color: black;
  font-weight: bold;
  text-align: center;
}
#onText {
  vertical-align: top;
  display: inline-block;
  height: 40px;
  line-height: 25px;
  width: 60px;
  font-size: 10px;
  color: black;
  font-weight: bold;
  text-align: right;
}
#powerSwitch {
  background: grey;
  vertical-align: top;
  display: inline-block;
  border: solid 1px black;
  margin-top: 5px;
  height: 15px;
  width: 30px;
}
#buttonOn {
  visibility: hidden;
  background: blue;
  vertical-align: top;
  display: inline-block;
  border-radius: 15%;
  margin: 1px 2.8px 0px 1px;
  height: 10px;
  width: 12px;
}
#buttonOff {
  background: blue;
  vertical-align: top;
  display: inline-block;
  border-radius: 15%;
  margin: 1px 0px 0px 0px;
  height: 10px;
  width: 12px;
}
#offText {
  vertical-align: top;
  display: inline-block;
  height: 40px;
  line-height: 25px;
  width: 60px;
  font-size: 10px;
  color: black;
  font-weight: bold;
}

4. Load the jQuery by adding the following CDN link just before closing the <body> tag:

<script src='//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

5. Finally, add the following JavaScript code to your project to initialize the Simon game.

var power = "off";
var strict = "off";
var running = false;
var memoryArray = [];
var memoryArrayCounter = 0;
var userArray = [];
var userArrayCounter = 0;
var levelCount = 1;
var tempColor;
var runMemory;
var matchingArrays = true;
var tempo;

//Visualization Note
function colorButton(id, color) {
    this.id = id;
    this.color = color;
}
var gre = new colorButton(1, "gre");
var red = new colorButton(2, "red");
var yel = new colorButton(3, "yel");
var blu = new colorButton(4, "blu");

//Visual Changes when clicking the power button
$("#powerSwitch").on("click", function() {
  if (power == "off") {
    $("#buttonOn").css("visibility", "visible");
    $("#buttonOff").css("visibility", "hidden");
    $("#displayText").css("opacity", "1");
    power = "on";
  }
  else if (power == "on") {
    $("#buttonOn").css("visibility", "hidden");
    $("#buttonOff").css("visibility", "visible");
    $("#displayText").css("opacity", "0.3");
    power = "off";
    strict = "off";
    $("#strictButton").css("background", "yellow");
    $("#strictButton").removeClass("fa fa-check");
    running = false;
    $("#startButton").css("background", "red");
    memoryArray = [];
    userArray = [];
    levelCount = 1;
    $("#displayText").html("--");
    memoryArrayCounter = 0;
    userArrayCounter = 0;
    matchingArrays = true;
    clearInterval(runMemory);
    $(".fourButton").css("pointer-events", "none");
  }
});

//Visual changes when clicking the strict button
$("#strictButton").on("click", function() {
  if (power == "on" && running == false) {
    if (strict == "off") {
      $("#strictButton").css("background", "green");
      $("#strictButton").addClass("fa fa-check");
      strict = "on";
    }
    else if (strict == "on") {
      $("#strictButton").css("background", "yellow");
      $("#strictButton").removeClass("fa fa-check");
      strict = "off";
    }
  }
});

//Effects when clicking the start button
$("#startButton").on("click", function() {
  if (power == "on") {
    $("#startButton").css("background", "green");
    running = true;
    userArray = [];
    memoryArray = [];
    memoryArrayCounter = 0;
    userArrayCounter = 0;
    levelCount = 1;
    $("#displayText").html("--");
    matchingArrays = true;
    clearInterval(runMemory);
    $(".fourButton").css("pointer-events", "none");
    newMemory();
    console.log(memoryArray);
    setTimeout(function() {runMemory = setInterval(playMemory, 1000);}, 1000);
  }
});

//Effects when clicking colored buttons
$("div[id*='button']").on("click", function() {
  if (power == "on" && running) {
    if (event.which == 1) {
      $("#sound" + this.id).get(0).cloneNode().play();
      userArray.push(this.id.slice(6, 9));
      userArrayCounter++;
      
      for (i = 0; i < userArray.length; i++) {
        if (memoryArray[i] != userArray[i]) {
          matchingArrays = false;
        }
      }
      if (!matchingArrays) {
        $("#displayText").html("!!");
        $("#soundbuttonWrong").get(0).play();
        userArray = [];
        memoryArrayCounter = 0;
        userArrayCounter = 0;
        matchingArrays = true;
        $(".fourButton").css("pointer-events", "none");
        if (strict == "on") {
          memoryArray = [];
          levelCount = 1;
          newMemory();
          console.log(memoryArray);
          setTimeout(function() {runMemory = setInterval(playMemory, tempo);}, 1000);
        }
        else {
          setTimeout(function() {runMemory = setInterval(playMemory, tempo);}, 1000);
        }
      }
      else {
        if (userArrayCounter == memoryArrayCounter) {
          if (matchingArrays) {
            if (levelCount == 20) {
              win();
            }
            else {
              userArray = [];
              memoryArrayCounter = 0;
              userArrayCounter = 0;
              newMemory();
              levelCount++;

              switch(levelCount) {
                case 1:
                case 2:
                case 3:
                case 4:
                  tempo = 1000;
                    break;
                case 5:
                  tempo = 700;
                  break;
                case 9:
                  tempo = 500;
                  break;
                case 13:
                  tempo = 300;
                  break;
              }
              setTimeout(function() {runMemory = setInterval(playMemory, tempo);}, 1000);
              $(".fourButton").css("pointer-events", "none");
            }
          }
        }
      }
    }
  }
});

//Randomly selects a number for each level count and
//Adds it to the memoryArray.  Numbers correspond to 
//colors depending on the color's object.id
function newMemory() {
  var temp = Math.floor((Math.random() * 4) + 1);
  switch(temp) {
    case 1:
      memoryArray.push("Gre");
      break;
    case 2:
      memoryArray.push("Red");
      break;
    case 3:
      memoryArray.push("Yel");
      break;
    case 4:
      memoryArray.push("Blu");
      break;
  }
}

function playMemory() {
  $("#displayText").html(levelCount);
  tempColor = memoryArray[memoryArrayCounter];
  //$("#soundbutton" + tempColor).get(0).play();
  $("#soundbutton" + tempColor).get(0).cloneNode().play();
  $("#button" + tempColor).addClass("activated");
  setTimeout(function() {$("#button" + tempColor).removeClass("activated");}, 250);
  memoryArrayCounter++;
  if (memoryArrayCounter == memoryArray.length) {
    clearInterval(runMemory);
    $(".fourButton").css("pointer-events", "auto");
  }
}

function win() {
  $("#displayText").html("WIN");
  $("#buttonGre").addClass("activated");
  setTimeout(function() {$("#buttonGre").removeClass("activated");}, 250);
  setTimeout(function() {$("#buttonRed").addClass("activated");}, 250);
  setTimeout(function() {$("#buttonRed").removeClass("activated");}, 500);
  setTimeout(function() {$("#buttonYel").addClass("activated");}, 500);
  setTimeout(function() {$("#buttonYel").removeClass("activated");}, 750);
  setTimeout(function() {$("#buttonBlu").addClass("activated");}, 750);
  setTimeout(function() {$("#buttonBlu").removeClass("activated");}, 1000);
  
  setTimeout(function() {$("#buttonGre").addClass("activated");}, 1250);
  setTimeout(function() {$("#buttonRed").addClass("activated");}, 1250);
  setTimeout(function() {$("#buttonYel").addClass("activated");}, 1250);
  setTimeout(function() {$("#buttonBlu").addClass("activated");}, 1250);
  setTimeout(function() {$("#buttonGre").removeClass("activated");}, 1500);
  setTimeout(function() {$("#buttonRed").removeClass("activated");}, 1500);
  setTimeout(function() {$("#buttonYel").removeClass("activated");}, 1500);
  setTimeout(function() {$("#buttonBlu").removeClass("activated");}, 1500);
  
  setTimeout(function() {$("#buttonGre").addClass("activated");}, 1750);
  setTimeout(function() {$("#buttonRed").addClass("activated");}, 1750);
  setTimeout(function() {$("#buttonYel").addClass("activated");}, 1750);
  setTimeout(function() {$("#buttonBlu").addClass("activated");}, 1750);
  setTimeout(function() {$("#buttonGre").removeClass("activated");}, 2000);
  setTimeout(function() {$("#buttonRed").removeClass("activated");}, 2000);
  setTimeout(function() {$("#buttonYel").removeClass("activated");}, 2000);
  setTimeout(function() {$("#buttonBlu").removeClass("activated");}, 2000);
  
  setTimeout(function() {
    userArray = [];
    memoryArray = [];
    memoryArrayCounter = 0;
    userArrayCounter = 0;
    levelCount = 1;
    $("#displayText").html("--");
    matchingArrays = true;
    clearInterval(runMemory);
    $(".fourButton").css("pointer-events", "none");
    newMemory();
    console.log(memoryArray);
    setTimeout(function() {runMemory = setInterval(playMemory, 1000);}, 1000);
  }, 3000);
}

That’s it! hopefully, you have successfully created Simon Game using this JavaScript code. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply