0

The following code adds a grid of door images to the page and changes the image to a monster when clicked. If a sock is revealed then I add a button to the page to allow the user to play again. Once you click the play again button the page will correctly reset the images to doors. The problem is that the doors will no longer reveal monsters. What am I missing? Thank you.

Complete code

/**
 * Randomly shuffle an array
 * https://stackoverflow.com/a/2450976/1293256
 * @param  {Array} array The array to shuffle
 * @return {String}      The first item in the shuffled array
 */
var shuffle = function(array) {

  var currentIndex = array.length;
  var temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;

};
// The monsters and socks
var monsters = [
  'monster1',
  'monster2',
  'monster3',
  'monster4',
  'monster5',
  'monster6',
  'monster7',
  'monster8',
  'monster9',
  'monster10',
  'monster11',
  'sock'
];

let count = 0;
const app = document.querySelector('#app');

const initGame = function() {
  shuffle(monsters);
  app.innerHTML = '<div class="row">' + monsters.map(m => {
    let html = '<div class="grid"><a href="#"><img src="monsters/door.svg" /></a></div>';
    return html
  }).join('') + '</div>';
}

initGame();

const addButton = function() {
  app.innerHTML += '<button>Play Again</button>'
  document.querySelector('button').addEventListener('click', () => {
    initGame();
    count = 0;
  });
};

const doors = Array.prototype.slice.call(document.querySelectorAll('.grid'));

doors.forEach((d, i) => {
  d.addEventListener('click', (e) => {
    d.innerHTML = '<a role="button" href="#"><img src="monsters/' + monsters[i] + '.svg" /></a>';
    if (monsters[i] == 'sock') {
      alert('You lost. Click play again if you want another try.');
      addButton();
    } else {
      count++;
      if (count == monsters.length - 1) {
        alert("You Won!!!");
        addButton();
      }
    }
  });
});
<body>
  <h1>Monsters!</h1>
  <div id="app"></div>
</body>
Daweed
  • 1,419
  • 1
  • 9
  • 24
martinbshp
  • 1,073
  • 4
  • 22
  • 36

1 Answers1

1

you are attaching the event listeners only once when main script executes, then on next play initGame only create doors without listeners, you should put the elements initialization inside initGame, like this:

<h1>Monsters!</h1>

<div id="app"></div>

<script>
    /**
     * Randomly shuffle an array
     * https://stackoverflow.com/a/2450976/1293256
     * @param  {Array} array The array to shuffle
     * @return {String}      The first item in the shuffled array
     */
     var shuffle = function (array) {
    
    var currentIndex = array.length;
    var temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
        // Pick a remaining element...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;
    }

    return array;

};
    // The monsters and socks
    var monsters = [
        'monster1',
        'monster2',
        'monster3',
        'monster4',
        'monster5',
        'monster6',
        'monster7',
        'monster8',
        'monster9',
        'monster10',
        'monster11',
        'sock'
    ];

    let count = 0;
    const app = document.querySelector('#app');

    const initGame = function() {
        shuffle(monsters);
        app.innerHTML = '<div class="row">' + monsters.map(m => {
            let html = '<div class="grid"><a href="#"><img src="monsters/door.svg" /></a></div>';
            return html 
        }).join('') + '</div>';

      const addButton = function() {
          app.innerHTML += '<button>Play Again</button>'
          document.querySelector('button').addEventListener('click', () => {
                      initGame();
                      count = 0;
                  });
      };

      const doors = Array.prototype.slice.call(document.querySelectorAll('.grid'));

      doors.forEach((d,i) => {
          d.addEventListener('click', (e) => {
              d.innerHTML = '<a role="button" href="#"><img src="monsters/' + monsters[i] + '.svg" /></a>';
              if (monsters[i] == 'sock') {
                  alert('You lost. Click play again if you want another try.');
                  addButton();
              } else {
                  count++;
                  if (count == monsters.length - 1) {
                      alert("You Won!!!");
                      addButton();
                  }
              }
          });
      });
    }

    initGame();
    

</script>
n--
  • 3,563
  • 4
  • 9