MemorizationGameFinal

In this example below you will see how to do a MemorizationGameFinal with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Szczepkowski, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Szczepkowski ©
  • HTML
  • CSS
  • JavaScript
    

/*Downloaded from https://www.codeseek.co/Szczepkowski/memorizationgamefinal-WvQvWY */
    table {
  width: 600px;
  height: 300px;
  transform: rotateY(180deg);
}
td {
  width: 25%;
  height: 50%;
  text-align: center;
  color: rgba(1, 1, 1, 0);
  background-color: rgb(224, 114, 86);
}
.flipper {
  transform: rotateY(180deg);
  transition: transform 1s, color 0s 0.3s;
  color: rgba(0, 0, 0, 1);
}



/*Downloaded from https://www.codeseek.co/Szczepkowski/memorizationgamefinal-WvQvWY */
    Array.prototype.shuffle = function() {
  for(var i = this.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random()*(i+1));
    var temp = this[i];
    this[i] = this[j];
    this[j] = temp;
  }
  return this;
};

Array.prototype.duplicate = function() {
    var copy = this.slice(0);
    return this.concat(copy);
};

var Model = {
  fields: ["DOG","CAT","HORSE","DUCK"],
  player_fields: [],
};

var View = {
  createView: function(numRows, numColumns) {
    var table = document.createElement("table");
    for (var i = 0; i < numRows; i++){
      var row = table.insertRow();
      for (var j = 0; j < numColumns; j++) {
        var cell = row.insertCell();
        cell.field = Model.fields[i*numColumns+j];
      }
    }
    return table;
  }
};

var Controller = {
  init: function(game) {
    Controller.model = game;
    game.fields = game.fields.duplicate();
    game.fields = game.fields.shuffle();
    Controller.view = View.createView(2,4);
    Controller.view.addEventListener("click", Controller.action, false);
  },
  action: function(element) {
    var td = element.target;
    if(td.textContent !== "") { 
      alert("try another one");
    } else if (Model.player_fields.length % 2 == 0 || td.field == Model.player_fields[Model.player_fields.length-1]) {
      td.textContent = td.field;
      td.className = "flipper";
      Model.player_fields.push(td.field);
      Controller.quit_game();
      } else {
        var cells = document.getElementsByTagName("td");
        for (var i = 0; i < cells.length; i++) {
          if(cells[i].textContent == Model.player_fields[Model.player_fields.length-1]) {
            cells[i].textContent = "";
            cells[i].className = "";
            Model.player_fields.pop();
            return;
           }
        }
     } 
  },
  quit_game: function() {
		if(Model.player_fields.length == Model.fields.length) {
      Controller.view.removeEventListener("click", Controller.action, false);
      alert("Congrats");
    }
  }
};

Controller.init(Model);
document.body.appendChild(Controller.view);


Comments