cssAudio - Activefile-genericCSS - ActiveGeneric - ActiveHTML - ActiveImage - ActiveJS - ActiveSVG - ActiveText - Activefile-genericVideo - ActiveLovehtmlicon-new-collectionicon-personicon-teamlog-outoctocatpop-outspinnerstartv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

            
              <div class="game-box container-fluid">
  <div class="button-box">
  <div class="row">
    <div id="green" class="col-xs-6 pad square1" data-pad="1">
    <audio preload="auto" class="sound1" data-pad="1">
        <source src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg" />
      </audio>
    </div>
    <div id="red" class="col-xs-6 pad square2" data-pad="2">
      <audio preload="auto" class="sound2" data-pad="2">
        <source src="https://s3.amazonaws.com/freecodecamp/simonSound2.mp3" type="audio/mpeg" />
      </audio>
    </div>
  </div>
  <div class="row">
    <div id="yellow" class="col-xs-6 pad square3" data-pad="3">
      <audio preload="auto" class="sound3" data-pad="3">
        <source src="https://s3.amazonaws.com/freecodecamp/simonSound3.mp3" type="audio/mpeg" />
      </audio>
    </div>
    <div id="blue" class="col-xs-6 pad square4" data-pad="4">
      <audio preload="auto" class="sound4" data-pad="4">
        <source src="https://s3.amazonaws.com/freecodecamp/simonSound4.mp3" type="audio/mpeg" />
      </audio>
    </div>
  </div>
  </div>
  <div class="row">
    <div class="col-xs-4">
      <button id="startBtn" class="btn btn-default" type="submit">Start</button>
      <span>Count</span>
      <span id="stepCount">--</span>
      <button id="strictBtn" class="btn btn-default" type="submit">Strict</button>
    </div>
  </div>
</div>
            
          
!
            
              .game-box {
  background: #DCDCDC;
  max-width: 490px;
  margin-left: auto;
  margin-right: auto;
}

.button-box {
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.pad {
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=60)";
  filter: alpha(opacity=60);
  opacity: 0.6;
}

#green,
#red,
#blue,
#yellow {
  width: 200px;
  height: 200px;
  margin: 6px;
  border-radius: 14px;
}

#green {
  background: #3CB371;
}

#red {
  background: #DC143C;
}

#yellow {
  background: #FFD700;
}

#blue {
  background: #7B68EE;
}
            
          
!
            
              $(document).ready(function() {
  $('#startBtn').on('mouseup', function() { // initialise game when start button is clicked
    $(this).hide();
    game.init();
  });

/*--------------------------------------------------------------
# game object
--------------------------------------------------------------*/    
var game = { // game object
  count: 0, // number of steps in the sequence
  strict: false, // strict mode on or off
  active: false, // turn active or inactive
  handler: false, // click and sound handlers active or inactive
  aiSeq: [], // array containing the sequence generated by the AI

  /* Stephie's notes: You no not need an array to keep track of the user's inputs
  However you do need a number to keep track of their position within the sequence */
  
  //userSeq: [], // the human player's pad inputs  -- NOTE: Not necessary
  userIndex: 0, // User's position within the sequence. Resets every round.
  sequenceIndex : 0, // Needed for playing the sequence!
  
/*--------------------------------------------------------------
# game.init()
--------------------------------------------------------------*/  
  init: function() { // initialise the game
    if (this.handler === false) { // checks to see if handlers are already active
      this.padListener(); // if there isn't then activate them
      this.handler = true;
    }
    this.newGame();
  },

/*--------------------------------------------------------------
# game.padListener()
--------------------------------------------------------------*/
  padListener: function() { // listen for user clicking on the pads
    var that = this;
    $('.pad').on('mouseup', function() {
      if (that.active === true) {
        var pad = parseInt($(this).data('pad'), 10);
        that.lightUp($(this), 1, 300, pad);
        console.log(pad); // Logging to the console for testing.
        that.checkSeq(pad); // Check to see if the guess was correct.
      }
    });
    this.handler = true;
  },

/*-------------------------------------------------------------
# game.newGame()
--------------------------------------------------------------*/ 
  newGame: function() { // resets the game and starts a new one
    this.count = 1;
    this.displayCount();
    // this.aiSeq.length = 0; This is not how you should clear out arrays!
    this.aiSeq = [];
    this.active = true;
    this.randomPad();
    this.displaySequence();
  },

/*--------------------------------------------------------------
# game.lightUp()
--------------------------------------------------------------*/  
  lightUp: function(element, times, speed, pad) { // function to illuminate the pads when active
    var that = this; // cache this

    if (times > 0) { // checks that it's correct to illuminate the pad
      that.playSound(pad); // play the corresponding pad sound
      element.stop().animate({
        opacity: '1'
      }, { // animate the element to flash
        duration: 50,
        complete: function() {
          element.stop().animate({
            opacity: '0.6'
          }, 200);
        }
      }); // end animation
    }

    if (times > 0) { // call the lightUp function again the correct number of times
      setTimeout(function() {
        that.lightUp(element, times, speed, pad);
      }, speed);
      times -= 1; // subtract 1 from times each time it's called
    }
  },

/*--------------------------------------------------------------
# game.playSound()
--------------------------------------------------------------*/  
  playSound: function(tone) { // plays the sound that corresponds to the pad chosen
    var sound = $('.sound' + tone)[0];
    sound.currentTime = 0;
    sound.play();
  },

/*--------------------------------------------------------------
# game.randomPad()
--------------------------------------------------------------*/  
  randomPad: function() {
    this.aiSeq.push(Math.floor(Math.random() * 4) + 1); // generate a random number between 1 and 4 to push to the AI sequence array
    console.log(this.aiSeq);
  },

/*--------------------------------------------------------------
# game.displaySequence()
--------------------------------------------------------------*/  
  displaySequence: function() { // display the generated sequence to the user
    var that = this;
      var val = that.aiSeq[that.sequenceIndex]; // Grab the value (1-4) from the sequence at the current play position
      that.sequenceIndex++; // Increment play position
      setTimeout(function() {
        that.lightUp($(".square" + val), 1, 300, val); //Light it up
        if (that.sequenceIndex < that.count){ // Have we not played the whole sequence?
          that.displaySequence(); // Then play it again (recursive)
        } else {
          that.sequenceIndex = 0; // Reset play index (playing stops)
        }
      }, 500);
  },

/*--------------------------------------------------------------
# game.displayCount()
--------------------------------------------------------------*/  
  displayCount: function() { // display the current user level (Count) on the screen
    $('#stepCount').text(this.count);
  },

/*--------------------------------------------------------------
# game.keepCount()
--------------------------------------------------------------*/  
  keepCount: function() { // keep the user's count level
    this.count++;
    this.displayCount();
  },

/*--------------------------------------------------------------
# game.checkSeq()
--------------------------------------------------------------*/  
  checkSeq: function(pad) { // check to determine if the pad the user pressed was the correct next one in the sequence
    var that = this;
    if (pad !== this.aiSeq[this.userIndex]) {
      this.userIndex = 0; // Start Over
      if (this.strict === true) {
        this.gameOver(); // strict mode is on, end the game
      } else if (this.strict === false) {
        this.displaySequence(); // strict mode is off, display the sequence again to the user
      }
    } else { // they guessed correctly
      this.userIndex++; //Increment the user's position within the sequence
      if(this.userIndex === this.aiSeq.length){ // If the user has correctly guessed the entire current sequence
        this.userIndex = 0; // Start at the beginning of the sequence
        
        //this.active = false;  This is making it so we can't guess past the first round!!
        if(this.count >= 20){ // Have they completed all 20 rounds?
          // If so, they won!
          setTimeout(function(){ // Using set timeout to avoid 'play() interrupeted' error
            alert("You Win! \n Restarting Game...");
            that.newGame();
          }, 150);  
        } else { // Otherwise, they haven't won but they did beat the round
          this.keepCount(); // if correct keep going and increment the count
          this.randomPad();
          this.displaySequence();
        }
     }
    }
  },
  
/*--------------------------------------------------------------
# game.gameOver()
--------------------------------------------------------------*/    
  gameOver: function() { // in strict mode, ends the game if user gets input wrong
    window.alert("Game over");
    return;
  }
};

}); // End doc ready
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console