Skip to content

vishwas2628/simon-says-game

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

simon-says-game

Here's a step-by-step algorithm for the logic and functionality of the Simon Game implemented in JavaScript. The focus is on explaining the logic, the importance of each function, and how it helps in creating the game. The HTML and CSS are not discussed here, as the focus is purely on the JavaScript logic.

Step 1: Define Initial Variables

  • gameSeq: This array stores the sequence of randomly generated button colors. It's the sequence that the user must replicate.
  • userSeq: This array stores the sequence of colors clicked by the user. It is compared with the gameSeq to check the user's progress.
  • btns: This array holds the available color buttons (red, yellow, green, purple).
  • started: This boolean is used to check if the game has started or not. It ensures the game starts only once after a keypress.
  • level: This variable tracks the game level, which increases after each successful round.
  • h2: This variable selects the HTML element where the game status (level or game over message) is displayed.

Step 2: Detect Game Start (keypress event)

  • Logic: The game starts when any key is pressed. A keypress event listener is set up to listen for this action.
  • Functionality: Once the game is started, the levelUp() function is called to advance the game and generate the first random button.
  • Importance: This ensures the game only starts once, resetting after a game over and waiting for user interaction to start again.
document.addEventListener("keypress", function (){ 
    if (!started){
        started = true;
        levelUp();
    }
});

Step 3: Button Flashing (btnFlash function)

  • Logic: When a button is clicked by the user or generated by the game, it flashes to indicate the button's action.
  • Functionality: The function adds a class to make the button flash (with a CSS effect), then removes it after a short delay.
  • Importance: This provides visual feedback to the user, making the game interactive and easier to follow.
function btnFlash(btn){
    btn.classList.add("flash");
    setTimeout(function () {
        btn.classList.remove("flash");
    }, 250);
}

Step 4: Generate Random Color and Level Up (levelUp function)

  • Logic: When the game moves to a new level, a new random color is added to the gameSeq, and the level is incremented.
  • Functionality:
    1. The userSeq is cleared to store the user's new inputs for the current level.
    2. The level is incremented, and the display is updated to reflect the current level.
    3. A random index is selected from the btns array to pick a color and add it to gameSeq.
    4. The selected button is flashed to show the next button in the sequence.
  • Importance: This function is the core of advancing the game by increasing the level and adding a new button to the sequence. It ensures the game becomes progressively harder.
function levelUp() {
    userSeq = [];
    level++;
    h2.innerText = `Level ${level}`;

    let randIdx = Math.floor(Math.random() * 4);
    let randColor = btns[randIdx];
    let randBtn = document.querySelector(`.${randColor}`);
    gameSeq.push(randColor);

    btnFlash(randBtn);
}

Step 5: Check User's Input (checkAns function)

  • Logic: This function checks if the user's sequence (userSeq) matches the game's sequence (gameSeq) at each step.
  • Functionality:
    1. It compares the current user input (from userSeq) with the corresponding entry in gameSeq.
    2. If the sequences match so far, and the user has completed the current level (i.e., the lengths of both sequences are equal), the game advances to the next level after a short delay.
    3. If the user's input doesn't match the game's sequence, the game is over, and the score (level reached) is displayed.
  • Importance: This function is responsible for determining whether the user is playing correctly or has lost the game. It controls both advancing levels and handling game over conditions.
function checkAns(idx){
    if (userSeq[idx] === gameSeq[idx]){
        if (userSeq.length === gameSeq.length) {
            setTimeout(levelUp, 1000);
        }
    } else {
        h2.innerHTML = `Game Over! Your Score was <b> ${level} </b> <br> Press any key to start again.`;
        document.querySelector("body").style.backgroundColor = "red";
        setTimeout(function () {
            document.querySelector("body").style.backgroundColor = "white";
        }, 150);

        reset();
    }
}

Step 6: Capture User Button Press (btnPress function)

  • Logic: When the user clicks a button, this function captures which button was pressed and stores it in userSeq.
  • Functionality:
    1. The button is flashed for visual feedback.
    2. The button's color is stored in the userSeq.
    3. The checkAns() function is called to verify if the user's sequence is correct so far.
  • Importance: This function handles the interaction between the user and the game. Each user input is crucial, and it is validated step-by-step.
function btnPress() {
    let btn = this;
    btnFlash(btn);

    userColor = btn.getAttribute("id");
    userSeq.push(userColor);

    checkAns(userSeq.length - 1);
}

Step 7: Add Event Listeners to Buttons

  • Logic: All buttons (colored buttons in the game) need to have event listeners attached so that they can respond to user clicks.
  • Functionality: This code adds a click event listener to each button. When the user clicks a button, the btnPress() function is triggered.
  • Importance: This connects the buttons to the game logic, ensuring that user interactions are captured.
let allBtns = document.querySelectorAll(".btn");
for (btn of allBtns){
    btn.addEventListener("click", btnPress);
}

Step 8: Reset the Game (reset function)

  • Logic: When the user loses, the game must reset to its initial state.
  • Functionality: This function resets all the necessary variables (started, gameSeq, userSeq, level) so that the game can start fresh when a new keypress is detected.
  • Importance: Without resetting, the game would not be able to restart properly, leading to bugs or incorrect behavior.
function reset(){
    started = false;
    gameSeq = [];
    userSeq = [];
    level = 0;
}

Summary:

  • Initialization: The game starts with keypress and initializes the sequences and levels.
  • Visual Feedback: Buttons flash on both game generation and user interaction.
  • Random Sequence: A new random color is generated at each level and added to the sequence.
  • User Interaction: User clicks are captured and checked against the game sequence.
  • Game Progression: Levels increase after each successful round, making the sequence harder to remember.
  • Game Over: When the user makes a mistake, the game ends, and the score is displayed.
  • Reset: The game resets after a loss, ready for a new round.

About

js

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors