Currently experiencing difficulties while attempting to create a Simon game in JavaScript. Seeking assistance to troubleshoot the issue

var buttonColor = ["red", "blue", "green", "yellow"];

var userClickedPattern = [];

var gamePattern = [];



var totalKey = [];


var level = 0;

$("*").on("keydown", function(m)  {
  var key = m.key;

  totalKey.push(key);
  var keyLength = totalKey.length;
  if (keyLength == 1) {
    nextSequence();
  }
});

function nextSequence() {
    userClickedPattern = [];
  $("#level-title").html("Level " + level );
  var num1 = Math.floor(Math.random() * 4);
  var randomChosenColor = buttonColor[num1];
  gamePattern.push(randomChosenColor);
  flashandsound(randomChosenColor);
  level++

}

function flashandsound(n) {
  $("#" + n ).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);

  var audio = new Audio("sounds/" + n + ".mp3");
  audio.play();
}



$("div").on ("click", function() {
  const userChosenColour = $(this).attr("id");
 //to animate the userChosenColour
  $("#" + userChosenColour).addClass("pressed");

  setTimeout(function () {
      $("#" + userChosenColour).removeClass("pressed");
  }, 500);

  userClickedPattern.push(userChosenColour);

  flashandsound(userChosenColour);


  checkAnser(userClickedPattern.length -3);
})

function checkAnser(currentLevel){

if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
  if ((userClickedPattern.length-2) === gamePattern.length) {
    setTimeout(function () {
      nextSequence();
    }, 1000);
  }


} else {
   $("#level-title").html('Game over, Press any key to start again');
   var audio = new Audio("sounds/wrong.mp3");
   audio.play();
   $("body").addClass("game-over");
   setTimeout(function () {
     $("body").removeClass("game-over");
   }, 1000);

   restart();
}

}

function restart() {
  totalKey = [];
  level = 0;
  gamePattern = [];
  userClickedPattern = [];
}
body {
  text-align: center;
  background-color: #011F3F;
}

#level-title {
  font-family: 'Press Start 2P', cursive;
  font-size: 3rem;
  margin:  5%;
  color: #FEF2BF;
}

.container {
  display: block;
  width: 50%;
  margin: auto;

}

.btn {
  margin: 25px;
  display: inline-block;
  height: 200px;
  width: 200px;
  border: 10px solid black;
  border-radius: 20%;
}

.game-over {
  background-color: red;
  opacity: 0.8;
}

.red {
  background-color: red;
}

.green {
  background-color: green;
}

.blue {
  background-color: blue;
}

.yellow {
  background-color: yellow;
}

.pressed {
  box-shadow: 0 0 20px white;
  background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Simon</title>
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Press+Start+2P" rel="stylesheet">
</head>

<body>

<!-- begin snippet: js hide: false console: true babel: false -->

<h1 id="level-title">Press A Key to Start</h1>
  
<div class="container">
    
<div lass="row">

      <div type="button" id="green" class="btn green">

      </div>

      <div type="button" id="red" class="btn red">

      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="btn yellow">

      </div>
      <div type="button" id="blue" class="btn blue">

      </div>

    </div>

  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="game.js" charset="utf-8"></script>

</body>

</html>

(I noticed that the userClickedPattern is returning three times the clicked value instead of one. Additionally, I'm struggling with framing a proper if statement to make the game run smoothly. Any guidance on what could be going wrong would be greatly appreciated. Thank you)

Answer №1

Your nested div buttons are causing a three-level deep structure.

<div class="container">
<div lass="row"> <!-- it should be class="row" instead -->
      <div type="button" id="green" class="btn green"&...

Additionally, each div in your jQuery selector is receiving an onclick event.

$("div").on ("click", function() {

To resolve the issue of multiple values being returned with every button press, consider changing your selector from $("div") to $("div.btn").

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`How can we efficiently transfer style props to child components?`

Is there a way to pass Props in the Style so that each component has a unique background image? Take a look at this component: countries.astro --- import type { Props } from 'astro'; const { country, description } = Astro.props as Props; --- & ...

Navigating a mobile-friendly menu anytime!

I'm in the process of creating a responsive "hamburger" menu for mobile devices. The HTML code I have implemented is as follows... .menu_closed { color: red; } .menu_open { color: blue; } <script src="https://ajax.googleapis.com/ajax/libs/jq ...

Tips for changing date format within Ajax javascript code

I am working with a JavaScript AJAX code: success:function(res){ var _html=''; var json_data=$.parseJSON(res.posts); $.each(json_data,function (index,data) { _html+='<span class=&apo ...

Is there a way to verify the location of an element?

Currently, I am attempting to monitor the position of the 'car'. When the car reaches a top offset of 200px, I would like to apply a specific property to the 'phone' element. The concept is that as you scroll down, the car will move, an ...

how to make a post request to an API using Next.js

I am attempting to make a request to the Exist API using next.js and the backend is in PHP. I am trying to send a post request (using Axios) with data and retrieve the response. How can I manage this API in my code? I have read that I need to include som ...

validating user input on a sign-in form on the server side

<form method="POST" onsubmit=" return formSubmit() " action="log-it-reports.php"> <div class="userimage"> <img class="userlogo" src="image/userlogo.png" alt="Picture- User Profile picture"> ...

Is there a way to update a single element within an array without triggering a refresh of the entire array?

Is there a way to prevent the component from rerendering every time new data is input? I attempted to memoize each cell but I am still facing the same issue. Any suggestions on how to accomplish this? import React, { useState, memo } from "react&quo ...

Utilizing Angular.js to Bind AJAX Content to Web Pages

I recently experimented with coding using angular.js version 1.5. <div class="container clearfix" id="mainMenu" ng-controller="MainMenuController as mainMenu"> <ul class="menu clearfix" ng-init="tab = 'ant'"> <li class ...

What content appears post-iframe?

After researching for a while, I've only come across information about text displayed after a broken iframe on this topic. However, what I actually want to do is display text below an iframe set at 90% height, like so: https://i.sstatic.net/KHXI3.png ...

Focus issue with MUI Custom Text Field when state changes

Currently, I've integrated the MUI library into my React Js application. In this project, I'm utilizing the controlled Text Field component to establish a basic search user interface. However, an unexpected issue has surfaced. Following a chang ...

The UI router fails to render the template

I've recently started working with ui-router, but I'm facing an issue where nothing shows up in the ui-view. To simplify things, I even tried adding it to Plunker but still couldn't get it to work. Here's a link to my project: https://p ...

Listening for Angular 2 router events

How can I detect state changes in Angular 2 router? In Angular 1.x, I used the following event: $rootScope.$on('$stateChangeStart', function(event,toState,toParams,fromState,fromParams, options){ ... }) In Angular 2, using the window.addEv ...

Unnecessary Page Diversion

Within my index.php file, I have a download button with the id of "render". Using AJAX, I am sending a request to the server. The JavaScript code being utilized is as follows: $('#render').click(function(e){ $('html,body').animat ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...

Is it possible to perform direct URL searches using react-router-dom?

Encountering an issue when attempting to directly copy a route, resulting in the following error: Error: Cannot Access / home Despite utilizing various methods such as browserHistory, I am unable to successfully render views when navigating with menu i ...

Could you provide steps for verifying the functionality of the show password feature in selenium?

What is the best way to verify that the show password feature is functioning correctly? Which checkbox property should I inspect after clicking on the 'show password' checkbox to confirm that the entered text in the password field is visible? ...

The useMutation function trapped in an endless loop

I've been encountering an issue while running a query to save an entity in the database using usemutation. The saveVisa() mutation seems to be stuck in an infinite loop, creating the same element multiple times without any clear reason. import {React, ...

Tips for utilizing $http and $location in custom directives

I'm completely new to working with Angular, and I have a simple question about using $http and $location in directives. I'm trying to create a task list and would like to be able to delete an entry when clicking on a link. Right now, I've a ...

Balancing asynchronous tasks - masteringlearnode - program that initially succeeded but eventually faltered

node version: v4.4.3 npm version: 3.8.9 Error output Your entered data does not match the expected values. ──────────────────────────────────────────────── ...