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.
- 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
gameSeqto 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.
- 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();
}
});- 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);
}- Logic: When the game moves to a new level, a new random color is added to the
gameSeq, and the level is incremented. - Functionality:
- The
userSeqis cleared to store the user's new inputs for the current level. - The
levelis incremented, and the display is updated to reflect the current level. - A random index is selected from the
btnsarray to pick a color and add it togameSeq. - The selected button is flashed to show the next button in the sequence.
- The
- 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);
}- Logic: This function checks if the user's sequence (
userSeq) matches the game's sequence (gameSeq) at each step. - Functionality:
- It compares the current user input (from
userSeq) with the corresponding entry ingameSeq. - 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.
- If the user's input doesn't match the game's sequence, the game is over, and the score (level reached) is displayed.
- It compares the current user input (from
- 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();
}
}- Logic: When the user clicks a button, this function captures which button was pressed and stores it in
userSeq. - Functionality:
- The button is flashed for visual feedback.
- The button's color is stored in the
userSeq. - 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);
}- 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
clickevent listener to each button. When the user clicks a button, thebtnPress()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);
}- 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;
}- Initialization: The game starts with
keypressand 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.