Tips on introducing a random pattern into a Javascript gaming experience

To kick off the game, let's generate a pattern randomly. Follow these steps:

-Include a function that generates the pattern. (Hint: JavaScript's Math.random function might come in handy) -Invoke your new function from the startGame function

I'm facing difficulties with this task. I'm unsure about how to produce random numbers from the array named pattern and have them play as clues in a random order.

JS File:

//Global Contants

const cluePauseTime = 333; //duration of pause between clues
const nextClueWaitTime = 1000; //waiting time before starting playback of the clue sequence

//Global variables
var clueHoldTime = 200; //duration each clue's light/sound stays on
var pattern = [2, 3, 1, 4, 6, 1, 2, 4, 3, 5];
var progress = 0;
var gamePlaying = false;
var tonePlaying = false;
var volume = 0.5;
var guessCounter = 0;

function startGame() {
  progress = 0;
  
  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 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; //initialize delay as initial wait time
  for (let i = 0; i <= progress; i++) {
    // for each revealed clue 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

Take a look at this resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

If you are looking to generate random numbers, the following function will do the trick.

function getRandomInt(max) {
 return Math.floor(Math.random() * Math.floor(max) + 1); // Adding 1 to avoid getting 0
}

To populate an array with random numbers, simply call this function in a loop at the beginning of your process. Here's an example:

var numbers = [];
var limit = 10;

function generateNumbers() {

numbers = []; // Resetting the array before adding new numbers
for (var i = 0; i < limit; i++) {
  numbers.push(getRandomInt(5));
}
console.log('Generated numbers: ' + numbers);

counter = 0;

gameOn = true;

document.getElementById("startGameBtn").classList.add("hidden");
document.getElementById("stopGameBtn").classList.remove("hidden");

playNumberSequence();

}

You can find my updated version with the changes on JSFiddle. https://jsfiddle.net/dm5pq4cr/2/

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

Incorporating onPause and onResume functionalities into a YouTube video featured on a page built with Ionic 2

I'm encountering a minor problem with a simple demo Android app built in Ionic 2. Whenever a Youtube video is playing on the Homepage, if the power button is pressed or the phone goes into sleep/lock mode, the Youtube video continues to play. This is ...

What is the best way to ensure PyScript is completely initialized, including the environment?

Hey there! I'm hoping to catch a specific message being logged in my browser's console by a script I added to my HTML file, and then trigger a JavaScript action based on that. For instance, when "ABCD:READY" appears in the console, I want to cal ...

CSS dimensional changes

I am currently working on developing an application that involves incorporating a perspective map with the ability to add map markers represented by absolutely positioned DIVs. However, I seem to be encountering challenges related to transformations and 3D ...

Experiencing challenges during the creation of a NUXT build

Trying to build a Nuxt SSR app, but encountering an error related to the css-loader during the build command execution. The issue seems to be with Invalid options object. ERROR in ./node_modules/vue2-google-maps/dist/components/streetViewPanorama.vue (./no ...

Attempting to establish a login system using MongoDB

I am currently working on a function to verify user login details entered in a form and compare them with data stored in MongoDB, such as email and password. However, the function seems to be malfunctioning. The expected behavior is that when a user ente ...

Challenges with adjusting the dimensions of varying-sized fluid squares that are floated

I've been facing a roadblock in my coding project since yesterday afternoon. I'm trying to transform a classic unordered list menu into a tiled "gallery" within a 12 column grid, with fluid square tiles. When the squares are floated, the first s ...

Why does modifying a variable within the fetch URL result in undefined

I currently have a server running on the URL http://localhost:3000/. Within my JavaScript code, I have defined a variable called productCode with the value 'example-code55'. let productCode = 'example-code55'; const fetchData = async ...

Different parameters in an Angular filter pipe

Currently, I am facing a challenge in implementing multiple filters on a pipe for a search result page that retrieves data from an API. How can I integrate different parameters into this filter pipe successfully? Access the application here: https://stack ...

Android Troubleshooting: Audio Issue with Hybrid App

Currently, I am utilizing Monaca.mobi to develop a hybrid app. Interestingly, when I compile the app for IOS, everything runs smoothly; however, there seems to be an issue with audio playback on an android device (specifically Nexus 7). Strangely enough, i ...

Styling sub-table titles in jQuery jTable with proper indentation

I am currently implementing jquery.jtable, where I have rows that invoke the openChildTable method in the jquery.jtable.js file. I'm attempting to figure out a way to indent the heading of the child table. Below is the code snippet responsible for cr ...

Is it possible to implement counters in CSS with Jquery?

I am trying to implement a specific style when an if statement is executed, but Jquery is encountering syntax issues and generating errors. Does anyone have a solution for escaping these errors so that I can still apply the desired styling? The problemati ...

Add Text to Bootstrap Modal Window

The bootstrap modal body is not containing all of my content and some of it is overflowing. <div class="modal fade" tabindex="-1" role="dialog" id= "blockModel"> <div class="modal-dialog"> <div class="modal-content"> < ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Encountering an error when attempting to reach a JSON endpoint using Javascript and X-Auth-Token

I'm attempting to retrieve data from a JSON endpoint using JavaScript and X-Auth-Token, but I am continuously encountering errors. The data is from a sports API, and despite diligently following all the instructions in the documentation and checking m ...

What is preventing me from accessing these attributes using "${array[a].name}"?

What is preventing me from reading the properties using ${ array[a].name } with For Of loop? I created an example with an array of objects to help diagnose the problem. const movies = [{ title: "Shrek", year: 2001 }, { title: "Shrek 2", ...

Applying CSS dynamically to a mat-cell in Angular 6

In my material table, I need to apply specific CSS classes based on the content of the cell. https://i.sstatic.net/YN6EO.png These are the CSS classes that I am using .status-code{ flex: 0 0 10% !important; width: 10% !important; } .status-code- ...

Tips for successfully passing an image using props in Vuejs without experiencing the issue of disappearing content when there is no image present

Is there a way to make a component that can function with or without an image? Currently, when the component doesn't have an image, other contents and styles disappear. How can I resolve this issue? App.Vue: <template> <div id="app&qu ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

Can you align a row under its corresponding column in Bootstrap?

Hello, I'm facing a dilemma with my layout. I have a grid consisting of 2 Rows and 4 Columns (col-md-8 & col md-4 in each row). The structure is as follows: Within the container Row 1 Column 1 (md-8) Row 1 Column 2 (md-4) [Accordion] Row 2 Colum ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...