Memory game

by kpulkit29

HTML

<div id="app"></div>
    <div class="tiles">
      <div class="tile"></div>
      <div class="tile"></div>
      <div class="tile"></div>
      <div class="tile"></div>
      <div class="tile"></div>
    </div>
    <p class="count">
    Count: 
    </p>
    <button id="start">Start</button>

CSS

body {
  font-family: sans-serif;
}

.tiles {
  display: flex;
  align-items: center;
  justify-content: center;
}

.tile {
  width: 50px;
  height: 50px;
  border: 1px solid black;
}

JavaScript

let order = "";

function RandomGenerator() {
  this.count = 5;
  this.generated = [];
  this.order = "";
}

RandomGenerator.prototype.getRandomNumber = function() {
  return Math.floor(Math.random() * 5) + 1;
}

RandomGenerator.prototype.scoreCounter = function() {
  let children = document.querySelectorAll('.tiles .tile');
  let score = document.querySelector('.count');
  let count = 0, sequence = [], ans = 0;
  for (let i=0;i<children.length;i++) {
  	let node = children[i];
    node.addEventListener("click", () => {
      if (node.done) return;
      if(count>=this.generated.length) {
        return;
      }
      node.style.background = "blue";
      node.done = 1;
      if(this.generated[count] === i+1) ans++;
      console.log(ans);
      score.innerText = `Count ${ans}`;
      count++;
      if(count>=this.generated.length) {
          this.generated = [];
      }
    });
  }
}

RandomGenerator.prototype.generateColor = function() {
  let tiles = document.getElementsByClassName('tiles')[0];
  let children = document.querySelectorAll('.tiles .tile');
  for (let i = 0; i < this.generated.length; i++) {
    setTimeout(() => {
      children[this.generated[i] - 1].style.background = "blue";
      if (i === this.generated.length - 1) {
        for (let i = 0; i < this.generated.length; i++) {
          children[i].style.background = "white";
          this.scoreCounter();
        }

      }
    }, i * 500)
  }
}



RandomGenerator.prototype.generateRandomOrder = function() {
  const numbers = [1, 2, 3, 4, 5];

  while (numbers.length > 0) {
    const randomIndex = Math.floor(Math.random() * numbers.length);
    const number = numbers.splice(randomIndex, 1)[0];
    this.generated.push(number);
  }

  this.generateColor();
}

let randomObj = new RandomGenerator();
document.getElementById("start").addEventListener("click", () => {
  randomObj.generateRandomOrder();
});