What is the best way to mix up the images in my memory game?

My JavaScript memory game is functioning properly, but I would like the images to load in a random order. Unfortunately, I'm not sure how to accomplish this.

Here is the current setup:

var easyImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg",
    "img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg"];

var hardImages = ["img/bat.jpg", "img/bug.jpg", "img/cat.jpg", "img/dog.jpg",
    "img/frog.jpg", "img/fly.jpg", "img/bat.jpg", "img/bug.jpg",
    "img/cat.jpg", "img/dog.jpg", "img/frog.jpg", "img/fly.jpg"]

var imagesToShow;

var imagesContainer = document.getElementById("images-container");

var questionMark = "img/memory-bg.jpg";


if (selectedDifficulty == "easy") {
    imagesToShow = easyImages;
}

else if (selectedDifficulty == "hard") {
    imagesToShow = hardImages;
}

imagesContainer.innerHTML = "";

if (imagesToShow !== "") {
    for (var i = 0; i < imagesToShow.length; i++) {
        var img = document.createElement("img");

        img.addEventListener("click", flipImage);

        img.src = questionMark;

        img.dataset.img = imagesToShow[i];

        imagesContainer.appendChild(img);
    }
}

Answer №1

Here's a possible solution:

const animalImages = ["img/lion.jpg", "img/zebra.jpg", "img/giraffe.jpg", "img/elephant.jpg",
"img/lion.jpg", "img/zebra.jpg", "img/giraffe.jpg", "img/elephant.jpg"];

let totalAnimals = 8;
while(animalImages.length < totalAnimals){
  let randomAnimal = Math.ceil(Math.random()*100);
  let foundMatch = false;
  for(let i=0; i<animalImages.length; i++){
    if(animalImages[i] == randomAnimal){foundMatch = true; break;}
  }
  if(!foundMatch) animalImages[animalImages.length] = randomAnimal;
}

Answer №2

One creative solution is to form a new array containing the images you wish to showcase. Utilizing a random number generator, select a random index from this array ensuring that the range falls within its length; otherwise, you may obtain indices beyond your intended selection. Subsequently, eliminate the image element corresponding to this position in the array, resulting in a collection of pictures that have yet to be exhibited.

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

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

Testing the Limits of CSS Hover

I'm having trouble figuring out how to implement this. When hovering, a yellow square/background should appear with an offset similar to the one in the image below. I am utilizing bootstrap for this project. Any assistance or guidance would be greatl ...

Removing an HTML element entirely

Although I am utilizing .remove() method and it is effectively removing the desired element, upon inspecting the page source by right-clicking in a browser window, I can still see those removed elements. It seems like they are not being permanently delet ...

Leverage JavaScript libraries utilizing namespaces within your Angular application

I have a unique JavaScript library that includes functions organized within namespaces. For example: var testNamespace = { insideFunction: function(str) { alert(atr); } }; Now, I am trying to integrate these functions into my Angular app.c ...

Bluebird Enthusiastically Predicting the Outcome of a Complex Operation

Lately, I've been heavily utilizing Bluebird in my HAPI API development. However, I've encountered a perplexing issue that has left me puzzled due to either my understanding or lack of experience. Below is an example demonstrating the challenge ...

Adjust the CSS of a nested div within the currently selected div upon page load

I am facing an issue with a page that users access by clicking through an ebook. Upon clicking a link, they are directed to a specific product on the page, and the URLs look like example.com/#product1 example.com/#product6 example.com/#product15, etc... ...

Display a pleasant alert message when the file is not recognized as an image during the loading

Is there someone who can assist me? I have attempted multiple times but without success. How can I display a sweet alert when a file is selected that is not an image? <input type ="file" /> ...

Uploading a file to NodeJS via POST and seamlessly forwarding it to another API without storing it on disk

In order to transfer a file from a user through a React UI (with axios), then send it to a NodeJS method via POST using Express, and finally forward the same file directly to another API (.NET WebAPI) without saving it to disk, I am faced with an issue whe ...

Tips for stopping html form from refreshing upon submission

Hello, despite extensive searching and testing, I am still unable to locate the issue and therefore I am reaching out to seek your assistance in resolving my problem. Within a form that I have created, upon clicking the submit button, a javascript functio ...

The array does not seem to be properly linked in React JS

I've been encountering this error even after trying various solutions based on my knowledge. Any help would be greatly appreciated. The issue arises when I attempt to pass an array in props, retrieve it in the component, and then set the props value ...

When redirecting to the same component, Vue.js hooks are not triggered

In my Vuejs project, I have two pages located at the same level with a common component. However, when I redirect from post/new to post/edit/:id, the beforeMount method is not being called. redirect() { this.$router.push({path: `home/post/edit/${this ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Zurb's Vertical Navigation Bar: A Stylish and Functional Design

I attempted to replicate the left navigation bar from this link: The responsive navigation bar and contents on the right caught my attention. Currently, I am working on a project that requires a similar navigation bar. While I am proficient in HTML and C ...

Analyzing the structure according to the month/week/year

My array consists of count and date values: day = [ { count: 1, date: '2022-07-07' }, { count: 1, date: '2022-08-14' }, { count: 2, date: '2022-07-19' }, { count: 4, date: '2022-07-19' }, { count: 2, date: ...

What are the steps to apply an AngularJS filter for formatting values within an array?

While I have experience using angular filters for formatting primitive values like numbers into currency formats, I am now faced with the challenge of applying the same filtering to an array of values. For example: price = 1 prices = [1,2,3] If I were to ...

Is nested testing the key to an elegant JQuery/AJAX form validation solution?

As I implement form validation with JQuery/AJAX, my goal is to provide a seamless experience for users. When an entry is missing or incorrect, I aim to display a single alert message and return the user to the form so they can make adjustments and resubmit ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Is there a way to automatically scroll the parent page's top when the user navigates within an iframe?

We are encountering an issue with the loading of the iFrame. When the iFrame loads on the client's page, we notice that the page location jumps around and, in most cases, the page focus is lower down the page. This requires users to scroll up to view ...

Starting the Android System Magnifier with a Click: A Step-by-Step Guide

Is there a way to incorporate a magnifying glass into an HTML page using jQuery or within an Android app? Ideally, it would be for a single picture. In my application, I am displaying an HTML file from my assets in a webview. The HTML page utilizes jQuery ...

EJS include function not working properly

In most cases, my EJS pages include the code below: <%- include('elements/fbviewpagepixel.ejs') %> Everything runs smoothly except for one particular page where I encountered an error message stating include is not a function. I managed t ...