Struggling to incorporate a three-strike mechanism into my JavaScript game

I need to implement a feature where the user can make up to 2 mistakes before losing the game. Here's what I need to do:

- Set up a global variable to keep track of the number of mistakes

- Initialize this variable during the startGame function

- Modify the guess function to update the mistake counter when the user makes an error, and include a check for this variable before triggering the loseGame function

I am facing challenges integrating this into the JS file. How can I accomplish this?

JS File:

const cluePauseTime = 333; //how long to pause in between clues
const nextClueWaitTime = 1000; //how long to wait before starting playback of the clue sequence

//Global variables
var clueHoldTime = 200; //how long to hold each clue's light/sound
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;

function startGame() {
  progress = 0;

  pattern = []; // reset so array doesn't get longer then 10 if we restart game
  for (var i = 0; i < clueLength; i++) {
    pattern.push(getRandomInt(5));
  }
  console.log("pattern: " + pattern);

  gamePlaying = true;

  document.getElementById("startBtn").classList.add("hidden");
  document.getElementById("stopBtn").classList.remove("hidden");

  playClueSequence();
}

function stopGame() {
  gamePlaying = false;

  document.getElementById("startBtn").classList.remove("hidden");
  document.getElementById("stopBtn").classList.add("hidden");
}

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max) + 1);
}

function lightButton(btn) {
  document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
  document.getElementById("button" + btn).classList.remove("lit");
}

function playSingleClue(btn) {
  if (gamePlaying) {
    lightButton(btn);
    playTone(btn, clueHoldTime);
    setTimeout(clearButton, clueHoldTime, btn);
  }
}

function playClueSequence() {
  guessCounter = 0;
  let delay = nextClueWaitTime; //set delay to initial wait time
  for (let i = 0; i <= progress; i++) {
    // for each clue that is revealed so far
    console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
    setTimeout(playSingleClue, delay, pattern[i]); // set a timeout to play that clue
    delay += clueHoldTime;
    delay += cluePauseTime;
  }
}

function loseGame() {
  stopGame();
  alert("Game Over. You lost.");
}
function winGame() {
  stopGame();
  alert("Yayyyyy, you win!!");
}

function guess(btn) {
  console.log("user guessed: " + btn);
  if (!gamePlaying) {
    return;
  }
  if (pattern[guessCounter] == btn) {
    if (guessCounter == progress) {
      if (progress == pattern.length - 1) {
        winGame();
      } else {
        progress++;
        playClueSequence();
      }
    } else {
      guessCounter++;
    }
    //guessCounter++;
  } else {
    loseGame();
  }
}
// Sound Synthesis Functions
const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2,
  5: 432.8,
  6: 336.2
};
function playTone(btn, len) {
  o.frequency.value = freqMap[btn];
  g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
  tonePlaying = true;
  setTimeout(function() {
    stopTone();
  }, len);
}
function startTone(btn) {
  if (!tonePlaying) {
    o.frequency.value = freqMap[btn];
    g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
    tonePlaying = true;
  }
}
function stopTone() {
  g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
  tonePlaying = false;
}

//Page Initialization
// Init Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title>Hello!</title>

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css" />

    <!-- import the webpage's javascript file -->
    <script src="/script.js" defer></script>
  </head>
  <body>
    <h1>Memory Game</h1>

    <p>
      Welcome to the game that will test your memory!
    </p>

    <button id="startBtn" onclick="startGame()">
      Start
    </button>
    <button id="stopBtn" class="hidden" onclick="stopGame()">
      Stop
    </button>

    <div id="gameButtonArea">
      <button
        id="button1"
        onclick="guess(1)"
        onmousedown="startTone(1)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button2"
        onclick="guess(2)"
        onmousedown="startTone(2)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button3"
        onclick="guess(3)"
        onmousedown="startTone(3)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button4"
        onclick="guess(4)"
        onmousedown="startTone(4)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button5"
        onclick="guess(5)"
        onmousedown="startTone(5)"
        onmouseup="stopTone()"
      ></button>
      <button
        id="button6"
        onclick="guess(6)"
        onmousedown="startTone(6)"
        onmouseup="stopTone()"
      ></button>
    </div>
  </body>
</html>

CSS:

body {
  font-family: helvetica, arial, sans-serif;
  margin: 2em;
  background-color: slategrey;
  color: white;
}

h1 {
  font-family: verdana, arial, sans-serif;
  color: yellow;
}

button {
  padding: 15px;
  border-radius: 15px;
}

#gameButtonArea > button {
  width: 200px;
  height: 200px;
  margin: 2px;
}

.hidden {
  display: none;
}

#button1 {
  background: lightgreen;
}
#button1:active,
#button1.lit {
  background: green;
}

#button2 {
  background: lightblue;
}
#button2:active,
#button2.lit {
  background: blue;
}

#button3 {
  background: pink;
}
#button3:active,
#button3.lit {
  background: red;
}

#button4 {
  background: lightyellow;
}
#button4:active,
#button4.lit {
  background: yellow;
}

#button5 {
  background: lightgray;
}
#button5:active,
#button5.lit {
  background: black;
}

#button6 {
  background: white;
}
#button6:active,
#button6.lit {
  background: purple;
}

Answer №1

  1. Declare a variable called let lostCount = 0;.

  2. Update the else block in the guess function to:

else {
    if (lostCount < 2) lostCount++;
    else loseGame();
 }

const cluePauseTime = 333; //how long to pause between clues
const nextClueWaitTime = 1000; //how long to wait before playing the clue sequence

//Global variables
var clueHoldTime = 200; //how long to hold each clue's sound/light
// var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var pattern = [];
var clueLength = 10;
///////////////////////////////
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;

let lostCount = 0;

function startGame() {
  progress = 0;

  pattern = []; // ensure array doesn't exceed length of 10 when game restarts
  for (var i = 0; i < clueLength; i++) {
    pattern.push(getRandomInt(5));
  }
  console.log("pattern: " + pattern);

  gamePlaying = true;

  document.getElementById("startBtn").classList.add("hidden");
  document.getElementById("stopBtn").classList.remove("hidden");

  playClueSequence();
}

function stopGame() {
  gamePlaying = false;

  document.getElementById("startBtn").classList.remove("hidden");
  document.getElementById("stopBtn").classList.add("hidden");
}

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max) + 1);
}

function lightButton(btn) {
  document.getElementById("button" + btn).classList.add("lit");
}
function clearButton(btn) {
  document.getElementById("button" + btn).classList.remove("lit");
}

function playSingleClue(btn) {
  if (gamePlaying) {
    lightButton(btn);
    playTone(btn, clueHoldTime);
    setTimeout(clearButton, clueHoldTime, btn);
  }
}

function playClueSequence() {
  guessCounter = 0;
  let delay = nextClueWaitTime; //initial delay time
  for (let i = 0; i <= progress; i++) {
    // reveal each already revealed clue
    console.log("play single clue: " + pattern[i] + " in " + delay + "ms");
    setTimeout(playSingleClue, delay, pattern[i]); // set timeout to play the clue
    delay += clueHoldTime;
    delay += cluePauseTime;
  }
}

function loseGame() {
  stopGame();
  alert("Game Over. You lost.");
}
function winGame() {
  stopGame();
  alert("Yayyyyy, you win!!");
}

function guess(btn) {
  console.log("user guessed: " + btn);
  if (!gamePlaying) {
    return;
  }
  if (pattern[guessCounter] == btn) {
    if (guessCounter == progress) {
      if (progress == pattern.length - 1) {
        winGame();
      } else {
        progress++;
        playClueSequence();
      }
    } else {
      guessCounter++;
    }
    //guessCounter++;
  } else {
    if (lostCount < 2) lostCount++;
    else loseGame();
  }
}
// Sound Synthesis Functions
const freqMap = {
  1: 261.6,
  2: 329.6,
  3: 392,
  4: 466.2,
  5: 432.8,
  6: 336.2,
};
function playTone(btn, len) {
  o.frequency.value = freqMap[btn];
  g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
  tonePlaying = true;
  setTimeout(function () {
    stopTone();
  }, len);
}
function startTone(btn) {
  if (!tonePlaying) {
    o.frequency.value = freqMap[btn];
    g.gain.setTargetAtTime(volume, context.currentTime + 0.05, 0.025);
    tonePlaying = true;
  }
}
function stopTone() {
  g.gain.setTargetAtTime(0, context.currentTime + 0.05, 0.025);
  tonePlaying = false;
}

//Page Initialization
// Initialize Sound Synthesizer
var context = new AudioContext();
var o = context.createOscillator();
var g = context.createGain();
g.connect(context.destination);
g.gain.setValueAtTime(0, context.currentTime);
o.connect(g);
o.start(0);

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

Try utilizing MutationObserver to monitor changes in various nodes

I am faced with a situation where I have elements in my HTML that are dynamically populated with text from an API. My goal is to check if all these elements have a value and then trigger a function accordingly. The current code I have only allows me to obs ...

The second tab on Bootstrap5's tab content feature seems to generate an endless amount of white

I am working on a project where I need to display statistics for both the current month and year. To organize this data, I created a card with tabs for each - one tab for the month and another for the year. By default, the month tab is loaded first. Howev ...

Is it feasible to share HTML5 media captures and display them in real-time on another page within the website?

Recently, I just learned about the html5 media capture API and I am excited to start experimenting with it. One thing that caught my attention is capturing the camera on the same page, but I haven't come across any information about streaming through ...

Arranging components in a horizontal layout on Jquery mobile

I'm completely new to Jquery mobile and I'm having trouble getting these elements aligned. Here's my code, but I need the two icons to line up horizontally with the caption "Heading". <h3>Heading</h3> <img src="../re ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...

Consider utilizing divs in a similar manner to tables

I typically use tables to align images and text, but they don't work well on mobile devices. I'd like to switch to using CSS and DIVs instead, even though I have no experience with them. My goal is to center three pictures with text above each o ...

"Enhance your web app with Emotion.js and Preact SSR, complete with

In my preact SSR application, I have utilized Emotion JS 10 for styling purposes. My goal was to incorporate RTL support into the app. To achieve this, I implemented createEmotion and createEmotionServer, leveraging the resulting renderStylesToString to r ...

Is it possible to use basic HTML for creating views within the Express framework?

I recently began using node.js in conjunction with the Express framework, but I'm finding it challenging to remove Jade and other templates from my project. I prefer writing my views in plain HTML. Can anyone provide guidance on how to achieve this? ...

Having difficulty identifying duplicate sentences in Vue.js when highlighting them

I am looking for a way to identify and highlight repetitive sentences within a text area input paragraph. I attempted the following code, but unfortunately, it did not produce the desired result. highlightRepeatedText(str) { // Split the string into an ...

The Axios-generated string I created is returning a 403 forbidden error due to a broken URL, however, it works perfectly fine

When Axios creates a string that combines multiple values to form a URL, it sometimes returns a 403 forbidden error due to a broken URL. For example, the following code works fine: const inventory = await axios.get("http://steamcommunity.com/inventory/765 ...

Sending an object from ng-repeat to a different page for the purpose of showcasing its contents

Currently, I am immersed in a project that involves MySQL, Angular, Express, and Node. Within this project, I have an array of objects displayed using ng-repeat. The goal is to allow users to click on a specific item and navigate to another page where they ...

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

When using jQuery, the onChange() function can be used to switch focus

Make sure to check out this fiddle first: http://jsfiddle.net/7Prys/ I am looking for a way to automatically focus on the next input field when a user enters a value in the previous field. This should happen until the fourth input field. Is there a simple ...

What is the best way to horizontally center my HTML tables and ensure that they all have uniform widths?

I'm currently facing an issue where I'd like to center align all tables similar to the 'Ruby Table.' However, I'm unsure of how to achieve this. You may also observe that some tables have varying widths. What CSS rule can I apply ...

Tips for patiently waiting for a series of asynchronous calls to successfully complete

I have a scenario where I am dealing with multiple asynchronous calls that are dependent on each other's success. For example: function1 = () => { /*Some required Logic*/ return fetch("myurl") .then((json) => { functi ...

React and Axios: Overcoming CORS Policy to Connect with Java/SpringBoot REST Backend Service

As a first-time user of Axios to connect to my Java/SpringBoot Rest GET service on localhost:8080, I am using React and node.js. My goal is to successfully retrieve the REST data but encountered the following error: Failed to compile src\App.js Lin ...

Is it possible to include an if/else statement within a tailwind class in React components?

I want to dynamically change the background color of a div based on a condition. If the condition is true, I want the background color to be white; otherwise, I want it to be black. Despite trying to achieve this using an if/else statement, the background ...

Creating a tree-like design with the spry accordion換stepping up your spr

I want to style my accordion in a way that it resembles a tree structure. How can I achieve this using CSS? For example: + should be displayed when the accordion tab is closed, and - when the accordion is open. <div class="Accordion" id="systemAccordi ...

What is the best way to disengage a loop of elements within an internship?

In my scenario, the DOM structure is as follows: <table id="campaigns"> <tr> <th>Name</th> <th>Status</th> </tr> <tr> <td>first data</td> </tr> <tr data- ...

JavaScript-Based Header Features Similar to Excel

Currently, I am in the process of developing a function that generates a sequence of strings similar to Excel headers. For those who may not be familiar with Excel, the sequence goes like this: A,B,...,Z,AA,...,AZ,BA,...,ZZ,AAA,...,etc. Here is the code ...