[WIP] MemoryJS

an attempt to create a memory game in JS

by Julien Roy

HTML

<h2>
Memory JS
</h2>

<div id="cards">

</div>
Nombre de coups: <span id="score"></span>

<div id="game">
</div>

CSS

#cards,
#game {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap
}

.card {
  margin: 2px;
  width: 60px;
  height: 100px;
  border: 1px solid black;
  border-radius: 2px;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  display: flex;
  color: #1C90F3;
  background-color: #1C90F3;
  background-clip: content-box;
  padding: 5px;
}

.found {
  background-color: green;
}

.selected,
.found {
  color: black;
  font-weight: bold;
  font-size: 1.4rem;
}

JavaScript

const foundClass = 'found';
const addFoundClass = el => el.classList.add(foundClass);

const game = {
  pair: 5,
  containerSelector: document.getElementById('game'),
  nbCards() { return this.pair * 2 },
  cardClickHandler(event) {
    const card = event.srcElement;
    console.log(card);

    if (card === this.currentCard) {
      console.log('card already selected');
      return;
    }

    if (card.classList.contains(foundClass)) {
      console.log('card already found');
      return;
    }

    card.classList.toggle('selected');

    if (!_.isUndefined(this.currentCard)) {
      if (card.dataset.val === this.currentCard.dataset.val) {
        console.log('same card !!');
        addFoundClass(card);
        addFoundClass(this.currentCard);
        this.foundCards += 2;
      } else {
        console.log('not same card !!', this.currentCard.dataset.val, card.dataset.val);
      }
      setTimeout((function() {
        card.classList.remove('selected');
        this.currentCard.classList.remove('selected');
        this.currentCard = undefined;
      }).bind(this), 1000);
    } else {
      this.currentCard = card;
    }
    this.score += 1;
    this.updateScore();
    if (this.isGameOver()) {
      this.displayResult();
    }
  },
  cardTemplate:  '<div data-val="${value}" class="card"> ${value} </div>',
  generateCards() {
  	const range = x => _.range(x);
  	const cards = _.shuffle(range(this.pair).concat(range(this.pair)));
    const compiledCardTemplate = _.template(this.cardTemplate);
   
  	return cards.map(c => compiledCardTemplate({ value: c	}))
  	.join('');
  },
  start() {
    console.log('starting game');
    this.foundCards = 0;
    this.currentCard = undefined;
    this.score = 0;

    this.containerSelector.innerHTML = this.generateCards();

    const cards = this.containerSelector.querySelectorAll('.card');
    cards.forEach(c => c.addEventListener('click', this.cardClickHandler.bind(this)));
    
    this.updateScore();
  },
  currentCard:...