add tile merging
[2048.git] / js / html_actuator.js
blob:a/js/html_actuator.js -> blob:b/js/html_actuator.js
--- a/js/html_actuator.js
+++ b/js/html_actuator.js
@@ -1,12 +1,16 @@
 function HTMLActuator() {
-  this.tileContainer = document.getElementsByClassName("tile-container")[0];
+  this.tileContainer  = document.getElementsByClassName("tile-container")[0];
+  this.gameContainer  = document.getElementsByClassName("game-container")[0];
+  this.scoreContainer = document.getElementsByClassName("score-container")[0];
+
+  this.score = 0;
 }
 
-HTMLActuator.prototype.actuate = function (grid) {
+HTMLActuator.prototype.actuate = function (grid, metadata) {
   var self = this;
 
   window.requestAnimationFrame(function () {
-    self.clearContainer();
+    self.clearContainer(self.tileContainer);
 
     grid.cells.forEach(function (column) {
       column.forEach(function (cell) {
@@ -15,12 +19,17 @@
         }
       });
     });
+
+    self.updateScore(metadata.score);
+
+    if (metadata.over) self.message(false); // You lose
+    if (metadata.won) self.message(true); // You win!
   });
 };
 
-HTMLActuator.prototype.clearContainer = function () {
-  while (this.tileContainer.firstChild) {
-    this.tileContainer.removeChild(this.tileContainer.firstChild);
+HTMLActuator.prototype.clearContainer = function (container) {
+  while (container.firstChild) {
+    container.removeChild(container.firstChild);
   }
 };
 
@@ -60,3 +69,25 @@
   return "tile-position-" + position.x + "-" + position.y;
 };
 
+HTMLActuator.prototype.updateScore = function (score) {
+  this.clearContainer(this.scoreContainer);
+
+  var difference = score - this.score;
+  this.score = score;
+
+  this.scoreContainer.textContent = this.score;
+
+  if (difference) {
+    var addition = document.createElement("div");
+    addition.classList.add("score-addition");
+    addition.textContent = "+" + difference;
+
+    this.scoreContainer.appendChild(addition);
+  }
+};
+
+HTMLActuator.prototype.message = function (won) {
+  var type = won ? "game-won" : "game-over";
+  this.gameContainer.classList.add(type);
+};
+

comments