Having trouble figuring out how to make images revert back when matched incorrectly

Currently working on developing a straightforward card matching game.

The goal is to have two distinct cards selected in the game, they will flip back over, and you will consume a turn. If the two cards match, they will remain turned over, and you will gain both a point and use up a turn.

Yet, I am uncertain whether my code is able to determine if the cards are identical or not.

Presented below is the snippet of my code:

// Declaring global variables
const cards = document.getElementsByClassName('card');
let movesDisplay = document.querySelector('.move-counter');
let toggledCardsArray = [];
let move = 0;
let winCount = 0;
const restart = document.getElementById('restart');

const imagesLinkArray = [
    { id: 1, image: './assets/talisman1.png', newAlt: 'talisman1' },
    { id: 2, image: './assets/talisman2.png', newAlt: 'talisman2' },
    { id: 3, image: './assets/talisman3.png', newAlt: 'talisman3' },
    { id: 4, image: './assets/talisman4.png', newAlt: 'talisman4' },
    { id: 5, image: './assets/talisman5.png', newAlt: 'talisman5' },
    { id: 6, image: './assets/talisman6.png', newAlt: 'talisman6' },
    { id: 7, image: './assets/talisman1.png', newAlt: 'talisman1' },
    { id: 8, image: './assets/talisman2.png', newAlt: 'talisman2' },
    { id: 9, image: './assets/talisman3.png', newAlt: 'talisman3' },
    { id: 10, image: './assets/talisman4.png', newAlt: 'talisman4' },
    { id: 11, image: './assets/talisman5.png', newAlt: 'talisman5' },
    { id: 12, image: './assets/talisman6.png', newAlt: 'talisman6' }
];

// Restarting the game
const restartGame = () => {
    const toggledCards = document.querySelectorAll('.card.toggled');
    toggledCards.forEach((card) => {
        card.classList.remove('toggled');
    });

    // Shuffling the imagesLinkArray
    imagesLinkArray.sort(() => Math.random() - 0.5);

    // Resetting game state
    toggledCardsArray = [];
    move = 0;
    winCount = 0;
    movesDisplay.innerText = `Turn(s): ${move}`;

    // Updating card images
    const allImagesSrc = document.querySelectorAll('.card-img');
    allImagesSrc.forEach((el, index) => {
        el.src = imagesLinkArray[index].image;
        el.alt = imagesLinkArray[index].newAlt;
        el.id = imagesLinkArray[index].id;
    });
};

// Adding event listener to the restart button
restart.addEventListener('click', restartGame);

// Handling card clicks
for (let i = 0; i < cards.length; i++) {
    cards[i].addEventListener('click', function () {
        if (this.classList.contains('toggled') || toggledCardsArray.length === 2) return;

        this.classList.add('toggled');
        toggledCardsArray.push(this);

        if (toggledCardsArray.length === 2) {
            let firstCardSrc = toggledCardsArray[0].querySelector('.card-img')?.src;
            let secondCardSrc = toggledCardsArray[1].querySelector('.card-img')?.src;

            if (firstCardSrc === secondCardSrc) {
                winCount++;
                toggledCardsArray = [];
            } else {
                setTimeout(() => {
                    toggledCardsArray.forEach((card) => {
                        card.classList.remove('toggled');
                    });
                    toggledCardsArray = [];
                }, 500);
            }

            move++;
            movesDisplay.innerText = `Turn(s): ${move}`;

            if (winCount === 6) {
                setTimeout(() => {
                    alert(`Congratulations!!! You won the game in ${move} moves.`);
                }, 300);
            }
        }

I have attempted to delve deep into Geek4Geeks for reference since it was inspired by a similar game from their platform. However, their code does not yield the same results as mine when handling flipped cards.

Answer №1

Take a look at the code snippet below for guidance on implementing card-flipping behavior. Make sure to update the Image array with the correct image paths.

const gameBoard = document.getElementById('game-board');
const movesDisplay = document.querySelector('.move-counter');
const restart = document.getElementById('restart');

let toggledCardsArray = [];
let move = 0;
let winCount = 0;

const imagesLinkArray = [{
    id: 1,
    image: './assets/talisman1.png',
    newAlt: 'talisman1'
  },
  ...
];


const shuffleArray = (array) => { // Function to shuffle the images array
  return array.sort(() => Math.random() - 0.5);
};


const createCards = () => { // Generating the cards dynamically
  ...
};


const restartGame = () => { // Restarting the game if needed
  ...
};

const handleCardClick = (card) => { // Handling click events on the cards
  ...
};

const addCardClickListeners = () => {
  ...
};
restart.addEventListener('click', restartGame);
restartGame();
body {
  font-family: Arial, sans-serif;
  text-align: center;
  margin: 0;
  padding: 0;
}
...
<html lang="en">

<head>
  <title>Card Matching Game</title>
</head>

<body>
  <h1>Card Matching Game</h1>
  <div class="controls">
    <div class="move-counter">Turn(s): 0</div>
    <button id="restart">Restart</button>
  </div>
  <div class="game-container" id="game-board">
  </div>
</body>

</html>

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

Expand the accordion and incorporate both a hyperlink and an anchor tag within the content

My go-to source for codes is usually https://www.w3schools.com. They also provide an accordion feature along with the code; However, I've encountered an issue where when a link is used -> to The accordion doesn't open but remains closed. Does ...

Center-aligned footer with a sleek right border in Bootstrap 4.1.1

Presenting my design concept for the footer: https://i.sstatic.net/kxdXJ.png Here is the code snippet for the footer design utilizing Bootstrap 4.1.1: .mainfooter-area { background: #404044; padding: 100px 0; } ... <link href="https://cdnjs.cl ...

What is the best way to eliminate borders on a span element so they collapse seamlessly?

When using the tryit editor on this html and narrowing the result window (to around 200px), the border ends up inside the span as it spans across multiple lines. Is there a way to make the border "collapse" so that it forms a single irregular border around ...

Pause the audio using jQuery when the slide changes

I have a Drupal website with a slider that includes an audio player on each slide. I need the audio to stop whenever the slide changes. The slider plugin I'm using is owlCarousel. Here is my current code: $("#owl-demo").owlCarousel({ afterAction: ...

If the $_POST['data'] parameter is not defined, it could mean that the data being passed is too large

I am encountering an issue where I need to send a approximately 10MB json data within a textarea named "data". Strangely, when the data size is between 1-2KB, it works perfectly fine. However, with larger json files, the $_POST['data'] appears to ...

the concept of constructors in C# and how they are used with structs

My data is structured in a way that I would ideally like to represent as follows: LinkedList<T>[] However, due to restrictions on generics, I had to wrap it in a struct: public struct SuitList { LinkedList< ...

Issues with JavaScript Regular Expressions failing to match patterns

Good morning! I've encountered an issue with a JavaScript regular expression that I can't seem to troubleshoot. My script is making a call to the API provided by , and receiving a JSON response containing monitor statuses. However, this JSON st ...

Switching the ng-class in Angular with a click event

I'm having trouble modifying a class I've created based on a value from JSON, and then changing it when the user clicks on it. Here's my code in the controller: $scope.like = function(){ if ($scope.class === "ion-ios-heart-outline") ...

How can I focus on a particular P element within this Div using CSS?

I am attempting to target a paragraph element within the code snippet below. I want to create a class that applies text-shadow to the text of that specific paragraph. However, I am unsure which class to focus on and what the correct syntax should be. I in ...

Unable to locate the required conditional template for the 'mdRadioButton' directive due to the absence of the 'mdRadioGroup' controller

I am currently working on developing a custom directive that will help me display questions within a survey. Given the multiple types of questions I have, I decided to create a single directive and dynamically change its template based on the type of quest ...

Dividing an array by the highest values in two columns: a guide

Looking to divide a numpy array based on the values of two columns, separating when both reach their maximum at the same time. Even though each column reaches its max individually multiple times, I need to split specifically when they are both at their hig ...

Advantages and drawbacks of utilizing both of these HTML codes for generating an image

Could you explain the distinction between creating the image in these two code snippets? <link href="img/favicon.ico" rel="icon" type="image/png"> compared to initiating it using a simple <img /> tag I'm t ...

Implementing full-width responsive background images with srcset and lazy loading for optimal performance

I'm currently developing a website with a striking layout featuring 'hero' panels that cascade down the home page, showcasing text overlaid on captivating background images. My goal is to utilize inline images with srcset and sizes attribut ...

What is the process for identifying the ActiveX control being referenced on a webpage?

After developing a web application using ASP.NET Web Forms, I encountered a challenge with a client who has strict security policies. Whenever they try to access the web page, Internet Explorer displays a message stating: Your security settings do not all ...

Tips for Rectifying Axis Label Formatting in Highcharts while containing the contents within a div Tag

Take a look at the current appearance of the chart here: https://i.sstatic.net/j5IHb.png I am hoping to show a tooltip when someone hovers over one of the X-axis labels. To achieve this, I have adjusted the formatting as recommended here: labels: { useHTM ...

Tips for utilizing the <br> element within a Bootstrap card?

Is there a way to break the line after "Other online payment" without affecting the card content alignment in bootstrap? Adding the <br> tag is causing issues with the alignment. Any thoughts on why this is happening? Thank you :) .user-ads { fo ...

Troubleshooting problem with table reflow in Bootstrap v4.0.0-alpha.3 on mobile devices

I am having trouble fixing the table-reflow issue in mobile view while trying out the code below. Any suggestions on how to resolve this would be greatly appreciated. Check out the image here To see the code, visit CODEPEN <div class="container"> ...

Recursive React Function for Rendering Components

I've been working on integrating a react-bootstrap component into a custom navBar component in my react project. I have a recursive function set up to render the components and drill down until there are no more NavItem components nested under the Nav ...

Why is the variable not defined when it is supposed to be?

Hey there, I'm having an issue where I'm trying to trigger a PHP function whenever a button is clicked, but unfortunately I keep encountering an error mentioned in the title. This is how I am attempting to call the function: echo("<th>< ...

How can I handle pings in Discord using discord.js?

I've been working on a feature in my discord.js bot that responds to pings, but I'm running into issues. Even after trying <@BOTID> and @BOT#0000, the functionality is not behaving as expected. Here's the snippet of code I'm using ...