-3

Im new to programming and trying to make a memory game. First I created 5 different flags in CSS that I would like to "play" with in my game. However I'm very stuck and have no Ideas how to proceed.

I know that I need some sort of function only allows two flags to be "clicked" at the same time and then another function that check if those two flags matches each other.

Any ideas how I could do that, and again very new to this.

    (function() {
  'use strict';

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

  var i;
  var j;


  //function that can shuffle the 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>';
  //var swedishFlag = '<div class="ruta"></div>';

  var japanFlag = '<div class="flag japan"><div class="part2"></div></div>';
  //var japanFlag = '<div class="ruta"></div>';

  var litauenFlag = '<div class="flag litauen"><div class="part1"></div><div class="part2"></div></div>';
  //var litauenFlag = '<div class="ruta"></div>';

  var elfenbenskustenFlag = '<div class="flag elfenbenskusten"><div class="part1"></div><div class="part2"></div></div>';
  //var elfenbenskustenFlag = '<div class="ruta"></div>';

  var tysklandFlag = '<div class="flag tyskland"><div class="part1"></div><div class="part2"></div></div>';
  //var tysklandFlag = '<div class="ruta"></div>';

  var swedishFlag2 = '<div class="flag sweden"><div class="vertikal"></div><div class="horisontell"></div></div>';
  //var swedishFlag2 = '<div class="ruta"></div>';

  var japanFlag2 = '<div class="flag japan"><div class="part2"></div></div>';
  //var japanFlag2 = '<div class="ruta"></div>';

  var litauenFlag2 = '<div class="flag litauen"><div class="part1"></div><div class="part2"></div></div>';
  //var litauenFlag2 = '<div class="ruta"></div>';

  var elfenbenskustenFlag2 = '<div class="flag elfenbenskusten"><div class="part1"></div><div class="part2"></div></div>';
  //var elfenbenskustenFlag2 = '<div class="ruta"></div>';

  var tysklandFlag2 = '<div class="flag tyskland"><div class="part1"></div><div class="part2"></div></div>';
  //var tysklandFlag2 = '<div class="ruta"></div>';

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

  //shuffles the flaglist
  flaglist.shuffle();
  class1.shuffle();


  //for (var i = 0; i < flaglist.length; i++) {
  for (var i = 0; i < 10; i++) {

    //document.body.appendChild(flaglist[i]);
    if (i < 5) {
      //flagTarget1.innerHTML += flaglist[i];
      flagTarget1.innerHTML += '<div class="ruta"></div>';

      //console.log('ritar ' + flaglist[i]);
    } else {
      //flagTarget2.innerHTML += flaglist[i];
      flagTarget2.innerHTML += '<div class="ruta"></div>';


    }

  }

  var flags = document.getElementsByClassName('ruta');

  //loop who adds their own ID to every flag-div.
  for (i = 0; i < flags.length; i++) {
    flags[i].setAttribute('id', 'flagga' + (i));
  }


  //loop who changes style.top on the first row of flags och spreads them out
  for (i = 0, j = 145; i < 5; i++, j += 200) {
    var temp = document.getElementById('flagga' + i);
    temp.style.left = j + 'px';
    temp.style.top = "50px";
  }

  //loop who changes style.top on the second row of flags och spreads them out
  for (i = 5, j = 145; i <= 9; i++, j += 200) {
    var temp = document.getElementById('flagga' + i);
    //console.log(temp);
    temp.style.left = j + 'px';
    temp.style.top = '210px';
  }


  var boxes = document.getElementsByClassName('ruta');
  //console.log('class name boxes ' + boxes[2]);


  // the array to hold clicked flag
  var flagQueue = [];

  function pickFlag(event) { //the event argument gets passed by default
    // event.target signifies the target of the event fired
    flagQueue.push(event.target.firstChild.className); // push the class string to array
    console.log(flagQueue);
    if (flagQueue.length == 2) { // if it has 2 elements,
      if (flagQueue[0] == flagQueue[1]) { // compare them
        console.log('Grattis, du hittade ett matchande par.');
      } else {
        console.log('Inget matchande par. Försök igen');
      }
      // whatever happens, reset the flagQueue array
      flagQueue.length = 0;
    }
  }

  //loop who adds event for boxes
  for (i = 0; i < boxes.length; i++) {
    boxes[i].addEventListener('click', function() {
      temp = document.getElementById(this.id);
      //console.log(temp);

      switch (this.id) {
        case 'flagga0':
          temp.innerHTML = flaglist[0];
          break;
        case 'flagga1':
          temp.innerHTML = flaglist[1];
          break;
        case 'flagga2':
          temp.innerHTML = flaglist[2];
          break;
        case 'flagga3':
          temp.innerHTML = flaglist[3];
          break;
        case 'flagga4':
          temp.innerHTML = flaglist[4];
          break;
        case 'flagga5':
          temp.innerHTML = flaglist[5];
          break;
        case 'flagga6':
          temp.innerHTML = flaglist[6];
          break;
        case 'flagga7':
          temp.innerHTML = flaglist[7];
          break;
        case 'flagga8':
          temp.innerHTML = flaglist[8];
          break;
        case 'flagga9':
          temp.innerHTML = flaglist[9];
          break;


        default:

      }


      //console.log('flaggnr ' + this.id);
      //console.log(temp);
    })
    boxes[i].addEventListener('click', pickFlag);
  }


})();

Okay, so I used the answer I got here and made it partially work. When I get two of the same it writes out a "congratulation". However I need help to get the cards/tiles to turn back around if they don't match and stay if they match. Any help would be appreciated.

Edit: I'm appreciate the help but I need couple of more things before everything works smoothly.

  1. The program thinks that flagQueue[0].className are the same as flagQueue[1].className even though it shouldn't be. I wrote a console.log(flagQueue) to check why and got this

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

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

  2. The first thing I do in pickFlag() is to make the flag "hidden", altough it's the first flags thats been pressed. Which If I'm not mistaken makes all the flags I pick "hidden"? Is it possible to compare the hidden flag with the original state of the flag (before the flag have been clicked?)

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

Thanks again!

A.Ga
  • 13
  • 3
  • If you have other questions, please create a new question and ask about different things. I believe, my answer in this thread is thorough and doesn't need improvement. As for the classList.toggle(), read the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) – Marian May 30 '16 at 18:28

1 Answers1

0

Welcome to Stackoverflow!

Please do consider internationalizing your code. Using variable names formed from English words, as well as using comments in English is helpful for people who try to help you.

I'd go with creating an array to hold the clicked flags. After you add a flag to it, check if it has 2 elements now. If it does, compare. If it doesn't, wait for next click.

// the array to hold clicked flag
var flagQueue = [];
function pickFlag(event){ //the event argument gets passed by default
    // event.target signifies the target of the event fired
    flagQueue.push(event.target.className); // push the class string to array
    if(flagQueue.length==2){                // if it has 2 elements,
        if(flagQueue[0]==flagQueue[1]){     // compare them
            alert('Congratulations');
        }
        else {
            alert('Try again');
        }
        // whatever happens, reset the flagQueue array
        flagQueue.length = 0;
    }
}

// Now we select all HTML elements with class flag
var flags = document.querySelectorAll('.flag');
// And we add an eventListener to each of them.
for(var i=0; i<flags.length; i++){
    flags[i].addEventListener('click',pickFlag);
}

EDIT

I have made a JSFiddle for you. The css is basic, just so you can see how the script works. If you click 2 of the same flags, you get 'Congratulations'. If you click 2 different flags, you get 'Try again'. Please note, that JSFiddle runs the JS code after it creates the page itself. So if you wnt to replicate my code in a browser, make sure that the <script> with my JS code is placed right before the </body>, so it starts running after all the elements on the page have been created.

If you want to create the flags in Javascript, use the following snippet should come in handy:

// create array to keep the html elements
var flagElements = [];
// put country names into an array
var countries = ['usa','japan','sweden','finland'];
// create new elements for each of the country names
for(var i=0;i<countries.length;i++){
    // first create a div element for the flag
    var flag1 = document.createElement('div');
    // set the class to 'flag <country>'
    flag.className = 'flag '+countries[i];
    //push it to the array
    flagElements.push(flag1);
    //then create a second flag, I will just use the same code
    var flag2 = document.createElement('div');
    flag2.className = 'flag '+countries[i];
    flagElements.push(flag2);
}
// Now you have an array holding all of the divs for you.
// All you need to do is shuffle them and append to DOM.
// You can find info about shuffling on stackoverlow, just implement something
myShufflingAlogirthm(flagElements);
// to append the elements just loop over them and append to body
for(var i=0;i<flagElements.length;i++){
    document.body.appendChild(flagElements[i]);
}

Also note, that you can edit your own post to include new informatin or clarify questions your answerers have. You can also add comments to other people's answers. Refer to stackoverflow help pages for more info on how to use the website, inluding asking, answering, reputation and more.

An example of shuffling algortihm

EDIT 2 Check out this fiddle for some ideas on how to implement flags going back to being hidden or leaving them up. I added a css class hidden and I just toggle it. I believe that this kind of thing should be solved by css, not by complicated code. Also notice, that I changed the eventListener a bit - now it pushes the HTML Element into array, instead of just the className.

Community
  • 1
  • 1
Marian
  • 3,789
  • 2
  • 26
  • 36