JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next.

I understand that I need some functions to handle the clicking of two flags at a time and then check if they match each other. Any suggestions on how I can accomplish this? Please keep in mind that I am very new to all of this.

    (function() {
  'use strict';

  var flagTarget1 = document.getElementById('flag1');
  var flagTarget2 = document.getElementById('flag2');

  var i;
  var j;


  //Function for shuffling an array
  Array.prototype.shuffle = function() {
    var input = this;
    for (var i = input.length - 1; i >= 0; i--) {
      var randomIndex = Math.floor(Math.random() * (i + 1));
      var itemAtIndex = input[randomIndex];
      input[randomIndex] = input[i];
      input[i] = itemAtIndex;
    }
    return input;
  }



  var swedishFlag = '<div class="flag sweden"><div class="vertikal"></div><div class="horisontell"></div></div>';
  
  // Code for other flags omitted for brevity

  // List of classes
  var class1 = ['sweden', 'litauen', 'japan', 'tyskland', 'elfenbenskusten', 'sweden', 'litauen', 'japan', 'tyskland', 'elfenbenskusten']
    
  // List of flags
  var flaglist = [swedishFlag, japanFlag, litauenFlag, elfenbenskustenFlag, tysklandFlag, swedishFlag2, japanFlag2, litauenFlag2, elfenbenskustenFlag2, tysklandFlag2];

  // Shuffling the flag list
  flaglist.shuffle();
  class1.shuffle();

  // Rendering flags on the screen
  
  // Event listener code omitted for brevity

})();

After implementing some advice I received, I managed to make part of the game work. When two matching flags are found, a "congratulations" message is displayed. However, I still need help figuring out how to flip the cards back over if they don't match while keeping them visible if they do match. Any guidance would be highly appreciated.

Edit: I really appreciate the assistance so far, but I have a few more hurdles to overcome before the game runs smoothly.

  1. The program mistakenly identifies identical class names within flagQueue[0] and flagQueue[1]. I used console.log(flagQueue) to investigate and discovered this

    [div#flagga0.ruta.hidden, div#flagga5.ruta.hidden]

    Congratulations it's a pair (even though it isn't)

  2. At the start of pickFlag(), the first action taken is to hide the flag, even when the initial flag has been clicked. This results in all subsequent flags being hidden as well. Is there a way to compare the hidden flag with its original state before being clicked?

fiddle: https://jsfiddle.net/b05sdy9o/

Thank you once again!

Answer №1

Welcome to Stackoverflow! We're glad you're here.

It's important to keep internationalization in mind when writing your code. Using English variable names and comments can make it easier for others to assist you with your coding questions.

A good approach would be to create an array to store the clicked flags. Once a flag is added, check if the array now contains 2 elements. If it does, compare them. If not, wait for the next click event.

// Code snippet to handle clicked flags
var flagQueue = [];
function pickFlag(event){
    flagQueue.push(event.target.className);
    if(flagQueue.length==2){
        if(flagQueue[0]==flagQueue[1]){
            alert('Congratulations');
        }
        else {
            alert('Try again');
        }
        flagQueue.length = 0;
    }
}

// Select all HTML elements with class flag
var flags = document.querySelectorAll('.flag');

// Add eventListener to each flag element
for(var i=0; i<flags.length; i++){
    flags[i].addEventListener('click',pickFlag);
}

UPDATE:

I've created a JSFiddle for you to see the functionality in action. Feel free to experiment with it. Remember that JSFiddle may run the script after creating the page, so ensure the script tag is placed before the closing body tag in your own implementation.

If you need to generate flag elements dynamically using JavaScript, you can follow this example code snippet:

// Generating flag elements dynamically
var flagElements = [];
var countries = ['usa','japan','sweden','finland'];

for(var i=0;i<countries.length;i++){
    var flag1 = document.createElement('div');
    flag.className = 'flag '+countries[i];
    flagElements.push(flag1);

    var flag2 = document.createElement('div');
    flag2.className = 'flag '+countries[i];
    flagElements.push(flag2);
}

// Shuffle the elements and append to the DOM
myShufflingAlogirthm(flagElements);
for(var i=0;i<flagElements.length;i++){
    document.body.appendChild(flagElements[i]);
}

Feel free to edit your post or add comments to provide additional information. Check out Stackoverflow help pages for more guidance on using the platform effectively.

You can also explore different shuffling algorithms like the one mentioned here.

UPDATE 2: Take a look at this modified fiddle for ideas on toggling flags between hidden and visible states using CSS classes instead of complex code logic. I adjusted the eventListener to push HTML Elements into the array for better handling.

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

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...

AngularJS's ScrollTo function allows users to scroll to a specific

Trying to implement a quick nav that smoothly scrolls to different sections on the page when a link is clicked. Currently using a guide provided by Treehouse for reference. $("#quickNav a").click(function(){ var quickNavId = $(this).attr("href"); ...

Using orchestrate.js for local passport.js authentication

I need assistance finding a tutorial or resources for setting up local passport.js authentication with Orchestrate as the user storage. Most of the resources I have come across are based on MongoDB, but our project requires us to use Orchestrate. Any advic ...

Ensure to first close the existing global connection before attempting to establish a new one in your Node.js Post WebApi application

Currently, I am in the process of creating a small post WebAPI using node.js to collect user data such as names and numbers. However, when I have an excessive number of users accessing this web API, I encounter the following error message: "node.js Global ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

Obtain information from express middleware

I am currently working on a project using node.js. As part of my application, I have developed a middleware function that is triggered whenever a GET request is made. This occurs when someone visits the home page, profile page, or any other page within my ...

Select the Best jQuery Package

Having a variety of packages available for selection. <div class="image-grid-item" data-search="select"> <input name="pack1" type="checkbox" style="display: none;"> </div> <div class="image-grid-item" data-search="select"> <inp ...

Persuading on the Server-Side

After reading through the Google-Caja wiki, I became intrigued by its capabilities. From what I understand, with Caja we can send a snippet of HTML (such as a ) to Google-Caja's server (cajoling service) for processing. The HTML is cajoled and the Jav ...

Attempting to adjust the width of a text animation loaded with jQuery using Textillate, but encountering difficulties

I found a captivating animation on this website: http://codepen.io/jschr/pen/GaJCi Currently, I am integrating it into my project. #content { position: relative; margin-left: auto; margin-right: auto; width: 1000px; height: 700px; } ...

Dealing with error management in Transfer-Encoding chunked HTTP requests using express and axios

My current challenge involves fetching a large amount of data from a database in JavaScript using streaming to avoid loading all the data into memory at once. I am utilizing express as my server and a nodeJS client that retrieves the data using Axios. Whil ...

IE encounters issues making Ajax calls when transitioning from secure HTTPS requests to insecure HTTP requests

I am currently facing an issue with my ajax CORS request. It is functioning perfectly on all browsers except for Internet Explorer. In IE, the request doesn't even attempt to go through and fails instantly without any error messages appearing in the c ...

Turn off the scrollbar without losing the ability to scroll

Struggling with disabling the HTML scrollbar while keeping the scrolling ability and preserving the scrollbar of a text area. Check out my code here I attempted to use this CSS: html {overflow:hidden;} Although it partially worked, I'm not complete ...

Error: The parent class is not defined as an object

My program is currently attempting to utilize this.state, but I encountered an error. Can anyone provide assistance on resolving this issue? https://i.stack.imgur.com/wgxBf.png ...

Delete outdated information using Google Apps Scripts when the date is less than the current date plus a specified number of days

I have a Google Sheet where I need to filter out entries based on the number of days since the last check. Specifically, I want to keep only those entries where the number of days since the last check is greater than 10. You can find the Sheet here. fu ...

Is it possible for me to send transactions asynchronously using polkadot-js?

After thoroughly going through the official documentation, I stumbled upon a page discussing how to transfer using polkadot-js const transfer = api.tx.balances.transfer(BOB, 12345); const hash = await transfer.signAndSend(alice); I am curious if it' ...

Transmitting Data via Socket.io: Post it or Fetch it!

I am struggling to send data via POST or GET in socket.io without receiving any data back. My goal is to send the data externally from the connection. Take a look at the code snippets below: Server-side code: app.js io.sockets.on('connection', ...

A guide on retrieving the selected option from a dropdown menu with React Material UI

Utilizing Material UI React, I am constructing a dropdown menu containing various options. My concern is: if I choose two options from different dropdowns within the menu, how can I intercept or store which option was selected? Below is a snippet of my co ...

html interactive/expandable tree

I've come across this code which generates an HTML tree, but I'm facing an issue where the tree expands every time I refresh the page. What I want to achieve is to have certain branches expanded and others collapsed when the page is opened, depe ...

Having difficulty in dynamically loading an image from an API's URL in Angular

In the title, I mentioned that I am utilizing a free API to display cryptocurrency news for my practice project. Everything seems to be working fine except for displaying the images in card view. I will share my code here, so if you have any suggestions on ...

How can I assign a default value for a multiple select dropdown list in AngularJS?

I am currently facing an issue with my multiselect dropdown. The code for the dropdown is as follows: <select id="year" multiple ng-model="type" ng-disabled="!type1" > <option value="all" selected>all</option>; <option value= ...